ionic.bundle.js 2.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569
  1. /*!
  2. * ionic.bundle.js is a concatenation of:
  3. * ionic.js, angular.js, angular-animate.js,
  4. * angular-sanitize.js, angular-ui-router.js,
  5. * and ionic-angular.js
  6. */
  7. /*!
  8. * Copyright 2015 Drifty Co.
  9. * http://drifty.com/
  10. *
  11. * Ionic, v1.3.1
  12. * A powerful HTML5 mobile app framework.
  13. * http://ionicframework.com/
  14. *
  15. * By @maxlynch, @benjsperry, @adamdbradley <3
  16. *
  17. * Licensed under the MIT license. Please see LICENSE for more information.
  18. *
  19. */
  20. (function() {
  21. // Create global ionic obj and its namespaces
  22. // build processes may have already created an ionic obj
  23. window.ionic = window.ionic || {};
  24. window.ionic.views = {};
  25. window.ionic.version = '1.3.1';
  26. (function (ionic) {
  27. ionic.DelegateService = function(methodNames) {
  28. if (methodNames.indexOf('$getByHandle') > -1) {
  29. throw new Error("Method '$getByHandle' is implicitly added to each delegate service. Do not list it as a method.");
  30. }
  31. function trueFn() { return true; }
  32. return ['$log', function($log) {
  33. /*
  34. * Creates a new object that will have all the methodNames given,
  35. * and call them on the given the controller instance matching given
  36. * handle.
  37. * The reason we don't just let $getByHandle return the controller instance
  38. * itself is that the controller instance might not exist yet.
  39. *
  40. * We want people to be able to do
  41. * `var instance = $ionicScrollDelegate.$getByHandle('foo')` on controller
  42. * instantiation, but on controller instantiation a child directive
  43. * may not have been compiled yet!
  44. *
  45. * So this is our way of solving this problem: we create an object
  46. * that will only try to fetch the controller with given handle
  47. * once the methods are actually called.
  48. */
  49. function DelegateInstance(instances, handle) {
  50. this._instances = instances;
  51. this.handle = handle;
  52. }
  53. methodNames.forEach(function(methodName) {
  54. DelegateInstance.prototype[methodName] = instanceMethodCaller(methodName);
  55. });
  56. /**
  57. * The delegate service (eg $ionicNavBarDelegate) is just an instance
  58. * with a non-defined handle, a couple extra methods for registering
  59. * and narrowing down to a specific handle.
  60. */
  61. function DelegateService() {
  62. this._instances = [];
  63. }
  64. DelegateService.prototype = DelegateInstance.prototype;
  65. DelegateService.prototype._registerInstance = function(instance, handle, filterFn) {
  66. var instances = this._instances;
  67. instance.$$delegateHandle = handle;
  68. instance.$$filterFn = filterFn || trueFn;
  69. instances.push(instance);
  70. return function deregister() {
  71. var index = instances.indexOf(instance);
  72. if (index !== -1) {
  73. instances.splice(index, 1);
  74. }
  75. };
  76. };
  77. DelegateService.prototype.$getByHandle = function(handle) {
  78. return new DelegateInstance(this._instances, handle);
  79. };
  80. return new DelegateService();
  81. function instanceMethodCaller(methodName) {
  82. return function caller() {
  83. var handle = this.handle;
  84. var args = arguments;
  85. var foundInstancesCount = 0;
  86. var returnValue;
  87. this._instances.forEach(function(instance) {
  88. if ((!handle || handle == instance.$$delegateHandle) && instance.$$filterFn(instance)) {
  89. foundInstancesCount++;
  90. var ret = instance[methodName].apply(instance, args);
  91. //Only return the value from the first call
  92. if (foundInstancesCount === 1) {
  93. returnValue = ret;
  94. }
  95. }
  96. });
  97. if (!foundInstancesCount && handle) {
  98. return $log.warn(
  99. 'Delegate for handle "' + handle + '" could not find a ' +
  100. 'corresponding element with delegate-handle="' + handle + '"! ' +
  101. methodName + '() was not called!\n' +
  102. 'Possible cause: If you are calling ' + methodName + '() immediately, and ' +
  103. 'your element with delegate-handle="' + handle + '" is a child of your ' +
  104. 'controller, then your element may not be compiled yet. Put a $timeout ' +
  105. 'around your call to ' + methodName + '() and try again.'
  106. );
  107. }
  108. return returnValue;
  109. };
  110. }
  111. }];
  112. };
  113. })(window.ionic);
  114. (function(window, document, ionic) {
  115. var readyCallbacks = [];
  116. var isDomReady = document.readyState === 'complete' || document.readyState === 'interactive';
  117. function domReady() {
  118. isDomReady = true;
  119. for (var x = 0; x < readyCallbacks.length; x++) {
  120. ionic.requestAnimationFrame(readyCallbacks[x]);
  121. }
  122. readyCallbacks = [];
  123. document.removeEventListener('DOMContentLoaded', domReady);
  124. }
  125. if (!isDomReady) {
  126. document.addEventListener('DOMContentLoaded', domReady);
  127. }
  128. // From the man himself, Mr. Paul Irish.
  129. // The requestAnimationFrame polyfill
  130. // Put it on window just to preserve its context
  131. // without having to use .call
  132. window._rAF = (function() {
  133. return window.requestAnimationFrame ||
  134. window.webkitRequestAnimationFrame ||
  135. window.mozRequestAnimationFrame ||
  136. function(callback) {
  137. window.setTimeout(callback, 16);
  138. };
  139. })();
  140. var cancelAnimationFrame = window.cancelAnimationFrame ||
  141. window.webkitCancelAnimationFrame ||
  142. window.mozCancelAnimationFrame ||
  143. window.webkitCancelRequestAnimationFrame;
  144. /**
  145. * @ngdoc utility
  146. * @name ionic.DomUtil
  147. * @module ionic
  148. */
  149. ionic.DomUtil = {
  150. //Call with proper context
  151. /**
  152. * @ngdoc method
  153. * @name ionic.DomUtil#requestAnimationFrame
  154. * @alias ionic.requestAnimationFrame
  155. * @description Calls [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame), or a polyfill if not available.
  156. * @param {function} callback The function to call when the next frame
  157. * happens.
  158. */
  159. requestAnimationFrame: function(cb) {
  160. return window._rAF(cb);
  161. },
  162. cancelAnimationFrame: function(requestId) {
  163. cancelAnimationFrame(requestId);
  164. },
  165. /**
  166. * @ngdoc method
  167. * @name ionic.DomUtil#animationFrameThrottle
  168. * @alias ionic.animationFrameThrottle
  169. * @description
  170. * When given a callback, if that callback is called 100 times between
  171. * animation frames, adding Throttle will make it only run the last of
  172. * the 100 calls.
  173. *
  174. * @param {function} callback a function which will be throttled to
  175. * requestAnimationFrame
  176. * @returns {function} A function which will then call the passed in callback.
  177. * The passed in callback will receive the context the returned function is
  178. * called with.
  179. */
  180. animationFrameThrottle: function(cb) {
  181. var args, isQueued, context;
  182. return function() {
  183. args = arguments;
  184. context = this;
  185. if (!isQueued) {
  186. isQueued = true;
  187. ionic.requestAnimationFrame(function() {
  188. cb.apply(context, args);
  189. isQueued = false;
  190. });
  191. }
  192. };
  193. },
  194. contains: function(parentNode, otherNode) {
  195. var current = otherNode;
  196. while (current) {
  197. if (current === parentNode) return true;
  198. current = current.parentNode;
  199. }
  200. },
  201. /**
  202. * @ngdoc method
  203. * @name ionic.DomUtil#getPositionInParent
  204. * @description
  205. * Find an element's scroll offset within its container.
  206. * @param {DOMElement} element The element to find the offset of.
  207. * @returns {object} A position object with the following properties:
  208. * - `{number}` `left` The left offset of the element.
  209. * - `{number}` `top` The top offset of the element.
  210. */
  211. getPositionInParent: function(el) {
  212. return {
  213. left: el.offsetLeft,
  214. top: el.offsetTop
  215. };
  216. },
  217. getOffsetTop: function(el) {
  218. var curtop = 0;
  219. if (el.offsetParent) {
  220. do {
  221. curtop += el.offsetTop;
  222. el = el.offsetParent;
  223. } while (el)
  224. return curtop;
  225. }
  226. },
  227. /**
  228. * @ngdoc method
  229. * @name ionic.DomUtil#ready
  230. * @description
  231. * Call a function when the DOM is ready, or if it is already ready
  232. * call the function immediately.
  233. * @param {function} callback The function to be called.
  234. */
  235. ready: function(cb) {
  236. if (isDomReady) {
  237. ionic.requestAnimationFrame(cb);
  238. } else {
  239. readyCallbacks.push(cb);
  240. }
  241. },
  242. /**
  243. * @ngdoc method
  244. * @name ionic.DomUtil#getTextBounds
  245. * @description
  246. * Get a rect representing the bounds of the given textNode.
  247. * @param {DOMElement} textNode The textNode to find the bounds of.
  248. * @returns {object} An object representing the bounds of the node. Properties:
  249. * - `{number}` `left` The left position of the textNode.
  250. * - `{number}` `right` The right position of the textNode.
  251. * - `{number}` `top` The top position of the textNode.
  252. * - `{number}` `bottom` The bottom position of the textNode.
  253. * - `{number}` `width` The width of the textNode.
  254. * - `{number}` `height` The height of the textNode.
  255. */
  256. getTextBounds: function(textNode) {
  257. if (document.createRange) {
  258. var range = document.createRange();
  259. range.selectNodeContents(textNode);
  260. if (range.getBoundingClientRect) {
  261. var rect = range.getBoundingClientRect();
  262. if (rect) {
  263. var sx = window.scrollX;
  264. var sy = window.scrollY;
  265. return {
  266. top: rect.top + sy,
  267. left: rect.left + sx,
  268. right: rect.left + sx + rect.width,
  269. bottom: rect.top + sy + rect.height,
  270. width: rect.width,
  271. height: rect.height
  272. };
  273. }
  274. }
  275. }
  276. return null;
  277. },
  278. /**
  279. * @ngdoc method
  280. * @name ionic.DomUtil#getChildIndex
  281. * @description
  282. * Get the first index of a child node within the given element of the
  283. * specified type.
  284. * @param {DOMElement} element The element to find the index of.
  285. * @param {string} type The nodeName to match children of element against.
  286. * @returns {number} The index, or -1, of a child with nodeName matching type.
  287. */
  288. getChildIndex: function(element, type) {
  289. if (type) {
  290. var ch = element.parentNode.children;
  291. var c;
  292. for (var i = 0, k = 0, j = ch.length; i < j; i++) {
  293. c = ch[i];
  294. if (c.nodeName && c.nodeName.toLowerCase() == type) {
  295. if (c == element) {
  296. return k;
  297. }
  298. k++;
  299. }
  300. }
  301. }
  302. return Array.prototype.slice.call(element.parentNode.children).indexOf(element);
  303. },
  304. /**
  305. * @private
  306. */
  307. swapNodes: function(src, dest) {
  308. dest.parentNode.insertBefore(src, dest);
  309. },
  310. elementIsDescendant: function(el, parent, stopAt) {
  311. var current = el;
  312. do {
  313. if (current === parent) return true;
  314. current = current.parentNode;
  315. } while (current && current !== stopAt);
  316. return false;
  317. },
  318. /**
  319. * @ngdoc method
  320. * @name ionic.DomUtil#getParentWithClass
  321. * @param {DOMElement} element
  322. * @param {string} className
  323. * @returns {DOMElement} The closest parent of element matching the
  324. * className, or null.
  325. */
  326. getParentWithClass: function(e, className, depth) {
  327. depth = depth || 10;
  328. while (e.parentNode && depth--) {
  329. if (e.parentNode.classList && e.parentNode.classList.contains(className)) {
  330. return e.parentNode;
  331. }
  332. e = e.parentNode;
  333. }
  334. return null;
  335. },
  336. /**
  337. * @ngdoc method
  338. * @name ionic.DomUtil#getParentOrSelfWithClass
  339. * @param {DOMElement} element
  340. * @param {string} className
  341. * @returns {DOMElement} The closest parent or self matching the
  342. * className, or null.
  343. */
  344. getParentOrSelfWithClass: function(e, className, depth) {
  345. depth = depth || 10;
  346. while (e && depth--) {
  347. if (e.classList && e.classList.contains(className)) {
  348. return e;
  349. }
  350. e = e.parentNode;
  351. }
  352. return null;
  353. },
  354. /**
  355. * @ngdoc method
  356. * @name ionic.DomUtil#rectContains
  357. * @param {number} x
  358. * @param {number} y
  359. * @param {number} x1
  360. * @param {number} y1
  361. * @param {number} x2
  362. * @param {number} y2
  363. * @returns {boolean} Whether {x,y} fits within the rectangle defined by
  364. * {x1,y1,x2,y2}.
  365. */
  366. rectContains: function(x, y, x1, y1, x2, y2) {
  367. if (x < x1 || x > x2) return false;
  368. if (y < y1 || y > y2) return false;
  369. return true;
  370. },
  371. /**
  372. * @ngdoc method
  373. * @name ionic.DomUtil#blurAll
  374. * @description
  375. * Blurs any currently focused input element
  376. * @returns {DOMElement} The element blurred or null
  377. */
  378. blurAll: function() {
  379. if (document.activeElement && document.activeElement != document.body) {
  380. document.activeElement.blur();
  381. return document.activeElement;
  382. }
  383. return null;
  384. },
  385. cachedAttr: function(ele, key, value) {
  386. ele = ele && ele.length && ele[0] || ele;
  387. if (ele && ele.setAttribute) {
  388. var dataKey = '$attr-' + key;
  389. if (arguments.length > 2) {
  390. if (ele[dataKey] !== value) {
  391. ele.setAttribute(key, value);
  392. ele[dataKey] = value;
  393. }
  394. } else if (typeof ele[dataKey] == 'undefined') {
  395. ele[dataKey] = ele.getAttribute(key);
  396. }
  397. return ele[dataKey];
  398. }
  399. },
  400. cachedStyles: function(ele, styles) {
  401. ele = ele && ele.length && ele[0] || ele;
  402. if (ele && ele.style) {
  403. for (var prop in styles) {
  404. if (ele['$style-' + prop] !== styles[prop]) {
  405. ele.style[prop] = ele['$style-' + prop] = styles[prop];
  406. }
  407. }
  408. }
  409. }
  410. };
  411. //Shortcuts
  412. ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame;
  413. ionic.cancelAnimationFrame = ionic.DomUtil.cancelAnimationFrame;
  414. ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle;
  415. })(window, document, ionic);
  416. /**
  417. * ion-events.js
  418. *
  419. * Author: Max Lynch <max@drifty.com>
  420. *
  421. * Framework events handles various mobile browser events, and
  422. * detects special events like tap/swipe/etc. and emits them
  423. * as custom events that can be used in an app.
  424. *
  425. * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys!
  426. */
  427. (function(ionic) {
  428. // Custom event polyfill
  429. ionic.CustomEvent = (function() {
  430. if( typeof window.CustomEvent === 'function' ) return CustomEvent;
  431. var customEvent = function(event, params) {
  432. var evt;
  433. params = params || {
  434. bubbles: false,
  435. cancelable: false,
  436. detail: undefined
  437. };
  438. try {
  439. evt = document.createEvent("CustomEvent");
  440. evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  441. } catch (error) {
  442. // fallback for browsers that don't support createEvent('CustomEvent')
  443. evt = document.createEvent("Event");
  444. for (var param in params) {
  445. evt[param] = params[param];
  446. }
  447. evt.initEvent(event, params.bubbles, params.cancelable);
  448. }
  449. return evt;
  450. };
  451. customEvent.prototype = window.Event.prototype;
  452. return customEvent;
  453. })();
  454. /**
  455. * @ngdoc utility
  456. * @name ionic.EventController
  457. * @module ionic
  458. */
  459. ionic.EventController = {
  460. VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'],
  461. /**
  462. * @ngdoc method
  463. * @name ionic.EventController#trigger
  464. * @alias ionic.trigger
  465. * @param {string} eventType The event to trigger.
  466. * @param {object} data The data for the event. Hint: pass in
  467. * `{target: targetElement}`
  468. * @param {boolean=} bubbles Whether the event should bubble up the DOM.
  469. * @param {boolean=} cancelable Whether the event should be cancelable.
  470. */
  471. // Trigger a new event
  472. trigger: function(eventType, data, bubbles, cancelable) {
  473. var event = new ionic.CustomEvent(eventType, {
  474. detail: data,
  475. bubbles: !!bubbles,
  476. cancelable: !!cancelable
  477. });
  478. // Make sure to trigger the event on the given target, or dispatch it from
  479. // the window if we don't have an event target
  480. data && data.target && data.target.dispatchEvent && data.target.dispatchEvent(event) || window.dispatchEvent(event);
  481. },
  482. /**
  483. * @ngdoc method
  484. * @name ionic.EventController#on
  485. * @alias ionic.on
  486. * @description Listen to an event on an element.
  487. * @param {string} type The event to listen for.
  488. * @param {function} callback The listener to be called.
  489. * @param {DOMElement} element The element to listen for the event on.
  490. */
  491. on: function(type, callback, element) {
  492. var e = element || window;
  493. // Bind a gesture if it's a virtual event
  494. for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) {
  495. if(type == this.VIRTUALIZED_EVENTS[i]) {
  496. var gesture = new ionic.Gesture(element);
  497. gesture.on(type, callback);
  498. return gesture;
  499. }
  500. }
  501. // Otherwise bind a normal event
  502. e.addEventListener(type, callback);
  503. },
  504. /**
  505. * @ngdoc method
  506. * @name ionic.EventController#off
  507. * @alias ionic.off
  508. * @description Remove an event listener.
  509. * @param {string} type
  510. * @param {function} callback
  511. * @param {DOMElement} element
  512. */
  513. off: function(type, callback, element) {
  514. element.removeEventListener(type, callback);
  515. },
  516. /**
  517. * @ngdoc method
  518. * @name ionic.EventController#onGesture
  519. * @alias ionic.onGesture
  520. * @description Add an event listener for a gesture on an element.
  521. *
  522. * Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)):
  523. *
  524. * `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/>
  525. * `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/>
  526. * `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, <br/>
  527. * `touch`, `release`
  528. *
  529. * @param {string} eventType The gesture event to listen for.
  530. * @param {function(e)} callback The function to call when the gesture
  531. * happens.
  532. * @param {DOMElement} element The angular element to listen for the event on.
  533. * @param {object} options object.
  534. * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).
  535. */
  536. onGesture: function(type, callback, element, options) {
  537. var gesture = new ionic.Gesture(element, options);
  538. gesture.on(type, callback);
  539. return gesture;
  540. },
  541. /**
  542. * @ngdoc method
  543. * @name ionic.EventController#offGesture
  544. * @alias ionic.offGesture
  545. * @description Remove an event listener for a gesture created on an element.
  546. * @param {ionic.Gesture} gesture The gesture that should be removed.
  547. * @param {string} eventType The gesture event to remove the listener for.
  548. * @param {function(e)} callback The listener to remove.
  549. */
  550. offGesture: function(gesture, type, callback) {
  551. gesture && gesture.off(type, callback);
  552. },
  553. handlePopState: function() {}
  554. };
  555. // Map some convenient top-level functions for event handling
  556. ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); };
  557. ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); };
  558. ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); };
  559. ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); };
  560. ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); };
  561. })(window.ionic);
  562. /* eslint camelcase:0 */
  563. /**
  564. * Simple gesture controllers with some common gestures that emit
  565. * gesture events.
  566. *
  567. * Ported from github.com/EightMedia/hammer.js Gestures - thanks!
  568. */
  569. (function(ionic) {
  570. /**
  571. * ionic.Gestures
  572. * use this to create instances
  573. * @param {HTMLElement} element
  574. * @param {Object} options
  575. * @returns {ionic.Gestures.Instance}
  576. * @constructor
  577. */
  578. ionic.Gesture = function(element, options) {
  579. return new ionic.Gestures.Instance(element, options || {});
  580. };
  581. ionic.Gestures = {};
  582. // default settings
  583. ionic.Gestures.defaults = {
  584. // add css to the element to prevent the browser from doing
  585. // its native behavior. this doesnt prevent the scrolling,
  586. // but cancels the contextmenu, tap highlighting etc
  587. // set to false to disable this
  588. stop_browser_behavior: 'disable-user-behavior'
  589. };
  590. // detect touchevents
  591. ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;
  592. ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window);
  593. // dont use mouseevents on mobile devices
  594. ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i;
  595. ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX);
  596. // eventtypes per touchevent (start, move, end)
  597. // are filled by ionic.Gestures.event.determineEventTypes on setup
  598. ionic.Gestures.EVENT_TYPES = {};
  599. // direction defines
  600. ionic.Gestures.DIRECTION_DOWN = 'down';
  601. ionic.Gestures.DIRECTION_LEFT = 'left';
  602. ionic.Gestures.DIRECTION_UP = 'up';
  603. ionic.Gestures.DIRECTION_RIGHT = 'right';
  604. // pointer type
  605. ionic.Gestures.POINTER_MOUSE = 'mouse';
  606. ionic.Gestures.POINTER_TOUCH = 'touch';
  607. ionic.Gestures.POINTER_PEN = 'pen';
  608. // touch event defines
  609. ionic.Gestures.EVENT_START = 'start';
  610. ionic.Gestures.EVENT_MOVE = 'move';
  611. ionic.Gestures.EVENT_END = 'end';
  612. // hammer document where the base events are added at
  613. ionic.Gestures.DOCUMENT = window.document;
  614. // plugins namespace
  615. ionic.Gestures.plugins = {};
  616. // if the window events are set...
  617. ionic.Gestures.READY = false;
  618. /**
  619. * setup events to detect gestures on the document
  620. */
  621. function setup() {
  622. if(ionic.Gestures.READY) {
  623. return;
  624. }
  625. // find what eventtypes we add listeners to
  626. ionic.Gestures.event.determineEventTypes();
  627. // Register all gestures inside ionic.Gestures.gestures
  628. for(var name in ionic.Gestures.gestures) {
  629. if(ionic.Gestures.gestures.hasOwnProperty(name)) {
  630. ionic.Gestures.detection.register(ionic.Gestures.gestures[name]);
  631. }
  632. }
  633. // Add touch events on the document
  634. ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect);
  635. ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect);
  636. // ionic.Gestures is ready...!
  637. ionic.Gestures.READY = true;
  638. }
  639. /**
  640. * create new hammer instance
  641. * all methods should return the instance itself, so it is chainable.
  642. * @param {HTMLElement} element
  643. * @param {Object} [options={}]
  644. * @returns {ionic.Gestures.Instance}
  645. * @name Gesture.Instance
  646. * @constructor
  647. */
  648. ionic.Gestures.Instance = function(element, options) {
  649. var self = this;
  650. // A null element was passed into the instance, which means
  651. // whatever lookup was done to find this element failed to find it
  652. // so we can't listen for events on it.
  653. if(element === null) {
  654. void 0;
  655. return this;
  656. }
  657. // setup ionic.GesturesJS window events and register all gestures
  658. // this also sets up the default options
  659. setup();
  660. this.element = element;
  661. // start/stop detection option
  662. this.enabled = true;
  663. // merge options
  664. this.options = ionic.Gestures.utils.extend(
  665. ionic.Gestures.utils.extend({}, ionic.Gestures.defaults),
  666. options || {});
  667. // add some css to the element to prevent the browser from doing its native behavoir
  668. if(this.options.stop_browser_behavior) {
  669. ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);
  670. }
  671. // start detection on touchstart
  672. ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) {
  673. if(self.enabled) {
  674. ionic.Gestures.detection.startDetect(self, ev);
  675. }
  676. });
  677. // return instance
  678. return this;
  679. };
  680. ionic.Gestures.Instance.prototype = {
  681. /**
  682. * bind events to the instance
  683. * @param {String} gesture
  684. * @param {Function} handler
  685. * @returns {ionic.Gestures.Instance}
  686. */
  687. on: function onEvent(gesture, handler){
  688. var gestures = gesture.split(' ');
  689. for(var t = 0; t < gestures.length; t++) {
  690. this.element.addEventListener(gestures[t], handler, false);
  691. }
  692. return this;
  693. },
  694. /**
  695. * unbind events to the instance
  696. * @param {String} gesture
  697. * @param {Function} handler
  698. * @returns {ionic.Gestures.Instance}
  699. */
  700. off: function offEvent(gesture, handler){
  701. var gestures = gesture.split(' ');
  702. for(var t = 0; t < gestures.length; t++) {
  703. this.element.removeEventListener(gestures[t], handler, false);
  704. }
  705. return this;
  706. },
  707. /**
  708. * trigger gesture event
  709. * @param {String} gesture
  710. * @param {Object} eventData
  711. * @returns {ionic.Gestures.Instance}
  712. */
  713. trigger: function triggerEvent(gesture, eventData){
  714. // create DOM event
  715. var event = ionic.Gestures.DOCUMENT.createEvent('Event');
  716. event.initEvent(gesture, true, true);
  717. event.gesture = eventData;
  718. // trigger on the target if it is in the instance element,
  719. // this is for event delegation tricks
  720. var element = this.element;
  721. if(ionic.Gestures.utils.hasParent(eventData.target, element)) {
  722. element = eventData.target;
  723. }
  724. element.dispatchEvent(event);
  725. return this;
  726. },
  727. /**
  728. * enable of disable hammer.js detection
  729. * @param {Boolean} state
  730. * @returns {ionic.Gestures.Instance}
  731. */
  732. enable: function enable(state) {
  733. this.enabled = state;
  734. return this;
  735. }
  736. };
  737. /**
  738. * this holds the last move event,
  739. * used to fix empty touchend issue
  740. * see the onTouch event for an explanation
  741. * type {Object}
  742. */
  743. var last_move_event = null;
  744. /**
  745. * when the mouse is hold down, this is true
  746. * type {Boolean}
  747. */
  748. var enable_detect = false;
  749. /**
  750. * when touch events have been fired, this is true
  751. * type {Boolean}
  752. */
  753. var touch_triggered = false;
  754. ionic.Gestures.event = {
  755. /**
  756. * simple addEventListener
  757. * @param {HTMLElement} element
  758. * @param {String} type
  759. * @param {Function} handler
  760. */
  761. bindDom: function(element, type, handler) {
  762. var types = type.split(' ');
  763. for(var t = 0; t < types.length; t++) {
  764. element.addEventListener(types[t], handler, false);
  765. }
  766. },
  767. /**
  768. * touch events with mouse fallback
  769. * @param {HTMLElement} element
  770. * @param {String} eventType like ionic.Gestures.EVENT_MOVE
  771. * @param {Function} handler
  772. */
  773. onTouch: function onTouch(element, eventType, handler) {
  774. var self = this;
  775. this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {
  776. var sourceEventType = ev.type.toLowerCase();
  777. // onmouseup, but when touchend has been fired we do nothing.
  778. // this is for touchdevices which also fire a mouseup on touchend
  779. if(sourceEventType.match(/mouse/) && touch_triggered) {
  780. return;
  781. }
  782. // mousebutton must be down or a touch event
  783. else if( sourceEventType.match(/touch/) || // touch events are always on screen
  784. sourceEventType.match(/pointerdown/) || // pointerevents touch
  785. (sourceEventType.match(/mouse/) && ev.which === 1) // mouse is pressed
  786. ){
  787. enable_detect = true;
  788. }
  789. // mouse isn't pressed
  790. else if(sourceEventType.match(/mouse/) && ev.which !== 1) {
  791. enable_detect = false;
  792. }
  793. // we are in a touch event, set the touch triggered bool to true,
  794. // this for the conflicts that may occur on ios and android
  795. if(sourceEventType.match(/touch|pointer/)) {
  796. touch_triggered = true;
  797. }
  798. // count the total touches on the screen
  799. var count_touches = 0;
  800. // when touch has been triggered in this detection session
  801. // and we are now handling a mouse event, we stop that to prevent conflicts
  802. if(enable_detect) {
  803. // update pointerevent
  804. if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) {
  805. count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);
  806. }
  807. // touch
  808. else if(sourceEventType.match(/touch/)) {
  809. count_touches = ev.touches.length;
  810. }
  811. // mouse
  812. else if(!touch_triggered) {
  813. count_touches = sourceEventType.match(/up/) ? 0 : 1;
  814. }
  815. // if we are in a end event, but when we remove one touch and
  816. // we still have enough, set eventType to move
  817. if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) {
  818. eventType = ionic.Gestures.EVENT_MOVE;
  819. }
  820. // no touches, force the end event
  821. else if(!count_touches) {
  822. eventType = ionic.Gestures.EVENT_END;
  823. }
  824. // store the last move event
  825. if(count_touches || last_move_event === null) {
  826. last_move_event = ev;
  827. }
  828. // trigger the handler
  829. handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev));
  830. // remove pointerevent from list
  831. if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) {
  832. count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);
  833. }
  834. }
  835. //debug(sourceEventType +" "+ eventType);
  836. // on the end we reset everything
  837. if(!count_touches) {
  838. last_move_event = null;
  839. enable_detect = false;
  840. touch_triggered = false;
  841. ionic.Gestures.PointerEvent.reset();
  842. }
  843. });
  844. },
  845. /**
  846. * we have different events for each device/browser
  847. * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant
  848. */
  849. determineEventTypes: function determineEventTypes() {
  850. // determine the eventtype we want to set
  851. var types;
  852. // pointerEvents magic
  853. if(ionic.Gestures.HAS_POINTEREVENTS) {
  854. types = ionic.Gestures.PointerEvent.getEvents();
  855. }
  856. // on Android, iOS, blackberry, windows mobile we dont want any mouseevents
  857. else if(ionic.Gestures.NO_MOUSEEVENTS) {
  858. types = [
  859. 'touchstart',
  860. 'touchmove',
  861. 'touchend touchcancel'];
  862. }
  863. // for non pointer events browsers and mixed browsers,
  864. // like chrome on windows8 touch laptop
  865. else {
  866. types = [
  867. 'touchstart mousedown',
  868. 'touchmove mousemove',
  869. 'touchend touchcancel mouseup'];
  870. }
  871. ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0];
  872. ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1];
  873. ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2];
  874. },
  875. /**
  876. * create touchlist depending on the event
  877. * @param {Object} ev
  878. * @param {String} eventType used by the fakemultitouch plugin
  879. */
  880. getTouchList: function getTouchList(ev/*, eventType*/) {
  881. // get the fake pointerEvent touchlist
  882. if(ionic.Gestures.HAS_POINTEREVENTS) {
  883. return ionic.Gestures.PointerEvent.getTouchList();
  884. }
  885. // get the touchlist
  886. else if(ev.touches) {
  887. return ev.touches;
  888. }
  889. // make fake touchlist from mouse position
  890. else {
  891. ev.identifier = 1;
  892. return [ev];
  893. }
  894. },
  895. /**
  896. * collect event data for ionic.Gestures js
  897. * @param {HTMLElement} element
  898. * @param {String} eventType like ionic.Gestures.EVENT_MOVE
  899. * @param {Object} eventData
  900. */
  901. collectEventData: function collectEventData(element, eventType, touches, ev) {
  902. // find out pointerType
  903. var pointerType = ionic.Gestures.POINTER_TOUCH;
  904. if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {
  905. pointerType = ionic.Gestures.POINTER_MOUSE;
  906. }
  907. return {
  908. center: ionic.Gestures.utils.getCenter(touches),
  909. timeStamp: new Date().getTime(),
  910. target: ev.target,
  911. touches: touches,
  912. eventType: eventType,
  913. pointerType: pointerType,
  914. srcEvent: ev,
  915. /**
  916. * prevent the browser default actions
  917. * mostly used to disable scrolling of the browser
  918. */
  919. preventDefault: function() {
  920. if(this.srcEvent.preventManipulation) {
  921. this.srcEvent.preventManipulation();
  922. }
  923. if(this.srcEvent.preventDefault) {
  924. // this.srcEvent.preventDefault();
  925. }
  926. },
  927. /**
  928. * stop bubbling the event up to its parents
  929. */
  930. stopPropagation: function() {
  931. this.srcEvent.stopPropagation();
  932. },
  933. /**
  934. * immediately stop gesture detection
  935. * might be useful after a swipe was detected
  936. * @return {*}
  937. */
  938. stopDetect: function() {
  939. return ionic.Gestures.detection.stopDetect();
  940. }
  941. };
  942. }
  943. };
  944. ionic.Gestures.PointerEvent = {
  945. /**
  946. * holds all pointers
  947. * type {Object}
  948. */
  949. pointers: {},
  950. /**
  951. * get a list of pointers
  952. * @returns {Array} touchlist
  953. */
  954. getTouchList: function() {
  955. var self = this;
  956. var touchlist = [];
  957. // we can use forEach since pointerEvents only is in IE10
  958. Object.keys(self.pointers).sort().forEach(function(id) {
  959. touchlist.push(self.pointers[id]);
  960. });
  961. return touchlist;
  962. },
  963. /**
  964. * update the position of a pointer
  965. * @param {String} type ionic.Gestures.EVENT_END
  966. * @param {Object} pointerEvent
  967. */
  968. updatePointer: function(type, pointerEvent) {
  969. if(type == ionic.Gestures.EVENT_END) {
  970. this.pointers = {};
  971. }
  972. else {
  973. pointerEvent.identifier = pointerEvent.pointerId;
  974. this.pointers[pointerEvent.pointerId] = pointerEvent;
  975. }
  976. return Object.keys(this.pointers).length;
  977. },
  978. /**
  979. * check if ev matches pointertype
  980. * @param {String} pointerType ionic.Gestures.POINTER_MOUSE
  981. * @param {PointerEvent} ev
  982. */
  983. matchType: function(pointerType, ev) {
  984. if(!ev.pointerType) {
  985. return false;
  986. }
  987. var types = {};
  988. types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE);
  989. types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH);
  990. types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN);
  991. return types[pointerType];
  992. },
  993. /**
  994. * get events
  995. */
  996. getEvents: function() {
  997. return [
  998. 'pointerdown MSPointerDown',
  999. 'pointermove MSPointerMove',
  1000. 'pointerup pointercancel MSPointerUp MSPointerCancel'
  1001. ];
  1002. },
  1003. /**
  1004. * reset the list
  1005. */
  1006. reset: function() {
  1007. this.pointers = {};
  1008. }
  1009. };
  1010. ionic.Gestures.utils = {
  1011. /**
  1012. * extend method,
  1013. * also used for cloning when dest is an empty object
  1014. * @param {Object} dest
  1015. * @param {Object} src
  1016. * @param {Boolean} merge do a merge
  1017. * @returns {Object} dest
  1018. */
  1019. extend: function extend(dest, src, merge) {
  1020. for (var key in src) {
  1021. if(dest[key] !== undefined && merge) {
  1022. continue;
  1023. }
  1024. dest[key] = src[key];
  1025. }
  1026. return dest;
  1027. },
  1028. /**
  1029. * find if a node is in the given parent
  1030. * used for event delegation tricks
  1031. * @param {HTMLElement} node
  1032. * @param {HTMLElement} parent
  1033. * @returns {boolean} has_parent
  1034. */
  1035. hasParent: function(node, parent) {
  1036. while(node){
  1037. if(node == parent) {
  1038. return true;
  1039. }
  1040. node = node.parentNode;
  1041. }
  1042. return false;
  1043. },
  1044. /**
  1045. * get the center of all the touches
  1046. * @param {Array} touches
  1047. * @returns {Object} center
  1048. */
  1049. getCenter: function getCenter(touches) {
  1050. var valuesX = [], valuesY = [];
  1051. for(var t = 0, len = touches.length; t < len; t++) {
  1052. valuesX.push(touches[t].pageX);
  1053. valuesY.push(touches[t].pageY);
  1054. }
  1055. return {
  1056. pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),
  1057. pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)
  1058. };
  1059. },
  1060. /**
  1061. * calculate the velocity between two points
  1062. * @param {Number} delta_time
  1063. * @param {Number} delta_x
  1064. * @param {Number} delta_y
  1065. * @returns {Object} velocity
  1066. */
  1067. getVelocity: function getVelocity(delta_time, delta_x, delta_y) {
  1068. return {
  1069. x: Math.abs(delta_x / delta_time) || 0,
  1070. y: Math.abs(delta_y / delta_time) || 0
  1071. };
  1072. },
  1073. /**
  1074. * calculate the angle between two coordinates
  1075. * @param {Touch} touch1
  1076. * @param {Touch} touch2
  1077. * @returns {Number} angle
  1078. */
  1079. getAngle: function getAngle(touch1, touch2) {
  1080. var y = touch2.pageY - touch1.pageY,
  1081. x = touch2.pageX - touch1.pageX;
  1082. return Math.atan2(y, x) * 180 / Math.PI;
  1083. },
  1084. /**
  1085. * angle to direction define
  1086. * @param {Touch} touch1
  1087. * @param {Touch} touch2
  1088. * @returns {String} direction constant, like ionic.Gestures.DIRECTION_LEFT
  1089. */
  1090. getDirection: function getDirection(touch1, touch2) {
  1091. var x = Math.abs(touch1.pageX - touch2.pageX),
  1092. y = Math.abs(touch1.pageY - touch2.pageY);
  1093. if(x >= y) {
  1094. return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;
  1095. }
  1096. else {
  1097. return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;
  1098. }
  1099. },
  1100. /**
  1101. * calculate the distance between two touches
  1102. * @param {Touch} touch1
  1103. * @param {Touch} touch2
  1104. * @returns {Number} distance
  1105. */
  1106. getDistance: function getDistance(touch1, touch2) {
  1107. var x = touch2.pageX - touch1.pageX,
  1108. y = touch2.pageY - touch1.pageY;
  1109. return Math.sqrt((x * x) + (y * y));
  1110. },
  1111. /**
  1112. * calculate the scale factor between two touchLists (fingers)
  1113. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  1114. * @param {Array} start
  1115. * @param {Array} end
  1116. * @returns {Number} scale
  1117. */
  1118. getScale: function getScale(start, end) {
  1119. // need two fingers...
  1120. if(start.length >= 2 && end.length >= 2) {
  1121. return this.getDistance(end[0], end[1]) /
  1122. this.getDistance(start[0], start[1]);
  1123. }
  1124. return 1;
  1125. },
  1126. /**
  1127. * calculate the rotation degrees between two touchLists (fingers)
  1128. * @param {Array} start
  1129. * @param {Array} end
  1130. * @returns {Number} rotation
  1131. */
  1132. getRotation: function getRotation(start, end) {
  1133. // need two fingers
  1134. if(start.length >= 2 && end.length >= 2) {
  1135. return this.getAngle(end[1], end[0]) -
  1136. this.getAngle(start[1], start[0]);
  1137. }
  1138. return 0;
  1139. },
  1140. /**
  1141. * boolean if the direction is vertical
  1142. * @param {String} direction
  1143. * @returns {Boolean} is_vertical
  1144. */
  1145. isVertical: function isVertical(direction) {
  1146. return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN);
  1147. },
  1148. /**
  1149. * stop browser default behavior with css class
  1150. * @param {HtmlElement} element
  1151. * @param {Object} css_class
  1152. */
  1153. stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) {
  1154. // changed from making many style changes to just adding a preset classname
  1155. // less DOM manipulations, less code, and easier to control in the CSS side of things
  1156. // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method
  1157. if(element && element.classList) {
  1158. element.classList.add(css_class);
  1159. element.onselectstart = function() {
  1160. return false;
  1161. };
  1162. }
  1163. }
  1164. };
  1165. ionic.Gestures.detection = {
  1166. // contains all registred ionic.Gestures.gestures in the correct order
  1167. gestures: [],
  1168. // data of the current ionic.Gestures.gesture detection session
  1169. current: null,
  1170. // the previous ionic.Gestures.gesture session data
  1171. // is a full clone of the previous gesture.current object
  1172. previous: null,
  1173. // when this becomes true, no gestures are fired
  1174. stopped: false,
  1175. /**
  1176. * start ionic.Gestures.gesture detection
  1177. * @param {ionic.Gestures.Instance} inst
  1178. * @param {Object} eventData
  1179. */
  1180. startDetect: function startDetect(inst, eventData) {
  1181. // already busy with a ionic.Gestures.gesture detection on an element
  1182. if(this.current) {
  1183. return;
  1184. }
  1185. this.stopped = false;
  1186. this.current = {
  1187. inst: inst, // reference to ionic.GesturesInstance we're working for
  1188. startEvent: ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc
  1189. lastEvent: false, // last eventData
  1190. name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc
  1191. };
  1192. this.detect(eventData);
  1193. },
  1194. /**
  1195. * ionic.Gestures.gesture detection
  1196. * @param {Object} eventData
  1197. */
  1198. detect: function detect(eventData) {
  1199. if(!this.current || this.stopped) {
  1200. return null;
  1201. }
  1202. // extend event data with calculations about scale, distance etc
  1203. eventData = this.extendEventData(eventData);
  1204. // instance options
  1205. var inst_options = this.current.inst.options;
  1206. // call ionic.Gestures.gesture handlers
  1207. for(var g = 0, len = this.gestures.length; g < len; g++) {
  1208. var gesture = this.gestures[g];
  1209. // only when the instance options have enabled this gesture
  1210. if(!this.stopped && inst_options[gesture.name] !== false) {
  1211. // if a handler returns false, we stop with the detection
  1212. if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {
  1213. this.stopDetect();
  1214. break;
  1215. }
  1216. }
  1217. }
  1218. // store as previous event event
  1219. if(this.current) {
  1220. this.current.lastEvent = eventData;
  1221. }
  1222. // endevent, but not the last touch, so dont stop
  1223. if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length - 1) {
  1224. this.stopDetect();
  1225. }
  1226. return eventData;
  1227. },
  1228. /**
  1229. * clear the ionic.Gestures.gesture vars
  1230. * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected
  1231. * to stop other ionic.Gestures.gestures from being fired
  1232. */
  1233. stopDetect: function stopDetect() {
  1234. // clone current data to the store as the previous gesture
  1235. // used for the double tap gesture, since this is an other gesture detect session
  1236. this.previous = ionic.Gestures.utils.extend({}, this.current);
  1237. // reset the current
  1238. this.current = null;
  1239. // stopped!
  1240. this.stopped = true;
  1241. },
  1242. /**
  1243. * extend eventData for ionic.Gestures.gestures
  1244. * @param {Object} ev
  1245. * @returns {Object} ev
  1246. */
  1247. extendEventData: function extendEventData(ev) {
  1248. var startEv = this.current.startEvent;
  1249. // if the touches change, set the new touches over the startEvent touches
  1250. // this because touchevents don't have all the touches on touchstart, or the
  1251. // user must place his fingers at the EXACT same time on the screen, which is not realistic
  1252. // but, sometimes it happens that both fingers are touching at the EXACT same time
  1253. if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {
  1254. // extend 1 level deep to get the touchlist with the touch objects
  1255. startEv.touches = [];
  1256. for(var i = 0, len = ev.touches.length; i < len; i++) {
  1257. startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i]));
  1258. }
  1259. }
  1260. var delta_time = ev.timeStamp - startEv.timeStamp,
  1261. delta_x = ev.center.pageX - startEv.center.pageX,
  1262. delta_y = ev.center.pageY - startEv.center.pageY,
  1263. velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y);
  1264. ionic.Gestures.utils.extend(ev, {
  1265. deltaTime: delta_time,
  1266. deltaX: delta_x,
  1267. deltaY: delta_y,
  1268. velocityX: velocity.x,
  1269. velocityY: velocity.y,
  1270. distance: ionic.Gestures.utils.getDistance(startEv.center, ev.center),
  1271. angle: ionic.Gestures.utils.getAngle(startEv.center, ev.center),
  1272. direction: ionic.Gestures.utils.getDirection(startEv.center, ev.center),
  1273. scale: ionic.Gestures.utils.getScale(startEv.touches, ev.touches),
  1274. rotation: ionic.Gestures.utils.getRotation(startEv.touches, ev.touches),
  1275. startEvent: startEv
  1276. });
  1277. return ev;
  1278. },
  1279. /**
  1280. * register new gesture
  1281. * @param {Object} gesture object, see gestures.js for documentation
  1282. * @returns {Array} gestures
  1283. */
  1284. register: function register(gesture) {
  1285. // add an enable gesture options if there is no given
  1286. var options = gesture.defaults || {};
  1287. if(options[gesture.name] === undefined) {
  1288. options[gesture.name] = true;
  1289. }
  1290. // extend ionic.Gestures default options with the ionic.Gestures.gesture options
  1291. ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true);
  1292. // set its index
  1293. gesture.index = gesture.index || 1000;
  1294. // add ionic.Gestures.gesture to the list
  1295. this.gestures.push(gesture);
  1296. // sort the list by index
  1297. this.gestures.sort(function(a, b) {
  1298. if (a.index < b.index) {
  1299. return -1;
  1300. }
  1301. if (a.index > b.index) {
  1302. return 1;
  1303. }
  1304. return 0;
  1305. });
  1306. return this.gestures;
  1307. }
  1308. };
  1309. ionic.Gestures.gestures = ionic.Gestures.gestures || {};
  1310. /**
  1311. * Custom gestures
  1312. * ==============================
  1313. *
  1314. * Gesture object
  1315. * --------------------
  1316. * The object structure of a gesture:
  1317. *
  1318. * { name: 'mygesture',
  1319. * index: 1337,
  1320. * defaults: {
  1321. * mygesture_option: true
  1322. * }
  1323. * handler: function(type, ev, inst) {
  1324. * // trigger gesture event
  1325. * inst.trigger(this.name, ev);
  1326. * }
  1327. * }
  1328. * @param {String} name
  1329. * this should be the name of the gesture, lowercase
  1330. * it is also being used to disable/enable the gesture per instance config.
  1331. *
  1332. * @param {Number} [index=1000]
  1333. * the index of the gesture, where it is going to be in the stack of gestures detection
  1334. * like when you build an gesture that depends on the drag gesture, it is a good
  1335. * idea to place it after the index of the drag gesture.
  1336. *
  1337. * @param {Object} [defaults={}]
  1338. * the default settings of the gesture. these are added to the instance settings,
  1339. * and can be overruled per instance. you can also add the name of the gesture,
  1340. * but this is also added by default (and set to true).
  1341. *
  1342. * @param {Function} handler
  1343. * this handles the gesture detection of your custom gesture and receives the
  1344. * following arguments:
  1345. *
  1346. * @param {Object} eventData
  1347. * event data containing the following properties:
  1348. * timeStamp {Number} time the event occurred
  1349. * target {HTMLElement} target element
  1350. * touches {Array} touches (fingers, pointers, mouse) on the screen
  1351. * pointerType {String} kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH
  1352. * center {Object} center position of the touches. contains pageX and pageY
  1353. * deltaTime {Number} the total time of the touches in the screen
  1354. * deltaX {Number} the delta on x axis we haved moved
  1355. * deltaY {Number} the delta on y axis we haved moved
  1356. * velocityX {Number} the velocity on the x
  1357. * velocityY {Number} the velocity on y
  1358. * angle {Number} the angle we are moving
  1359. * direction {String} the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT
  1360. * distance {Number} the distance we haved moved
  1361. * scale {Number} scaling of the touches, needs 2 touches
  1362. * rotation {Number} rotation of the touches, needs 2 touches *
  1363. * eventType {String} matches ionic.Gestures.EVENT_START|MOVE|END
  1364. * srcEvent {Object} the source event, like TouchStart or MouseDown *
  1365. * startEvent {Object} contains the same properties as above,
  1366. * but from the first touch. this is used to calculate
  1367. * distances, deltaTime, scaling etc
  1368. *
  1369. * @param {ionic.Gestures.Instance} inst
  1370. * the instance we are doing the detection for. you can get the options from
  1371. * the inst.options object and trigger the gesture event by calling inst.trigger
  1372. *
  1373. *
  1374. * Handle gestures
  1375. * --------------------
  1376. * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current
  1377. * detection sessionic. It has the following properties
  1378. * @param {String} name
  1379. * contains the name of the gesture we have detected. it has not a real function,
  1380. * only to check in other gestures if something is detected.
  1381. * like in the drag gesture we set it to 'drag' and in the swipe gesture we can
  1382. * check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name
  1383. *
  1384. * readonly
  1385. * @param {ionic.Gestures.Instance} inst
  1386. * the instance we do the detection for
  1387. *
  1388. * readonly
  1389. * @param {Object} startEvent
  1390. * contains the properties of the first gesture detection in this sessionic.
  1391. * Used for calculations about timing, distance, etc.
  1392. *
  1393. * readonly
  1394. * @param {Object} lastEvent
  1395. * contains all the properties of the last gesture detect in this sessionic.
  1396. *
  1397. * after the gesture detection session has been completed (user has released the screen)
  1398. * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous,
  1399. * this is usefull for gestures like doubletap, where you need to know if the
  1400. * previous gesture was a tap
  1401. *
  1402. * options that have been set by the instance can be received by calling inst.options
  1403. *
  1404. * You can trigger a gesture event by calling inst.trigger("mygesture", event).
  1405. * The first param is the name of your gesture, the second the event argument
  1406. *
  1407. *
  1408. * Register gestures
  1409. * --------------------
  1410. * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered
  1411. * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register
  1412. * manually and pass your gesture object as a param
  1413. *
  1414. */
  1415. /**
  1416. * Hold
  1417. * Touch stays at the same place for x time
  1418. * events hold
  1419. */
  1420. ionic.Gestures.gestures.Hold = {
  1421. name: 'hold',
  1422. index: 10,
  1423. defaults: {
  1424. hold_timeout: 500,
  1425. hold_threshold: 9
  1426. },
  1427. timer: null,
  1428. handler: function holdGesture(ev, inst) {
  1429. switch(ev.eventType) {
  1430. case ionic.Gestures.EVENT_START:
  1431. // clear any running timers
  1432. clearTimeout(this.timer);
  1433. // set the gesture so we can check in the timeout if it still is
  1434. ionic.Gestures.detection.current.name = this.name;
  1435. // set timer and if after the timeout it still is hold,
  1436. // we trigger the hold event
  1437. this.timer = setTimeout(function() {
  1438. if(ionic.Gestures.detection.current.name == 'hold') {
  1439. ionic.tap.cancelClick();
  1440. inst.trigger('hold', ev);
  1441. }
  1442. }, inst.options.hold_timeout);
  1443. break;
  1444. // when you move or end we clear the timer
  1445. case ionic.Gestures.EVENT_MOVE:
  1446. if(ev.distance > inst.options.hold_threshold) {
  1447. clearTimeout(this.timer);
  1448. }
  1449. break;
  1450. case ionic.Gestures.EVENT_END:
  1451. clearTimeout(this.timer);
  1452. break;
  1453. }
  1454. }
  1455. };
  1456. /**
  1457. * Tap/DoubleTap
  1458. * Quick touch at a place or double at the same place
  1459. * events tap, doubletap
  1460. */
  1461. ionic.Gestures.gestures.Tap = {
  1462. name: 'tap',
  1463. index: 100,
  1464. defaults: {
  1465. tap_max_touchtime: 250,
  1466. tap_max_distance: 10,
  1467. tap_always: true,
  1468. doubletap_distance: 20,
  1469. doubletap_interval: 300
  1470. },
  1471. handler: function tapGesture(ev, inst) {
  1472. if(ev.eventType == ionic.Gestures.EVENT_END && ev.srcEvent.type != 'touchcancel') {
  1473. // previous gesture, for the double tap since these are two different gesture detections
  1474. var prev = ionic.Gestures.detection.previous,
  1475. did_doubletap = false;
  1476. // when the touchtime is higher then the max touch time
  1477. // or when the moving distance is too much
  1478. if(ev.deltaTime > inst.options.tap_max_touchtime ||
  1479. ev.distance > inst.options.tap_max_distance) {
  1480. return;
  1481. }
  1482. // check if double tap
  1483. if(prev && prev.name == 'tap' &&
  1484. (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&
  1485. ev.distance < inst.options.doubletap_distance) {
  1486. inst.trigger('doubletap', ev);
  1487. did_doubletap = true;
  1488. }
  1489. // do a single tap
  1490. if(!did_doubletap || inst.options.tap_always) {
  1491. ionic.Gestures.detection.current.name = 'tap';
  1492. inst.trigger('tap', ev);
  1493. }
  1494. }
  1495. }
  1496. };
  1497. /**
  1498. * Swipe
  1499. * triggers swipe events when the end velocity is above the threshold
  1500. * events swipe, swipeleft, swiperight, swipeup, swipedown
  1501. */
  1502. ionic.Gestures.gestures.Swipe = {
  1503. name: 'swipe',
  1504. index: 40,
  1505. defaults: {
  1506. // set 0 for unlimited, but this can conflict with transform
  1507. swipe_max_touches: 1,
  1508. swipe_velocity: 0.4
  1509. },
  1510. handler: function swipeGesture(ev, inst) {
  1511. if(ev.eventType == ionic.Gestures.EVENT_END) {
  1512. // max touches
  1513. if(inst.options.swipe_max_touches > 0 &&
  1514. ev.touches.length > inst.options.swipe_max_touches) {
  1515. return;
  1516. }
  1517. // when the distance we moved is too small we skip this gesture
  1518. // or we can be already in dragging
  1519. if(ev.velocityX > inst.options.swipe_velocity ||
  1520. ev.velocityY > inst.options.swipe_velocity) {
  1521. // trigger swipe events
  1522. inst.trigger(this.name, ev);
  1523. inst.trigger(this.name + ev.direction, ev);
  1524. }
  1525. }
  1526. }
  1527. };
  1528. /**
  1529. * Drag
  1530. * Move with x fingers (default 1) around on the page. Blocking the scrolling when
  1531. * moving left and right is a good practice. When all the drag events are blocking
  1532. * you disable scrolling on that area.
  1533. * events drag, drapleft, dragright, dragup, dragdown
  1534. */
  1535. ionic.Gestures.gestures.Drag = {
  1536. name: 'drag',
  1537. index: 50,
  1538. defaults: {
  1539. drag_min_distance: 10,
  1540. // Set correct_for_drag_min_distance to true to make the starting point of the drag
  1541. // be calculated from where the drag was triggered, not from where the touch started.
  1542. // Useful to avoid a jerk-starting drag, which can make fine-adjustments
  1543. // through dragging difficult, and be visually unappealing.
  1544. correct_for_drag_min_distance: true,
  1545. // set 0 for unlimited, but this can conflict with transform
  1546. drag_max_touches: 1,
  1547. // prevent default browser behavior when dragging occurs
  1548. // be careful with it, it makes the element a blocking element
  1549. // when you are using the drag gesture, it is a good practice to set this true
  1550. drag_block_horizontal: true,
  1551. drag_block_vertical: true,
  1552. // drag_lock_to_axis keeps the drag gesture on the axis that it started on,
  1553. // It disallows vertical directions if the initial direction was horizontal, and vice versa.
  1554. drag_lock_to_axis: false,
  1555. // drag lock only kicks in when distance > drag_lock_min_distance
  1556. // This way, locking occurs only when the distance has become large enough to reliably determine the direction
  1557. drag_lock_min_distance: 25,
  1558. // prevent default if the gesture is going the given direction
  1559. prevent_default_directions: []
  1560. },
  1561. triggered: false,
  1562. handler: function dragGesture(ev, inst) {
  1563. if (ev.srcEvent.type == 'touchstart' || ev.srcEvent.type == 'touchend') {
  1564. this.preventedFirstMove = false;
  1565. } else if (!this.preventedFirstMove && ev.srcEvent.type == 'touchmove') {
  1566. // Prevent gestures that are not intended for this event handler from firing subsequent times
  1567. if (inst.options.prevent_default_directions.length > 0
  1568. && inst.options.prevent_default_directions.indexOf(ev.direction) != -1) {
  1569. ev.srcEvent.preventDefault();
  1570. }
  1571. this.preventedFirstMove = true;
  1572. }
  1573. // current gesture isnt drag, but dragged is true
  1574. // this means an other gesture is busy. now call dragend
  1575. if(ionic.Gestures.detection.current.name != this.name && this.triggered) {
  1576. inst.trigger(this.name + 'end', ev);
  1577. this.triggered = false;
  1578. return;
  1579. }
  1580. // max touches
  1581. if(inst.options.drag_max_touches > 0 &&
  1582. ev.touches.length > inst.options.drag_max_touches) {
  1583. return;
  1584. }
  1585. switch(ev.eventType) {
  1586. case ionic.Gestures.EVENT_START:
  1587. this.triggered = false;
  1588. break;
  1589. case ionic.Gestures.EVENT_MOVE:
  1590. // when the distance we moved is too small we skip this gesture
  1591. // or we can be already in dragging
  1592. if(ev.distance < inst.options.drag_min_distance &&
  1593. ionic.Gestures.detection.current.name != this.name) {
  1594. return;
  1595. }
  1596. // we are dragging!
  1597. if(ionic.Gestures.detection.current.name != this.name) {
  1598. ionic.Gestures.detection.current.name = this.name;
  1599. if (inst.options.correct_for_drag_min_distance) {
  1600. // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center.
  1601. // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0.
  1602. // It might be useful to save the original start point somewhere
  1603. var factor = Math.abs(inst.options.drag_min_distance / ev.distance);
  1604. ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor;
  1605. ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor;
  1606. // recalculate event data using new start point
  1607. ev = ionic.Gestures.detection.extendEventData(ev);
  1608. }
  1609. }
  1610. // lock drag to axis?
  1611. if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance <= ev.distance)) {
  1612. ev.drag_locked_to_axis = true;
  1613. }
  1614. var last_direction = ionic.Gestures.detection.current.lastEvent.direction;
  1615. if(ev.drag_locked_to_axis && last_direction !== ev.direction) {
  1616. // keep direction on the axis that the drag gesture started on
  1617. if(ionic.Gestures.utils.isVertical(last_direction)) {
  1618. ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;
  1619. }
  1620. else {
  1621. ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;
  1622. }
  1623. }
  1624. // first time, trigger dragstart event
  1625. if(!this.triggered) {
  1626. inst.trigger(this.name + 'start', ev);
  1627. this.triggered = true;
  1628. }
  1629. // trigger normal event
  1630. inst.trigger(this.name, ev);
  1631. // direction event, like dragdown
  1632. inst.trigger(this.name + ev.direction, ev);
  1633. // block the browser events
  1634. if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) ||
  1635. (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) {
  1636. ev.preventDefault();
  1637. }
  1638. break;
  1639. case ionic.Gestures.EVENT_END:
  1640. // trigger dragend
  1641. if(this.triggered) {
  1642. inst.trigger(this.name + 'end', ev);
  1643. }
  1644. this.triggered = false;
  1645. break;
  1646. }
  1647. }
  1648. };
  1649. /**
  1650. * Transform
  1651. * User want to scale or rotate with 2 fingers
  1652. * events transform, pinch, pinchin, pinchout, rotate
  1653. */
  1654. ionic.Gestures.gestures.Transform = {
  1655. name: 'transform',
  1656. index: 45,
  1657. defaults: {
  1658. // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1
  1659. transform_min_scale: 0.01,
  1660. // rotation in degrees
  1661. transform_min_rotation: 1,
  1662. // prevent default browser behavior when two touches are on the screen
  1663. // but it makes the element a blocking element
  1664. // when you are using the transform gesture, it is a good practice to set this true
  1665. transform_always_block: false
  1666. },
  1667. triggered: false,
  1668. handler: function transformGesture(ev, inst) {
  1669. // current gesture isnt drag, but dragged is true
  1670. // this means an other gesture is busy. now call dragend
  1671. if(ionic.Gestures.detection.current.name != this.name && this.triggered) {
  1672. inst.trigger(this.name + 'end', ev);
  1673. this.triggered = false;
  1674. return;
  1675. }
  1676. // atleast multitouch
  1677. if(ev.touches.length < 2) {
  1678. return;
  1679. }
  1680. // prevent default when two fingers are on the screen
  1681. if(inst.options.transform_always_block) {
  1682. ev.preventDefault();
  1683. }
  1684. switch(ev.eventType) {
  1685. case ionic.Gestures.EVENT_START:
  1686. this.triggered = false;
  1687. break;
  1688. case ionic.Gestures.EVENT_MOVE:
  1689. var scale_threshold = Math.abs(1 - ev.scale);
  1690. var rotation_threshold = Math.abs(ev.rotation);
  1691. // when the distance we moved is too small we skip this gesture
  1692. // or we can be already in dragging
  1693. if(scale_threshold < inst.options.transform_min_scale &&
  1694. rotation_threshold < inst.options.transform_min_rotation) {
  1695. return;
  1696. }
  1697. // we are transforming!
  1698. ionic.Gestures.detection.current.name = this.name;
  1699. // first time, trigger dragstart event
  1700. if(!this.triggered) {
  1701. inst.trigger(this.name + 'start', ev);
  1702. this.triggered = true;
  1703. }
  1704. inst.trigger(this.name, ev); // basic transform event
  1705. // trigger rotate event
  1706. if(rotation_threshold > inst.options.transform_min_rotation) {
  1707. inst.trigger('rotate', ev);
  1708. }
  1709. // trigger pinch event
  1710. if(scale_threshold > inst.options.transform_min_scale) {
  1711. inst.trigger('pinch', ev);
  1712. inst.trigger('pinch' + ((ev.scale < 1) ? 'in' : 'out'), ev);
  1713. }
  1714. break;
  1715. case ionic.Gestures.EVENT_END:
  1716. // trigger dragend
  1717. if(this.triggered) {
  1718. inst.trigger(this.name + 'end', ev);
  1719. }
  1720. this.triggered = false;
  1721. break;
  1722. }
  1723. }
  1724. };
  1725. /**
  1726. * Touch
  1727. * Called as first, tells the user has touched the screen
  1728. * events touch
  1729. */
  1730. ionic.Gestures.gestures.Touch = {
  1731. name: 'touch',
  1732. index: -Infinity,
  1733. defaults: {
  1734. // call preventDefault at touchstart, and makes the element blocking by
  1735. // disabling the scrolling of the page, but it improves gestures like
  1736. // transforming and dragging.
  1737. // be careful with using this, it can be very annoying for users to be stuck
  1738. // on the page
  1739. prevent_default: false,
  1740. // disable mouse events, so only touch (or pen!) input triggers events
  1741. prevent_mouseevents: false
  1742. },
  1743. handler: function touchGesture(ev, inst) {
  1744. if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) {
  1745. ev.stopDetect();
  1746. return;
  1747. }
  1748. if(inst.options.prevent_default) {
  1749. ev.preventDefault();
  1750. }
  1751. if(ev.eventType == ionic.Gestures.EVENT_START) {
  1752. inst.trigger(this.name, ev);
  1753. }
  1754. }
  1755. };
  1756. /**
  1757. * Release
  1758. * Called as last, tells the user has released the screen
  1759. * events release
  1760. */
  1761. ionic.Gestures.gestures.Release = {
  1762. name: 'release',
  1763. index: Infinity,
  1764. handler: function releaseGesture(ev, inst) {
  1765. if(ev.eventType == ionic.Gestures.EVENT_END) {
  1766. inst.trigger(this.name, ev);
  1767. }
  1768. }
  1769. };
  1770. })(window.ionic);
  1771. (function(window, document, ionic) {
  1772. function getParameterByName(name) {
  1773. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  1774. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  1775. results = regex.exec(location.search);
  1776. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  1777. }
  1778. var IOS = 'ios';
  1779. var ANDROID = 'android';
  1780. var WINDOWS_PHONE = 'windowsphone';
  1781. var EDGE = 'edge';
  1782. var CROSSWALK = 'crosswalk';
  1783. var requestAnimationFrame = ionic.requestAnimationFrame;
  1784. /**
  1785. * @ngdoc utility
  1786. * @name ionic.Platform
  1787. * @module ionic
  1788. * @description
  1789. * A set of utility methods that can be used to retrieve the device ready state and
  1790. * various other information such as what kind of platform the app is currently installed on.
  1791. *
  1792. * @usage
  1793. * ```js
  1794. * angular.module('PlatformApp', ['ionic'])
  1795. * .controller('PlatformCtrl', function($scope) {
  1796. *
  1797. * ionic.Platform.ready(function(){
  1798. * // will execute when device is ready, or immediately if the device is already ready.
  1799. * });
  1800. *
  1801. * var deviceInformation = ionic.Platform.device();
  1802. *
  1803. * var isWebView = ionic.Platform.isWebView();
  1804. * var isIPad = ionic.Platform.isIPad();
  1805. * var isIOS = ionic.Platform.isIOS();
  1806. * var isAndroid = ionic.Platform.isAndroid();
  1807. * var isWindowsPhone = ionic.Platform.isWindowsPhone();
  1808. *
  1809. * var currentPlatform = ionic.Platform.platform();
  1810. * var currentPlatformVersion = ionic.Platform.version();
  1811. *
  1812. * ionic.Platform.exitApp(); // stops the app
  1813. * });
  1814. * ```
  1815. */
  1816. var self = ionic.Platform = {
  1817. // Put navigator on platform so it can be mocked and set
  1818. // the browser does not allow window.navigator to be set
  1819. navigator: window.navigator,
  1820. /**
  1821. * @ngdoc property
  1822. * @name ionic.Platform#isReady
  1823. * @returns {boolean} Whether the device is ready.
  1824. */
  1825. isReady: false,
  1826. /**
  1827. * @ngdoc property
  1828. * @name ionic.Platform#isFullScreen
  1829. * @returns {boolean} Whether the device is fullscreen.
  1830. */
  1831. isFullScreen: false,
  1832. /**
  1833. * @ngdoc property
  1834. * @name ionic.Platform#platforms
  1835. * @returns {Array(string)} An array of all platforms found.
  1836. */
  1837. platforms: null,
  1838. /**
  1839. * @ngdoc property
  1840. * @name ionic.Platform#grade
  1841. * @returns {string} What grade the current platform is.
  1842. */
  1843. grade: null,
  1844. /**
  1845. * @ngdoc property
  1846. * @name ionic.Platform#ua
  1847. * @returns {string} What User Agent is.
  1848. */
  1849. ua: navigator.userAgent,
  1850. /**
  1851. * @ngdoc method
  1852. * @name ionic.Platform#ready
  1853. * @description
  1854. * Trigger a callback once the device is ready, or immediately
  1855. * if the device is already ready. This method can be run from
  1856. * anywhere and does not need to be wrapped by any additonal methods.
  1857. * When the app is within a WebView (Cordova), it'll fire
  1858. * the callback once the device is ready. If the app is within
  1859. * a web browser, it'll fire the callback after `window.load`.
  1860. * Please remember that Cordova features (Camera, FileSystem, etc) still
  1861. * will not work in a web browser.
  1862. * @param {function} callback The function to call.
  1863. */
  1864. ready: function(cb) {
  1865. // run through tasks to complete now that the device is ready
  1866. if (self.isReady) {
  1867. cb();
  1868. } else {
  1869. // the platform isn't ready yet, add it to this array
  1870. // which will be called once the platform is ready
  1871. readyCallbacks.push(cb);
  1872. }
  1873. },
  1874. /**
  1875. * @private
  1876. */
  1877. detect: function() {
  1878. self._checkPlatforms();
  1879. requestAnimationFrame(function() {
  1880. // only add to the body class if we got platform info
  1881. for (var i = 0; i < self.platforms.length; i++) {
  1882. document.body.classList.add('platform-' + self.platforms[i]);
  1883. }
  1884. });
  1885. },
  1886. /**
  1887. * @ngdoc method
  1888. * @name ionic.Platform#setGrade
  1889. * @description Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best
  1890. * (most css features enabled), 'c' is the worst. By default, sets the grade
  1891. * depending on the current device.
  1892. * @param {string} grade The new grade to set.
  1893. */
  1894. setGrade: function(grade) {
  1895. var oldGrade = self.grade;
  1896. self.grade = grade;
  1897. requestAnimationFrame(function() {
  1898. if (oldGrade) {
  1899. document.body.classList.remove('grade-' + oldGrade);
  1900. }
  1901. document.body.classList.add('grade-' + grade);
  1902. });
  1903. },
  1904. /**
  1905. * @ngdoc method
  1906. * @name ionic.Platform#device
  1907. * @description Return the current device (given by cordova).
  1908. * @returns {object} The device object.
  1909. */
  1910. device: function() {
  1911. return window.device || {};
  1912. },
  1913. _checkPlatforms: function() {
  1914. self.platforms = [];
  1915. var grade = 'a';
  1916. if (self.isWebView()) {
  1917. self.platforms.push('webview');
  1918. if (!(!window.cordova && !window.PhoneGap && !window.phonegap)) {
  1919. self.platforms.push('cordova');
  1920. } else if (typeof window.forge === 'object') {
  1921. self.platforms.push('trigger');
  1922. }
  1923. } else {
  1924. self.platforms.push('browser');
  1925. }
  1926. if (self.isIPad()) self.platforms.push('ipad');
  1927. var platform = self.platform();
  1928. if (platform) {
  1929. self.platforms.push(platform);
  1930. var version = self.version();
  1931. if (version) {
  1932. var v = version.toString();
  1933. if (v.indexOf('.') > 0) {
  1934. v = v.replace('.', '_');
  1935. } else {
  1936. v += '_0';
  1937. }
  1938. self.platforms.push(platform + v.split('_')[0]);
  1939. self.platforms.push(platform + v);
  1940. if (self.isAndroid() && version < 4.4) {
  1941. grade = (version < 4 ? 'c' : 'b');
  1942. } else if (self.isWindowsPhone()) {
  1943. grade = 'b';
  1944. }
  1945. }
  1946. }
  1947. self.setGrade(grade);
  1948. },
  1949. /**
  1950. * @ngdoc method
  1951. * @name ionic.Platform#isWebView
  1952. * @returns {boolean} Check if we are running within a WebView (such as Cordova).
  1953. */
  1954. isWebView: function() {
  1955. return !(!window.cordova && !window.PhoneGap && !window.phonegap && window.forge !== 'object');
  1956. },
  1957. /**
  1958. * @ngdoc method
  1959. * @name ionic.Platform#isIPad
  1960. * @returns {boolean} Whether we are running on iPad.
  1961. */
  1962. isIPad: function() {
  1963. if (/iPad/i.test(self.navigator.platform)) {
  1964. return true;
  1965. }
  1966. return /iPad/i.test(self.ua);
  1967. },
  1968. /**
  1969. * @ngdoc method
  1970. * @name ionic.Platform#isIOS
  1971. * @returns {boolean} Whether we are running on iOS.
  1972. */
  1973. isIOS: function() {
  1974. return self.is(IOS);
  1975. },
  1976. /**
  1977. * @ngdoc method
  1978. * @name ionic.Platform#isAndroid
  1979. * @returns {boolean} Whether we are running on Android.
  1980. */
  1981. isAndroid: function() {
  1982. return self.is(ANDROID);
  1983. },
  1984. /**
  1985. * @ngdoc method
  1986. * @name ionic.Platform#isWindowsPhone
  1987. * @returns {boolean} Whether we are running on Windows Phone.
  1988. */
  1989. isWindowsPhone: function() {
  1990. return self.is(WINDOWS_PHONE);
  1991. },
  1992. /**
  1993. * @ngdoc method
  1994. * @name ionic.Platform#isEdge
  1995. * @returns {boolean} Whether we are running on MS Edge/Windows 10 (inc. Phone)
  1996. */
  1997. isEdge: function() {
  1998. return self.is(EDGE);
  1999. },
  2000. isCrosswalk: function() {
  2001. return self.is(CROSSWALK);
  2002. },
  2003. /**
  2004. * @ngdoc method
  2005. * @name ionic.Platform#platform
  2006. * @returns {string} The name of the current platform.
  2007. */
  2008. platform: function() {
  2009. // singleton to get the platform name
  2010. if (platformName === null) self.setPlatform(self.device().platform);
  2011. return platformName;
  2012. },
  2013. /**
  2014. * @private
  2015. */
  2016. setPlatform: function(n) {
  2017. if (typeof n != 'undefined' && n !== null && n.length) {
  2018. platformName = n.toLowerCase();
  2019. } else if (getParameterByName('ionicplatform')) {
  2020. platformName = getParameterByName('ionicplatform');
  2021. } else if (self.ua.indexOf('Edge') > -1) {
  2022. platformName = EDGE;
  2023. } else if (self.ua.indexOf('Windows Phone') > -1) {
  2024. platformName = WINDOWS_PHONE;
  2025. } else if (self.ua.indexOf('Android') > 0) {
  2026. platformName = ANDROID;
  2027. } else if (/iPhone|iPad|iPod/.test(self.ua)) {
  2028. platformName = IOS;
  2029. } else {
  2030. platformName = self.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || '';
  2031. }
  2032. },
  2033. /**
  2034. * @ngdoc method
  2035. * @name ionic.Platform#version
  2036. * @returns {number} The version of the current device platform.
  2037. */
  2038. version: function() {
  2039. // singleton to get the platform version
  2040. if (platformVersion === null) self.setVersion(self.device().version);
  2041. return platformVersion;
  2042. },
  2043. /**
  2044. * @private
  2045. */
  2046. setVersion: function(v) {
  2047. if (typeof v != 'undefined' && v !== null) {
  2048. v = v.split('.');
  2049. v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0));
  2050. if (!isNaN(v)) {
  2051. platformVersion = v;
  2052. return;
  2053. }
  2054. }
  2055. platformVersion = 0;
  2056. // fallback to user-agent checking
  2057. var pName = self.platform();
  2058. var versionMatch = {
  2059. 'android': /Android (\d+).(\d+)?/,
  2060. 'ios': /OS (\d+)_(\d+)?/,
  2061. 'windowsphone': /Windows Phone (\d+).(\d+)?/
  2062. };
  2063. if (versionMatch[pName]) {
  2064. v = self.ua.match(versionMatch[pName]);
  2065. if (v && v.length > 2) {
  2066. platformVersion = parseFloat(v[1] + '.' + v[2]);
  2067. }
  2068. }
  2069. },
  2070. /**
  2071. * @ngdoc method
  2072. * @name ionic.Platform#is
  2073. * @param {string} Platform name.
  2074. * @returns {boolean} Whether the platform name provided is detected.
  2075. */
  2076. is: function(type) {
  2077. type = type.toLowerCase();
  2078. // check if it has an array of platforms
  2079. if (self.platforms) {
  2080. for (var x = 0; x < self.platforms.length; x++) {
  2081. if (self.platforms[x] === type) return true;
  2082. }
  2083. }
  2084. // exact match
  2085. var pName = self.platform();
  2086. if (pName) {
  2087. return pName === type.toLowerCase();
  2088. }
  2089. // A quick hack for to check userAgent
  2090. return self.ua.toLowerCase().indexOf(type) >= 0;
  2091. },
  2092. /**
  2093. * @ngdoc method
  2094. * @name ionic.Platform#exitApp
  2095. * @description Exit the app.
  2096. */
  2097. exitApp: function() {
  2098. self.ready(function() {
  2099. navigator.app && navigator.app.exitApp && navigator.app.exitApp();
  2100. });
  2101. },
  2102. /**
  2103. * @ngdoc method
  2104. * @name ionic.Platform#showStatusBar
  2105. * @description Shows or hides the device status bar (in Cordova). Requires `cordova plugin add org.apache.cordova.statusbar`
  2106. * @param {boolean} shouldShow Whether or not to show the status bar.
  2107. */
  2108. showStatusBar: function(val) {
  2109. // Only useful when run within cordova
  2110. self._showStatusBar = val;
  2111. self.ready(function() {
  2112. // run this only when or if the platform (cordova) is ready
  2113. requestAnimationFrame(function() {
  2114. if (self._showStatusBar) {
  2115. // they do not want it to be full screen
  2116. window.StatusBar && window.StatusBar.show();
  2117. document.body.classList.remove('status-bar-hide');
  2118. } else {
  2119. // it should be full screen
  2120. window.StatusBar && window.StatusBar.hide();
  2121. document.body.classList.add('status-bar-hide');
  2122. }
  2123. });
  2124. });
  2125. },
  2126. /**
  2127. * @ngdoc method
  2128. * @name ionic.Platform#fullScreen
  2129. * @description
  2130. * Sets whether the app is fullscreen or not (in Cordova).
  2131. * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. Requires `cordova plugin add org.apache.cordova.statusbar`
  2132. * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false.
  2133. */
  2134. fullScreen: function(showFullScreen, showStatusBar) {
  2135. // showFullScreen: default is true if no param provided
  2136. self.isFullScreen = (showFullScreen !== false);
  2137. // add/remove the fullscreen classname to the body
  2138. ionic.DomUtil.ready(function() {
  2139. // run this only when or if the DOM is ready
  2140. requestAnimationFrame(function() {
  2141. if (self.isFullScreen) {
  2142. document.body.classList.add('fullscreen');
  2143. } else {
  2144. document.body.classList.remove('fullscreen');
  2145. }
  2146. });
  2147. // showStatusBar: default is false if no param provided
  2148. self.showStatusBar((showStatusBar === true));
  2149. });
  2150. }
  2151. };
  2152. var platformName = null, // just the name, like iOS or Android
  2153. platformVersion = null, // a float of the major and minor, like 7.1
  2154. readyCallbacks = [],
  2155. windowLoadListenderAttached,
  2156. platformReadyTimer = 2000; // How long to wait for platform ready before emitting a warning
  2157. verifyPlatformReady();
  2158. // Warn the user if deviceready did not fire in a reasonable amount of time, and how to fix it.
  2159. function verifyPlatformReady() {
  2160. setTimeout(function() {
  2161. if(!self.isReady && self.isWebView()) {
  2162. void 0;
  2163. }
  2164. }, platformReadyTimer);
  2165. }
  2166. // setup listeners to know when the device is ready to go
  2167. function onWindowLoad() {
  2168. if (self.isWebView()) {
  2169. // the window and scripts are fully loaded, and a cordova/phonegap
  2170. // object exists then let's listen for the deviceready
  2171. document.addEventListener("deviceready", onPlatformReady, false);
  2172. } else {
  2173. // the window and scripts are fully loaded, but the window object doesn't have the
  2174. // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova
  2175. onPlatformReady();
  2176. }
  2177. if (windowLoadListenderAttached) {
  2178. window.removeEventListener("load", onWindowLoad, false);
  2179. }
  2180. }
  2181. if (document.readyState === 'complete') {
  2182. onWindowLoad();
  2183. } else {
  2184. windowLoadListenderAttached = true;
  2185. window.addEventListener("load", onWindowLoad, false);
  2186. }
  2187. function onPlatformReady() {
  2188. // the device is all set to go, init our own stuff then fire off our event
  2189. self.isReady = true;
  2190. self.detect();
  2191. for (var x = 0; x < readyCallbacks.length; x++) {
  2192. // fire off all the callbacks that were added before the platform was ready
  2193. readyCallbacks[x]();
  2194. }
  2195. readyCallbacks = [];
  2196. ionic.trigger('platformready', { target: document });
  2197. requestAnimationFrame(function() {
  2198. document.body.classList.add('platform-ready');
  2199. });
  2200. }
  2201. })(window, document, ionic);
  2202. (function(document, ionic) {
  2203. 'use strict';
  2204. // Ionic CSS polyfills
  2205. ionic.CSS = {};
  2206. ionic.CSS.TRANSITION = [];
  2207. ionic.CSS.TRANSFORM = [];
  2208. ionic.EVENTS = {};
  2209. (function() {
  2210. // transform
  2211. var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',
  2212. '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform'];
  2213. for (i = 0; i < keys.length; i++) {
  2214. if (document.documentElement.style[keys[i]] !== undefined) {
  2215. ionic.CSS.TRANSFORM = keys[i];
  2216. break;
  2217. }
  2218. }
  2219. // transition
  2220. keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition'];
  2221. for (i = 0; i < keys.length; i++) {
  2222. if (document.documentElement.style[keys[i]] !== undefined) {
  2223. ionic.CSS.TRANSITION = keys[i];
  2224. break;
  2225. }
  2226. }
  2227. // Fallback in case the keys don't exist at all
  2228. ionic.CSS.TRANSITION = ionic.CSS.TRANSITION || 'transition';
  2229. // The only prefix we care about is webkit for transitions.
  2230. var isWebkit = ionic.CSS.TRANSITION.indexOf('webkit') > -1;
  2231. // transition duration
  2232. ionic.CSS.TRANSITION_DURATION = (isWebkit ? '-webkit-' : '') + 'transition-duration';
  2233. // To be sure transitionend works everywhere, include *both* the webkit and non-webkit events
  2234. ionic.CSS.TRANSITIONEND = (isWebkit ? 'webkitTransitionEnd ' : '') + 'transitionend';
  2235. })();
  2236. (function() {
  2237. var touchStartEvent = 'touchstart';
  2238. var touchMoveEvent = 'touchmove';
  2239. var touchEndEvent = 'touchend';
  2240. var touchCancelEvent = 'touchcancel';
  2241. if (window.navigator.pointerEnabled) {
  2242. touchStartEvent = 'pointerdown';
  2243. touchMoveEvent = 'pointermove';
  2244. touchEndEvent = 'pointerup';
  2245. touchCancelEvent = 'pointercancel';
  2246. } else if (window.navigator.msPointerEnabled) {
  2247. touchStartEvent = 'MSPointerDown';
  2248. touchMoveEvent = 'MSPointerMove';
  2249. touchEndEvent = 'MSPointerUp';
  2250. touchCancelEvent = 'MSPointerCancel';
  2251. }
  2252. ionic.EVENTS.touchstart = touchStartEvent;
  2253. ionic.EVENTS.touchmove = touchMoveEvent;
  2254. ionic.EVENTS.touchend = touchEndEvent;
  2255. ionic.EVENTS.touchcancel = touchCancelEvent;
  2256. })();
  2257. // classList polyfill for them older Androids
  2258. // https://gist.github.com/devongovett/1381839
  2259. if (!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {
  2260. Object.defineProperty(HTMLElement.prototype, 'classList', {
  2261. get: function() {
  2262. var self = this;
  2263. function update(fn) {
  2264. return function() {
  2265. var x, classes = self.className.split(/\s+/);
  2266. for (x = 0; x < arguments.length; x++) {
  2267. fn(classes, classes.indexOf(arguments[x]), arguments[x]);
  2268. }
  2269. self.className = classes.join(" ");
  2270. };
  2271. }
  2272. return {
  2273. add: update(function(classes, index, value) {
  2274. ~index || classes.push(value);
  2275. }),
  2276. remove: update(function(classes, index) {
  2277. ~index && classes.splice(index, 1);
  2278. }),
  2279. toggle: update(function(classes, index, value) {
  2280. ~index ? classes.splice(index, 1) : classes.push(value);
  2281. }),
  2282. contains: function(value) {
  2283. return !!~self.className.split(/\s+/).indexOf(value);
  2284. },
  2285. item: function(i) {
  2286. return self.className.split(/\s+/)[i] || null;
  2287. }
  2288. };
  2289. }
  2290. });
  2291. }
  2292. })(document, ionic);
  2293. /**
  2294. * @ngdoc page
  2295. * @name tap
  2296. * @module ionic
  2297. * @description
  2298. * On touch devices such as a phone or tablet, some browsers implement a 300ms delay between
  2299. * the time the user stops touching the display and the moment the browser executes the
  2300. * click. This delay was initially introduced so the browser can know whether the user wants to
  2301. * double-tap to zoom in on the webpage. Basically, the browser waits roughly 300ms to see if
  2302. * the user is double-tapping, or just tapping on the display once.
  2303. *
  2304. * Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps
  2305. * feel more "native" like. Resultingly, other solutions such as
  2306. * [fastclick](https://github.com/ftlabs/fastclick) and Angular's
  2307. * [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts.
  2308. *
  2309. * Some browsers already remove the delay with certain settings, such as the CSS property
  2310. * `touch-events: none` or with specific meta tag viewport values. However, each of these
  2311. * browsers still handle clicks differently, such as when to fire off or cancel the event
  2312. * (like scrolling when the target is a button, or holding a button down).
  2313. * For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to
  2314. * normalize how clicks are handled across the various devices so there's an expected response
  2315. * no matter what the device, platform or version. Additionally, Ionic will prevent
  2316. * ghostclicks which even browsers that remove the delay still experience.
  2317. *
  2318. * In some cases, third-party libraries may also be working with touch events which can interfere
  2319. * with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement
  2320. * a touch detection system which conflicts with Ionic's tap system.
  2321. *
  2322. * ### Disabling the tap system
  2323. *
  2324. * To disable the tap for an element and all of its children elements,
  2325. * add the attribute `data-tap-disabled="true"`.
  2326. *
  2327. * ```html
  2328. * <div data-tap-disabled="true">
  2329. * <div id="google-map"></div>
  2330. * </div>
  2331. * ```
  2332. *
  2333. * ### Additional Notes:
  2334. *
  2335. * - Ionic tap works with Ionic's JavaScript scrolling
  2336. * - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing
  2337. * listeners
  2338. * - No "tap delay" after the first "tap" (you can tap as fast as you want, they all click)
  2339. * - Minimal events listeners, only being added to document
  2340. * - Correct focus in/out on each input type (select, textearea, range) on each platform/device
  2341. * - Shows and hides virtual keyboard correctly for each platform/device
  2342. * - Works with labels surrounding inputs
  2343. * - Does not fire off a click if the user moves the pointer too far
  2344. * - Adds and removes an 'activated' css class
  2345. * - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario
  2346. *
  2347. */
  2348. /*
  2349. IONIC TAP
  2350. ---------------
  2351. - Both touch and mouse events are added to the document.body on DOM ready
  2352. - If a touch event happens, it does not use mouse event listeners
  2353. - On touchend, if the distance between start and end was small, trigger a click
  2354. - In the triggered click event, add a 'isIonicTap' property
  2355. - The triggered click receives the same x,y coordinates as as the end event
  2356. - On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap'
  2357. - Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup
  2358. - Tapping inputs is disabled during scrolling
  2359. */
  2360. var tapDoc; // the element which the listeners are on (document.body)
  2361. var tapActiveEle; // the element which is active (probably has focus)
  2362. var tapEnabledTouchEvents;
  2363. var tapMouseResetTimer;
  2364. var tapPointerMoved;
  2365. var tapPointerStart;
  2366. var tapTouchFocusedInput;
  2367. var tapLastTouchTarget;
  2368. var tapTouchMoveListener = 'touchmove';
  2369. // how much the coordinates can be off between start/end, but still a click
  2370. var TAP_RELEASE_TOLERANCE = 12; // default tolerance
  2371. var TAP_RELEASE_BUTTON_TOLERANCE = 50; // button elements should have a larger tolerance
  2372. var tapEventListeners = {
  2373. 'click': tapClickGateKeeper,
  2374. 'mousedown': tapMouseDown,
  2375. 'mouseup': tapMouseUp,
  2376. 'mousemove': tapMouseMove,
  2377. 'touchstart': tapTouchStart,
  2378. 'touchend': tapTouchEnd,
  2379. 'touchcancel': tapTouchCancel,
  2380. 'touchmove': tapTouchMove,
  2381. 'pointerdown': tapTouchStart,
  2382. 'pointerup': tapTouchEnd,
  2383. 'pointercancel': tapTouchCancel,
  2384. 'pointermove': tapTouchMove,
  2385. 'MSPointerDown': tapTouchStart,
  2386. 'MSPointerUp': tapTouchEnd,
  2387. 'MSPointerCancel': tapTouchCancel,
  2388. 'MSPointerMove': tapTouchMove,
  2389. 'focusin': tapFocusIn,
  2390. 'focusout': tapFocusOut
  2391. };
  2392. ionic.tap = {
  2393. register: function(ele) {
  2394. tapDoc = ele;
  2395. tapEventListener('click', true, true);
  2396. tapEventListener('mouseup');
  2397. tapEventListener('mousedown');
  2398. if (window.navigator.pointerEnabled) {
  2399. tapEventListener('pointerdown');
  2400. tapEventListener('pointerup');
  2401. tapEventListener('pointercancel');
  2402. tapTouchMoveListener = 'pointermove';
  2403. } else if (window.navigator.msPointerEnabled) {
  2404. tapEventListener('MSPointerDown');
  2405. tapEventListener('MSPointerUp');
  2406. tapEventListener('MSPointerCancel');
  2407. tapTouchMoveListener = 'MSPointerMove';
  2408. } else {
  2409. tapEventListener('touchstart');
  2410. tapEventListener('touchend');
  2411. tapEventListener('touchcancel');
  2412. }
  2413. tapEventListener('focusin');
  2414. tapEventListener('focusout');
  2415. return function() {
  2416. for (var type in tapEventListeners) {
  2417. tapEventListener(type, false);
  2418. }
  2419. tapDoc = null;
  2420. tapActiveEle = null;
  2421. tapEnabledTouchEvents = false;
  2422. tapPointerMoved = false;
  2423. tapPointerStart = null;
  2424. };
  2425. },
  2426. ignoreScrollStart: function(e) {
  2427. return (e.defaultPrevented) || // defaultPrevented has been assigned by another component handling the event
  2428. (/^(file|range)$/i).test(e.target.type) ||
  2429. (e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll')) == 'true' || // manually set within an elements attributes
  2430. (!!(/^(object|embed)$/i).test(e.target.tagName)) || // flash/movie/object touches should not try to scroll
  2431. ionic.tap.isElementTapDisabled(e.target); // check if this element, or an ancestor, has `data-tap-disabled` attribute
  2432. },
  2433. isTextInput: function(ele) {
  2434. return !!ele &&
  2435. (ele.tagName == 'TEXTAREA' ||
  2436. ele.contentEditable === 'true' ||
  2437. (ele.tagName == 'INPUT' && !(/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i).test(ele.type)));
  2438. },
  2439. isDateInput: function(ele) {
  2440. return !!ele &&
  2441. (ele.tagName == 'INPUT' && (/^(date|time|datetime-local|month|week)$/i).test(ele.type));
  2442. },
  2443. isVideo: function(ele) {
  2444. return !!ele &&
  2445. (ele.tagName == 'VIDEO');
  2446. },
  2447. isKeyboardElement: function(ele) {
  2448. if ( !ionic.Platform.isIOS() || ionic.Platform.isIPad() ) {
  2449. return ionic.tap.isTextInput(ele) && !ionic.tap.isDateInput(ele);
  2450. } else {
  2451. return ionic.tap.isTextInput(ele) || ( !!ele && ele.tagName == "SELECT");
  2452. }
  2453. },
  2454. isLabelWithTextInput: function(ele) {
  2455. var container = tapContainingElement(ele, false);
  2456. return !!container &&
  2457. ionic.tap.isTextInput(tapTargetElement(container));
  2458. },
  2459. containsOrIsTextInput: function(ele) {
  2460. return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele);
  2461. },
  2462. cloneFocusedInput: function(container) {
  2463. if (ionic.tap.hasCheckedClone) return;
  2464. ionic.tap.hasCheckedClone = true;
  2465. ionic.requestAnimationFrame(function() {
  2466. var focusInput = container.querySelector(':focus');
  2467. if (ionic.tap.isTextInput(focusInput) && !ionic.tap.isDateInput(focusInput)) {
  2468. var clonedInput = focusInput.cloneNode(true);
  2469. clonedInput.value = focusInput.value;
  2470. clonedInput.classList.add('cloned-text-input');
  2471. clonedInput.readOnly = true;
  2472. if (focusInput.isContentEditable) {
  2473. clonedInput.contentEditable = focusInput.contentEditable;
  2474. clonedInput.innerHTML = focusInput.innerHTML;
  2475. }
  2476. focusInput.parentElement.insertBefore(clonedInput, focusInput);
  2477. focusInput.classList.add('previous-input-focus');
  2478. clonedInput.scrollTop = focusInput.scrollTop;
  2479. }
  2480. });
  2481. },
  2482. hasCheckedClone: false,
  2483. removeClonedInputs: function(container) {
  2484. ionic.tap.hasCheckedClone = false;
  2485. ionic.requestAnimationFrame(function() {
  2486. var clonedInputs = container.querySelectorAll('.cloned-text-input');
  2487. var previousInputFocus = container.querySelectorAll('.previous-input-focus');
  2488. var x;
  2489. for (x = 0; x < clonedInputs.length; x++) {
  2490. clonedInputs[x].parentElement.removeChild(clonedInputs[x]);
  2491. }
  2492. for (x = 0; x < previousInputFocus.length; x++) {
  2493. previousInputFocus[x].classList.remove('previous-input-focus');
  2494. previousInputFocus[x].style.top = '';
  2495. if ( ionic.keyboard.isOpen && !ionic.keyboard.isClosing ) previousInputFocus[x].focus();
  2496. }
  2497. });
  2498. },
  2499. requiresNativeClick: function(ele) {
  2500. if (ionic.Platform.isWindowsPhone() && (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click') || (ele.tagName == 'INPUT' && (ele.type == 'button' || ele.type == 'submit')))) {
  2501. return true; //Windows Phone edge case, prevent ng-click (and similar) events from firing twice on this platform
  2502. }
  2503. if (!ele || ele.disabled || (/^(file|range)$/i).test(ele.type) || (/^(object|video)$/i).test(ele.tagName) || ionic.tap.isLabelContainingFileInput(ele)) {
  2504. return true;
  2505. }
  2506. return ionic.tap.isElementTapDisabled(ele);
  2507. },
  2508. isLabelContainingFileInput: function(ele) {
  2509. var lbl = tapContainingElement(ele);
  2510. if (lbl.tagName !== 'LABEL') return false;
  2511. var fileInput = lbl.querySelector('input[type=file]');
  2512. if (fileInput && fileInput.disabled === false) return true;
  2513. return false;
  2514. },
  2515. isElementTapDisabled: function(ele) {
  2516. if (ele && ele.nodeType === 1) {
  2517. var element = ele;
  2518. while (element) {
  2519. if (element.getAttribute && element.getAttribute('data-tap-disabled') == 'true') {
  2520. return true;
  2521. }
  2522. element = element.parentElement;
  2523. }
  2524. }
  2525. return false;
  2526. },
  2527. setTolerance: function(releaseTolerance, releaseButtonTolerance) {
  2528. TAP_RELEASE_TOLERANCE = releaseTolerance;
  2529. TAP_RELEASE_BUTTON_TOLERANCE = releaseButtonTolerance;
  2530. },
  2531. cancelClick: function() {
  2532. // used to cancel any simulated clicks which may happen on a touchend/mouseup
  2533. // gestures uses this method within its tap and hold events
  2534. tapPointerMoved = true;
  2535. },
  2536. pointerCoord: function(event) {
  2537. // This method can get coordinates for both a mouse click
  2538. // or a touch depending on the given event
  2539. var c = { x: 0, y: 0 };
  2540. if (event) {
  2541. var touches = event.touches && event.touches.length ? event.touches : [event];
  2542. var e = (event.changedTouches && event.changedTouches[0]) || touches[0];
  2543. if (e) {
  2544. c.x = e.clientX || e.pageX || 0;
  2545. c.y = e.clientY || e.pageY || 0;
  2546. }
  2547. }
  2548. return c;
  2549. }
  2550. };
  2551. function tapEventListener(type, enable, useCapture) {
  2552. if (enable !== false) {
  2553. tapDoc.addEventListener(type, tapEventListeners[type], useCapture);
  2554. } else {
  2555. tapDoc.removeEventListener(type, tapEventListeners[type]);
  2556. }
  2557. }
  2558. function tapClick(e) {
  2559. // simulate a normal click by running the element's click method then focus on it
  2560. var container = tapContainingElement(e.target);
  2561. var ele = tapTargetElement(container);
  2562. if (ionic.tap.requiresNativeClick(ele) || tapPointerMoved) return false;
  2563. var c = ionic.tap.pointerCoord(e);
  2564. //console.log('tapClick', e.type, ele.tagName, '('+c.x+','+c.y+')');
  2565. triggerMouseEvent('click', ele, c.x, c.y);
  2566. // if it's an input, focus in on the target, otherwise blur
  2567. tapHandleFocus(ele);
  2568. }
  2569. function triggerMouseEvent(type, ele, x, y) {
  2570. // using initMouseEvent instead of MouseEvent for our Android friends
  2571. var clickEvent = document.createEvent("MouseEvents");
  2572. clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null);
  2573. clickEvent.isIonicTap = true;
  2574. ele.dispatchEvent(clickEvent);
  2575. }
  2576. function tapClickGateKeeper(e) {
  2577. //console.log('click ' + Date.now() + ' isIonicTap: ' + (e.isIonicTap ? true : false));
  2578. if (e.target.type == 'submit' && e.detail === 0) {
  2579. // do not prevent click if it came from an "Enter" or "Go" keypress submit
  2580. return null;
  2581. }
  2582. // do not allow through any click events that were not created by ionic.tap
  2583. if ((ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) ||
  2584. (!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target))) {
  2585. //console.log('clickPrevent', e.target.tagName);
  2586. e.stopPropagation();
  2587. if (!ionic.tap.isLabelWithTextInput(e.target)) {
  2588. // labels clicks from native should not preventDefault othersize keyboard will not show on input focus
  2589. e.preventDefault();
  2590. }
  2591. return false;
  2592. }
  2593. }
  2594. // MOUSE
  2595. function tapMouseDown(e) {
  2596. //console.log('mousedown ' + Date.now());
  2597. if (e.isIonicTap || tapIgnoreEvent(e)) return null;
  2598. if (tapEnabledTouchEvents) {
  2599. //console.log('mousedown', 'stop event');
  2600. e.stopPropagation();
  2601. if (!ionic.Platform.isEdge() && (!ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target) &&
  2602. !isSelectOrOption(e.target.tagName) && !ionic.tap.isVideo(e.target)) {
  2603. // If you preventDefault on a text input then you cannot move its text caret/cursor.
  2604. // Allow through only the text input default. However, without preventDefault on an
  2605. // input the 300ms delay can change focus on inputs after the keyboard shows up.
  2606. // The focusin event handles the chance of focus changing after the keyboard shows.
  2607. // Windows Phone - if you preventDefault on a video element then you cannot operate
  2608. // its native controls.
  2609. e.preventDefault();
  2610. }
  2611. return false;
  2612. }
  2613. tapPointerMoved = false;
  2614. tapPointerStart = ionic.tap.pointerCoord(e);
  2615. tapEventListener('mousemove');
  2616. ionic.activator.start(e);
  2617. }
  2618. function tapMouseUp(e) {
  2619. //console.log("mouseup " + Date.now());
  2620. if (tapEnabledTouchEvents) {
  2621. e.stopPropagation();
  2622. e.preventDefault();
  2623. return false;
  2624. }
  2625. if (tapIgnoreEvent(e) || isSelectOrOption(e.target.tagName)) return false;
  2626. if (!tapHasPointerMoved(e)) {
  2627. tapClick(e);
  2628. }
  2629. tapEventListener('mousemove', false);
  2630. ionic.activator.end();
  2631. tapPointerMoved = false;
  2632. }
  2633. function tapMouseMove(e) {
  2634. if (tapHasPointerMoved(e)) {
  2635. tapEventListener('mousemove', false);
  2636. ionic.activator.end();
  2637. tapPointerMoved = true;
  2638. return false;
  2639. }
  2640. }
  2641. // TOUCH
  2642. function tapTouchStart(e) {
  2643. //console.log("touchstart " + Date.now());
  2644. if (tapIgnoreEvent(e)) return;
  2645. tapPointerMoved = false;
  2646. tapEnableTouchEvents();
  2647. tapPointerStart = ionic.tap.pointerCoord(e);
  2648. tapEventListener(tapTouchMoveListener);
  2649. ionic.activator.start(e);
  2650. if (ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target)) {
  2651. // if the tapped element is a label, which has a child input
  2652. // then preventDefault so iOS doesn't ugly auto scroll to the input
  2653. // but do not prevent default on Android or else you cannot move the text caret
  2654. // and do not prevent default on Android or else no virtual keyboard shows up
  2655. var textInput = tapTargetElement(tapContainingElement(e.target));
  2656. if (textInput !== tapActiveEle) {
  2657. // don't preventDefault on an already focused input or else iOS's text caret isn't usable
  2658. //console.log('Would prevent default here');
  2659. e.preventDefault();
  2660. }
  2661. }
  2662. }
  2663. function tapTouchEnd(e) {
  2664. //console.log('touchend ' + Date.now());
  2665. if (tapIgnoreEvent(e)) return;
  2666. tapEnableTouchEvents();
  2667. if (!tapHasPointerMoved(e)) {
  2668. tapClick(e);
  2669. if (isSelectOrOption(e.target.tagName)) {
  2670. e.preventDefault();
  2671. }
  2672. }
  2673. tapLastTouchTarget = e.target;
  2674. tapTouchCancel();
  2675. }
  2676. function tapTouchMove(e) {
  2677. if (tapHasPointerMoved(e)) {
  2678. tapPointerMoved = true;
  2679. tapEventListener(tapTouchMoveListener, false);
  2680. ionic.activator.end();
  2681. return false;
  2682. }
  2683. }
  2684. function tapTouchCancel() {
  2685. tapEventListener(tapTouchMoveListener, false);
  2686. ionic.activator.end();
  2687. tapPointerMoved = false;
  2688. }
  2689. function tapEnableTouchEvents() {
  2690. tapEnabledTouchEvents = true;
  2691. clearTimeout(tapMouseResetTimer);
  2692. tapMouseResetTimer = setTimeout(function() {
  2693. tapEnabledTouchEvents = false;
  2694. }, 600);
  2695. }
  2696. function tapIgnoreEvent(e) {
  2697. if (e.isTapHandled) return true;
  2698. e.isTapHandled = true;
  2699. if(ionic.tap.isElementTapDisabled(e.target)) {
  2700. return true;
  2701. }
  2702. if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) {
  2703. e.preventDefault();
  2704. return true;
  2705. }
  2706. }
  2707. function tapHandleFocus(ele) {
  2708. tapTouchFocusedInput = null;
  2709. var triggerFocusIn = false;
  2710. if (ele.tagName == 'SELECT') {
  2711. // trick to force Android options to show up
  2712. triggerMouseEvent('mousedown', ele, 0, 0);
  2713. ele.focus && ele.focus();
  2714. triggerFocusIn = true;
  2715. } else if (tapActiveElement() === ele) {
  2716. // already is the active element and has focus
  2717. triggerFocusIn = true;
  2718. } else if ((/^(input|textarea|ion-label)$/i).test(ele.tagName) || ele.isContentEditable) {
  2719. triggerFocusIn = true;
  2720. ele.focus && ele.focus();
  2721. ele.value = ele.value;
  2722. if (tapEnabledTouchEvents) {
  2723. tapTouchFocusedInput = ele;
  2724. }
  2725. } else {
  2726. tapFocusOutActive();
  2727. }
  2728. if (triggerFocusIn) {
  2729. tapActiveElement(ele);
  2730. ionic.trigger('ionic.focusin', {
  2731. target: ele
  2732. }, true);
  2733. }
  2734. }
  2735. function tapFocusOutActive() {
  2736. var ele = tapActiveElement();
  2737. if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) {
  2738. //console.log('tapFocusOutActive', ele.tagName);
  2739. ele.blur();
  2740. }
  2741. tapActiveElement(null);
  2742. }
  2743. function tapFocusIn(e) {
  2744. //console.log('focusin ' + Date.now());
  2745. // Because a text input doesn't preventDefault (so the caret still works) there's a chance
  2746. // that its mousedown event 300ms later will change the focus to another element after
  2747. // the keyboard shows up.
  2748. if (tapEnabledTouchEvents &&
  2749. ionic.tap.isTextInput(tapActiveElement()) &&
  2750. ionic.tap.isTextInput(tapTouchFocusedInput) &&
  2751. tapTouchFocusedInput !== e.target) {
  2752. // 1) The pointer is from touch events
  2753. // 2) There is an active element which is a text input
  2754. // 3) A text input was just set to be focused on by a touch event
  2755. // 4) A new focus has been set, however the target isn't the one the touch event wanted
  2756. //console.log('focusin', 'tapTouchFocusedInput');
  2757. tapTouchFocusedInput.focus();
  2758. tapTouchFocusedInput = null;
  2759. }
  2760. ionic.scroll.isScrolling = false;
  2761. }
  2762. function tapFocusOut() {
  2763. //console.log("focusout");
  2764. tapActiveElement(null);
  2765. }
  2766. function tapActiveElement(ele) {
  2767. if (arguments.length) {
  2768. tapActiveEle = ele;
  2769. }
  2770. return tapActiveEle || document.activeElement;
  2771. }
  2772. function tapHasPointerMoved(endEvent) {
  2773. if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) {
  2774. return false;
  2775. }
  2776. var endCoordinates = ionic.tap.pointerCoord(endEvent);
  2777. var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains &&
  2778. typeof endEvent.target.classList.contains === 'function');
  2779. var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ?
  2780. TAP_RELEASE_BUTTON_TOLERANCE :
  2781. TAP_RELEASE_TOLERANCE;
  2782. return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance ||
  2783. Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance;
  2784. }
  2785. function tapContainingElement(ele, allowSelf) {
  2786. var climbEle = ele;
  2787. for (var x = 0; x < 6; x++) {
  2788. if (!climbEle) break;
  2789. if (climbEle.tagName === 'LABEL') return climbEle;
  2790. climbEle = climbEle.parentElement;
  2791. }
  2792. if (allowSelf !== false) return ele;
  2793. }
  2794. function tapTargetElement(ele) {
  2795. if (ele && ele.tagName === 'LABEL') {
  2796. if (ele.control) return ele.control;
  2797. // older devices do not support the "control" property
  2798. if (ele.querySelector) {
  2799. var control = ele.querySelector('input,textarea,select');
  2800. if (control) return control;
  2801. }
  2802. }
  2803. return ele;
  2804. }
  2805. function isSelectOrOption(tagName){
  2806. return (/^(select|option)$/i).test(tagName);
  2807. }
  2808. ionic.DomUtil.ready(function() {
  2809. var ng = typeof angular !== 'undefined' ? angular : null;
  2810. //do nothing for e2e tests
  2811. if (!ng || (ng && !ng.scenario)) {
  2812. ionic.tap.register(document);
  2813. }
  2814. });
  2815. (function(document, ionic) {
  2816. 'use strict';
  2817. var queueElements = {}; // elements that should get an active state in XX milliseconds
  2818. var activeElements = {}; // elements that are currently active
  2819. var keyId = 0; // a counter for unique keys for the above ojects
  2820. var ACTIVATED_CLASS = 'activated';
  2821. ionic.activator = {
  2822. start: function(e) {
  2823. var hitX = ionic.tap.pointerCoord(e).x;
  2824. if (hitX > 0 && hitX < 30) {
  2825. return;
  2826. }
  2827. // when an element is touched/clicked, it climbs up a few
  2828. // parents to see if it is an .item or .button element
  2829. ionic.requestAnimationFrame(function() {
  2830. if ((ionic.scroll && ionic.scroll.isScrolling) || ionic.tap.requiresNativeClick(e.target)) return;
  2831. var ele = e.target;
  2832. var eleToActivate;
  2833. for (var x = 0; x < 6; x++) {
  2834. if (!ele || ele.nodeType !== 1) break;
  2835. if (eleToActivate && ele.classList && ele.classList.contains('item')) {
  2836. eleToActivate = ele;
  2837. break;
  2838. }
  2839. if (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click')) {
  2840. eleToActivate = ele;
  2841. break;
  2842. }
  2843. if (ele.classList && ele.classList.contains('button')) {
  2844. eleToActivate = ele;
  2845. break;
  2846. }
  2847. // no sense climbing past these
  2848. if (ele.tagName == 'ION-CONTENT' || (ele.classList && ele.classList.contains('pane')) || ele.tagName == 'BODY') {
  2849. break;
  2850. }
  2851. ele = ele.parentElement;
  2852. }
  2853. if (eleToActivate) {
  2854. // queue that this element should be set to active
  2855. queueElements[keyId] = eleToActivate;
  2856. // on the next frame, set the queued elements to active
  2857. ionic.requestAnimationFrame(activateElements);
  2858. keyId = (keyId > 29 ? 0 : keyId + 1);
  2859. }
  2860. });
  2861. },
  2862. end: function() {
  2863. // clear out any active/queued elements after XX milliseconds
  2864. setTimeout(clear, 200);
  2865. }
  2866. };
  2867. function clear() {
  2868. // clear out any elements that are queued to be set to active
  2869. queueElements = {};
  2870. // in the next frame, remove the active class from all active elements
  2871. ionic.requestAnimationFrame(deactivateElements);
  2872. }
  2873. function activateElements() {
  2874. // activate all elements in the queue
  2875. for (var key in queueElements) {
  2876. if (queueElements[key]) {
  2877. queueElements[key].classList.add(ACTIVATED_CLASS);
  2878. activeElements[key] = queueElements[key];
  2879. }
  2880. }
  2881. queueElements = {};
  2882. }
  2883. function deactivateElements() {
  2884. if (ionic.transition && ionic.transition.isActive) {
  2885. setTimeout(deactivateElements, 400);
  2886. return;
  2887. }
  2888. for (var key in activeElements) {
  2889. if (activeElements[key]) {
  2890. activeElements[key].classList.remove(ACTIVATED_CLASS);
  2891. delete activeElements[key];
  2892. }
  2893. }
  2894. }
  2895. })(document, ionic);
  2896. (function(ionic) {
  2897. /* for nextUid function below */
  2898. var nextId = 0;
  2899. /**
  2900. * Various utilities used throughout Ionic
  2901. *
  2902. * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed.
  2903. */
  2904. ionic.Utils = {
  2905. arrayMove: function(arr, oldIndex, newIndex) {
  2906. if (newIndex >= arr.length) {
  2907. var k = newIndex - arr.length;
  2908. while ((k--) + 1) {
  2909. arr.push(undefined);
  2910. }
  2911. }
  2912. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  2913. return arr;
  2914. },
  2915. /**
  2916. * Return a function that will be called with the given context
  2917. */
  2918. proxy: function(func, context) {
  2919. var args = Array.prototype.slice.call(arguments, 2);
  2920. return function() {
  2921. return func.apply(context, args.concat(Array.prototype.slice.call(arguments)));
  2922. };
  2923. },
  2924. /**
  2925. * Only call a function once in the given interval.
  2926. *
  2927. * @param func {Function} the function to call
  2928. * @param wait {int} how long to wait before/after to allow function calls
  2929. * @param immediate {boolean} whether to call immediately or after the wait interval
  2930. */
  2931. debounce: function(func, wait, immediate) {
  2932. var timeout, args, context, timestamp, result;
  2933. return function() {
  2934. context = this;
  2935. args = arguments;
  2936. timestamp = new Date();
  2937. var later = function() {
  2938. var last = (new Date()) - timestamp;
  2939. if (last < wait) {
  2940. timeout = setTimeout(later, wait - last);
  2941. } else {
  2942. timeout = null;
  2943. if (!immediate) result = func.apply(context, args);
  2944. }
  2945. };
  2946. var callNow = immediate && !timeout;
  2947. if (!timeout) {
  2948. timeout = setTimeout(later, wait);
  2949. }
  2950. if (callNow) result = func.apply(context, args);
  2951. return result;
  2952. };
  2953. },
  2954. /**
  2955. * Throttle the given fun, only allowing it to be
  2956. * called at most every `wait` ms.
  2957. */
  2958. throttle: function(func, wait, options) {
  2959. var context, args, result;
  2960. var timeout = null;
  2961. var previous = 0;
  2962. options || (options = {});
  2963. var later = function() {
  2964. previous = options.leading === false ? 0 : Date.now();
  2965. timeout = null;
  2966. result = func.apply(context, args);
  2967. };
  2968. return function() {
  2969. var now = Date.now();
  2970. if (!previous && options.leading === false) previous = now;
  2971. var remaining = wait - (now - previous);
  2972. context = this;
  2973. args = arguments;
  2974. if (remaining <= 0) {
  2975. clearTimeout(timeout);
  2976. timeout = null;
  2977. previous = now;
  2978. result = func.apply(context, args);
  2979. } else if (!timeout && options.trailing !== false) {
  2980. timeout = setTimeout(later, remaining);
  2981. }
  2982. return result;
  2983. };
  2984. },
  2985. // Borrowed from Backbone.js's extend
  2986. // Helper function to correctly set up the prototype chain, for subclasses.
  2987. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  2988. // class properties to be extended.
  2989. inherit: function(protoProps, staticProps) {
  2990. var parent = this;
  2991. var child;
  2992. // The constructor function for the new subclass is either defined by you
  2993. // (the "constructor" property in your `extend` definition), or defaulted
  2994. // by us to simply call the parent's constructor.
  2995. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  2996. child = protoProps.constructor;
  2997. } else {
  2998. child = function() { return parent.apply(this, arguments); };
  2999. }
  3000. // Add static properties to the constructor function, if supplied.
  3001. ionic.extend(child, parent, staticProps);
  3002. // Set the prototype chain to inherit from `parent`, without calling
  3003. // `parent`'s constructor function.
  3004. var Surrogate = function() { this.constructor = child; };
  3005. Surrogate.prototype = parent.prototype;
  3006. child.prototype = new Surrogate();
  3007. // Add prototype properties (instance properties) to the subclass,
  3008. // if supplied.
  3009. if (protoProps) ionic.extend(child.prototype, protoProps);
  3010. // Set a convenience property in case the parent's prototype is needed
  3011. // later.
  3012. child.__super__ = parent.prototype;
  3013. return child;
  3014. },
  3015. // Extend adapted from Underscore.js
  3016. extend: function(obj) {
  3017. var args = Array.prototype.slice.call(arguments, 1);
  3018. for (var i = 0; i < args.length; i++) {
  3019. var source = args[i];
  3020. if (source) {
  3021. for (var prop in source) {
  3022. obj[prop] = source[prop];
  3023. }
  3024. }
  3025. }
  3026. return obj;
  3027. },
  3028. nextUid: function() {
  3029. return 'ion' + (nextId++);
  3030. },
  3031. disconnectScope: function disconnectScope(scope) {
  3032. if (!scope) return;
  3033. if (scope.$root === scope) {
  3034. return; // we can't disconnect the root node;
  3035. }
  3036. var parent = scope.$parent;
  3037. scope.$$disconnected = true;
  3038. scope.$broadcast('$ionic.disconnectScope', scope);
  3039. // See Scope.$destroy
  3040. if (parent.$$childHead === scope) {
  3041. parent.$$childHead = scope.$$nextSibling;
  3042. }
  3043. if (parent.$$childTail === scope) {
  3044. parent.$$childTail = scope.$$prevSibling;
  3045. }
  3046. if (scope.$$prevSibling) {
  3047. scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;
  3048. }
  3049. if (scope.$$nextSibling) {
  3050. scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;
  3051. }
  3052. scope.$$nextSibling = scope.$$prevSibling = null;
  3053. },
  3054. reconnectScope: function reconnectScope(scope) {
  3055. if (!scope) return;
  3056. if (scope.$root === scope) {
  3057. return; // we can't disconnect the root node;
  3058. }
  3059. if (!scope.$$disconnected) {
  3060. return;
  3061. }
  3062. var parent = scope.$parent;
  3063. scope.$$disconnected = false;
  3064. scope.$broadcast('$ionic.reconnectScope', scope);
  3065. // See Scope.$new for this logic...
  3066. scope.$$prevSibling = parent.$$childTail;
  3067. if (parent.$$childHead) {
  3068. parent.$$childTail.$$nextSibling = scope;
  3069. parent.$$childTail = scope;
  3070. } else {
  3071. parent.$$childHead = parent.$$childTail = scope;
  3072. }
  3073. },
  3074. isScopeDisconnected: function(scope) {
  3075. var climbScope = scope;
  3076. while (climbScope) {
  3077. if (climbScope.$$disconnected) return true;
  3078. climbScope = climbScope.$parent;
  3079. }
  3080. return false;
  3081. }
  3082. };
  3083. // Bind a few of the most useful functions to the ionic scope
  3084. ionic.inherit = ionic.Utils.inherit;
  3085. ionic.extend = ionic.Utils.extend;
  3086. ionic.throttle = ionic.Utils.throttle;
  3087. ionic.proxy = ionic.Utils.proxy;
  3088. ionic.debounce = ionic.Utils.debounce;
  3089. })(window.ionic);
  3090. /**
  3091. * @ngdoc page
  3092. * @name keyboard
  3093. * @module ionic
  3094. * @description
  3095. * On both Android and iOS, Ionic will attempt to prevent the keyboard from
  3096. * obscuring inputs and focusable elements when it appears by scrolling them
  3097. * into view. In order for this to work, any focusable elements must be within
  3098. * a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/)
  3099. * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/)
  3100. * that has a Scroll View.
  3101. *
  3102. * It will also attempt to prevent the native overflow scrolling on focus,
  3103. * which can cause layout issues such as pushing headers up and out of view.
  3104. *
  3105. * The keyboard fixes work best in conjunction with the
  3106. * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard),
  3107. * although it will perform reasonably well without. However, if you are using
  3108. * Cordova there is no reason not to use the plugin.
  3109. *
  3110. * ### Hide when keyboard shows
  3111. *
  3112. * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`.
  3113. *
  3114. * ```html
  3115. * <div class="hide-on-keyboard-open">
  3116. * <div id="google-map"></div>
  3117. * </div>
  3118. * ```
  3119. *
  3120. * Note: For performance reasons, elements will not be hidden for 400ms after the start of the `native.keyboardshow` event
  3121. * from the Ionic Keyboard plugin. If you would like them to disappear immediately, you could do something
  3122. * like:
  3123. *
  3124. * ```js
  3125. * window.addEventListener('native.keyboardshow', function(){
  3126. * document.body.classList.add('keyboard-open');
  3127. * });
  3128. * ```
  3129. * This adds the same `keyboard-open` class that is normally added by Ionic 400ms after the keyboard
  3130. * opens. However, bear in mind that adding this class to the body immediately may cause jank in any
  3131. * animations on Android that occur when the keyboard opens (for example, scrolling any obscured inputs into view).
  3132. *
  3133. * ----------
  3134. *
  3135. * ### Plugin Usage
  3136. * Information on using the plugin can be found at
  3137. * [https://github.com/driftyco/ionic-plugins-keyboard](https://github.com/driftyco/ionic-plugins-keyboard).
  3138. *
  3139. * ----------
  3140. *
  3141. * ### Android Notes
  3142. * - If your app is running in fullscreen, i.e. you have
  3143. * `<preference name="Fullscreen" value="true" />` in your `config.xml` file
  3144. * you will need to set `ionic.Platform.isFullScreen = true` manually.
  3145. *
  3146. * - You can configure the behavior of the web view when the keyboard shows by setting
  3147. * [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode)
  3148. * to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's
  3149. * activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting
  3150. * for Ionic, but if for some reason you do use `adjustPan` you will need to
  3151. * set `ionic.Platform.isFullScreen = true`.
  3152. *
  3153. * ```xml
  3154. * <activity android:windowSoftInputMode="adjustResize">
  3155. *
  3156. * ```
  3157. *
  3158. * ### iOS Notes
  3159. * - If the content of your app (including the header) is being pushed up and
  3160. * out of view on input focus, try setting `cordova.plugins.Keyboard.disableScroll(true)`.
  3161. * This does **not** disable scrolling in the Ionic scroll view, rather it
  3162. * disables the native overflow scrolling that happens automatically as a
  3163. * result of focusing on inputs below the keyboard.
  3164. *
  3165. */
  3166. /**
  3167. * The current viewport height.
  3168. */
  3169. var keyboardCurrentViewportHeight = 0;
  3170. /**
  3171. * The viewport height when in portrait orientation.
  3172. */
  3173. var keyboardPortraitViewportHeight = 0;
  3174. /**
  3175. * The viewport height when in landscape orientation.
  3176. */
  3177. var keyboardLandscapeViewportHeight = 0;
  3178. /**
  3179. * The currently focused input.
  3180. */
  3181. var keyboardActiveElement;
  3182. /**
  3183. * The previously focused input used to reset keyboard after focusing on a
  3184. * new non-keyboard element
  3185. */
  3186. var lastKeyboardActiveElement;
  3187. /**
  3188. * The scroll view containing the currently focused input.
  3189. */
  3190. var scrollView;
  3191. /**
  3192. * Timer for the setInterval that polls window.innerHeight to determine whether
  3193. * the layout has updated for the keyboard showing/hiding.
  3194. */
  3195. var waitForResizeTimer;
  3196. /**
  3197. * Sometimes when switching inputs or orientations, focusout will fire before
  3198. * focusin, so this timer is for the small setTimeout to determine if we should
  3199. * really focusout/hide the keyboard.
  3200. */
  3201. var keyboardFocusOutTimer;
  3202. /**
  3203. * on Android, orientationchange will fire before the keyboard plugin notifies
  3204. * the browser that the keyboard will show/is showing, so this flag indicates
  3205. * to nativeShow that there was an orientationChange and we should update
  3206. * the viewport height with an accurate keyboard height value
  3207. */
  3208. var wasOrientationChange = false;
  3209. /**
  3210. * CSS class added to the body indicating the keyboard is open.
  3211. */
  3212. var KEYBOARD_OPEN_CSS = 'keyboard-open';
  3213. /**
  3214. * CSS class that indicates a scroll container.
  3215. */
  3216. var SCROLL_CONTAINER_CSS = 'scroll-content';
  3217. /**
  3218. * Debounced keyboardFocusIn function
  3219. */
  3220. var debouncedKeyboardFocusIn = ionic.debounce(keyboardFocusIn, 200, true);
  3221. /**
  3222. * Debounced keyboardNativeShow function
  3223. */
  3224. var debouncedKeyboardNativeShow = ionic.debounce(keyboardNativeShow, 100, true);
  3225. /**
  3226. * Ionic keyboard namespace.
  3227. * @namespace keyboard
  3228. */
  3229. ionic.keyboard = {
  3230. /**
  3231. * Whether the keyboard is open or not.
  3232. */
  3233. isOpen: false,
  3234. /**
  3235. * Whether the keyboard is closing or not.
  3236. */
  3237. isClosing: false,
  3238. /**
  3239. * Whether the keyboard is opening or not.
  3240. */
  3241. isOpening: false,
  3242. /**
  3243. * The height of the keyboard in pixels, as reported by the keyboard plugin.
  3244. * If the plugin is not available, calculated as the difference in
  3245. * window.innerHeight after the keyboard has shown.
  3246. */
  3247. height: 0,
  3248. /**
  3249. * Whether the device is in landscape orientation or not.
  3250. */
  3251. isLandscape: false,
  3252. /**
  3253. * Whether the keyboard event listeners have been added or not
  3254. */
  3255. isInitialized: false,
  3256. /**
  3257. * Hide the keyboard, if it is open.
  3258. */
  3259. hide: function() {
  3260. if (keyboardHasPlugin()) {
  3261. cordova.plugins.Keyboard.close();
  3262. }
  3263. keyboardActiveElement && keyboardActiveElement.blur();
  3264. },
  3265. /**
  3266. * An alias for cordova.plugins.Keyboard.show(). If the keyboard plugin
  3267. * is installed, show the keyboard.
  3268. */
  3269. show: function() {
  3270. if (keyboardHasPlugin()) {
  3271. cordova.plugins.Keyboard.show();
  3272. }
  3273. },
  3274. /**
  3275. * Remove all keyboard related event listeners, effectively disabling Ionic's
  3276. * keyboard adjustments.
  3277. */
  3278. disable: function() {
  3279. if (keyboardHasPlugin()) {
  3280. window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );
  3281. window.removeEventListener('native.keyboardhide', keyboardFocusOut);
  3282. } else {
  3283. document.body.removeEventListener('focusout', keyboardFocusOut);
  3284. }
  3285. document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);
  3286. document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);
  3287. window.removeEventListener('orientationchange', keyboardOrientationChange);
  3288. if ( window.navigator.msPointerEnabled ) {
  3289. document.removeEventListener("MSPointerDown", keyboardInit);
  3290. } else {
  3291. document.removeEventListener('touchstart', keyboardInit);
  3292. }
  3293. ionic.keyboard.isInitialized = false;
  3294. },
  3295. /**
  3296. * Alias for keyboardInit, initialize all keyboard related event listeners.
  3297. */
  3298. enable: function() {
  3299. keyboardInit();
  3300. }
  3301. };
  3302. // Initialize the viewport height (after ionic.keyboard.height has been
  3303. // defined).
  3304. keyboardCurrentViewportHeight = getViewportHeight();
  3305. /* Event handlers */
  3306. /* ------------------------------------------------------------------------- */
  3307. /**
  3308. * Event handler for first touch event, initializes all event listeners
  3309. * for keyboard related events. Also aliased by ionic.keyboard.enable.
  3310. */
  3311. function keyboardInit() {
  3312. if (ionic.keyboard.isInitialized) return;
  3313. if (keyboardHasPlugin()) {
  3314. window.addEventListener('native.keyboardshow', debouncedKeyboardNativeShow);
  3315. window.addEventListener('native.keyboardhide', keyboardFocusOut);
  3316. } else {
  3317. document.body.addEventListener('focusout', keyboardFocusOut);
  3318. }
  3319. document.body.addEventListener('ionic.focusin', debouncedKeyboardFocusIn);
  3320. document.body.addEventListener('focusin', debouncedKeyboardFocusIn);
  3321. if (window.navigator.msPointerEnabled) {
  3322. document.removeEventListener("MSPointerDown", keyboardInit);
  3323. } else {
  3324. document.removeEventListener('touchstart', keyboardInit);
  3325. }
  3326. ionic.keyboard.isInitialized = true;
  3327. }
  3328. /**
  3329. * Event handler for 'native.keyboardshow' event, sets keyboard.height to the
  3330. * reported height and keyboard.isOpening to true. Then calls
  3331. * keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as
  3332. * the callback depending on whether the event was triggered by a focusin or
  3333. * an orientationchange.
  3334. */
  3335. function keyboardNativeShow(e) {
  3336. clearTimeout(keyboardFocusOutTimer);
  3337. //console.log("keyboardNativeShow fired at: " + Date.now());
  3338. //console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight);
  3339. if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
  3340. ionic.keyboard.isOpening = true;
  3341. ionic.keyboard.isClosing = false;
  3342. }
  3343. ionic.keyboard.height = e.keyboardHeight;
  3344. //console.log('nativeshow keyboard height:' + e.keyboardHeight);
  3345. if (wasOrientationChange) {
  3346. keyboardWaitForResize(keyboardUpdateViewportHeight, true);
  3347. } else {
  3348. keyboardWaitForResize(keyboardShow, true);
  3349. }
  3350. }
  3351. /**
  3352. * Event handler for 'focusin' and 'ionic.focusin' events. Initializes
  3353. * keyboard state (keyboardActiveElement and keyboard.isOpening) for the
  3354. * appropriate adjustments once the window has resized. If not using the
  3355. * keyboard plugin, calls keyboardWaitForResize with keyboardShow as the
  3356. * callback or keyboardShow right away if the keyboard is already open. If
  3357. * using the keyboard plugin does nothing and lets keyboardNativeShow handle
  3358. * adjustments with a more accurate keyboard height.
  3359. */
  3360. function keyboardFocusIn(e) {
  3361. clearTimeout(keyboardFocusOutTimer);
  3362. //console.log("keyboardFocusIn from: " + e.type + " at: " + Date.now());
  3363. if (!e.target ||
  3364. e.target.readOnly ||
  3365. !ionic.tap.isKeyboardElement(e.target) ||
  3366. !(scrollView = ionic.DomUtil.getParentWithClass(e.target, SCROLL_CONTAINER_CSS))) {
  3367. if (keyboardActiveElement) {
  3368. lastKeyboardActiveElement = keyboardActiveElement;
  3369. }
  3370. keyboardActiveElement = null;
  3371. return;
  3372. }
  3373. keyboardActiveElement = e.target;
  3374. // if using JS scrolling, undo the effects of native overflow scroll so the
  3375. // scroll view is positioned correctly
  3376. if (!scrollView.classList.contains("overflow-scroll")) {
  3377. document.body.scrollTop = 0;
  3378. scrollView.scrollTop = 0;
  3379. ionic.requestAnimationFrame(function(){
  3380. document.body.scrollTop = 0;
  3381. scrollView.scrollTop = 0;
  3382. });
  3383. // any showing part of the document that isn't within the scroll the user
  3384. // could touchmove and cause some ugly changes to the app, so disable
  3385. // any touchmove events while the keyboard is open using e.preventDefault()
  3386. if (window.navigator.msPointerEnabled) {
  3387. document.addEventListener("MSPointerMove", keyboardPreventDefault, false);
  3388. } else {
  3389. document.addEventListener('touchmove', keyboardPreventDefault, false);
  3390. }
  3391. }
  3392. if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
  3393. ionic.keyboard.isOpening = true;
  3394. ionic.keyboard.isClosing = false;
  3395. }
  3396. // attempt to prevent browser from natively scrolling input into view while
  3397. // we are trying to do the same (while we are scrolling) if the user taps the
  3398. // keyboard
  3399. document.addEventListener('keydown', keyboardOnKeyDown, false);
  3400. // if we aren't using the plugin and the keyboard isn't open yet, wait for the
  3401. // window to resize so we can get an accurate estimate of the keyboard size,
  3402. // otherwise we do nothing and let nativeShow call keyboardShow once we have
  3403. // an exact keyboard height
  3404. // if the keyboard is already open, go ahead and scroll the input into view
  3405. // if necessary
  3406. if (!ionic.keyboard.isOpen && !keyboardHasPlugin()) {
  3407. keyboardWaitForResize(keyboardShow, true);
  3408. } else if (ionic.keyboard.isOpen) {
  3409. keyboardShow();
  3410. }
  3411. }
  3412. /**
  3413. * Event handler for 'focusout' events. Sets keyboard.isClosing to true and
  3414. * calls keyboardWaitForResize with keyboardHide as the callback after a small
  3415. * timeout.
  3416. */
  3417. function keyboardFocusOut() {
  3418. clearTimeout(keyboardFocusOutTimer);
  3419. //console.log("keyboardFocusOut fired at: " + Date.now());
  3420. //console.log("keyboardFocusOut event type: " + e.type);
  3421. if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {
  3422. ionic.keyboard.isClosing = true;
  3423. ionic.keyboard.isOpening = false;
  3424. }
  3425. // Call keyboardHide with a slight delay because sometimes on focus or
  3426. // orientation change focusin is called immediately after, so we give it time
  3427. // to cancel keyboardHide
  3428. keyboardFocusOutTimer = setTimeout(function() {
  3429. ionic.requestAnimationFrame(function() {
  3430. // focusOut during or right after an orientationchange, so we didn't get
  3431. // a chance to update the viewport height yet, do it and keyboardHide
  3432. //console.log("focusOut, wasOrientationChange: " + wasOrientationChange);
  3433. if (wasOrientationChange) {
  3434. keyboardWaitForResize(function(){
  3435. keyboardUpdateViewportHeight();
  3436. keyboardHide();
  3437. }, false);
  3438. } else {
  3439. keyboardWaitForResize(keyboardHide, false);
  3440. }
  3441. });
  3442. }, 50);
  3443. }
  3444. /**
  3445. * Event handler for 'orientationchange' events. If using the keyboard plugin
  3446. * and the keyboard is open on Android, sets wasOrientationChange to true so
  3447. * nativeShow can update the viewport height with an accurate keyboard height.
  3448. * If the keyboard isn't open or keyboard plugin isn't being used,
  3449. * waits for the window to resize before updating the viewport height.
  3450. *
  3451. * On iOS, where orientationchange fires after the keyboard has already shown,
  3452. * updates the viewport immediately, regardless of if the keyboard is already
  3453. * open.
  3454. */
  3455. function keyboardOrientationChange() {
  3456. //console.log("orientationchange fired at: " + Date.now());
  3457. //console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
  3458. // toggle orientation
  3459. ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;
  3460. // //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
  3461. // no need to wait for resizing on iOS, and orientationchange always fires
  3462. // after the keyboard has opened, so it doesn't matter if it's open or not
  3463. if (ionic.Platform.isIOS()) {
  3464. keyboardUpdateViewportHeight();
  3465. }
  3466. // On Android, if the keyboard isn't open or we aren't using the keyboard
  3467. // plugin, update the viewport height once everything has resized. If the
  3468. // keyboard is open and we are using the keyboard plugin do nothing and let
  3469. // nativeShow handle it using an accurate keyboard height.
  3470. if ( ionic.Platform.isAndroid()) {
  3471. if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {
  3472. keyboardWaitForResize(keyboardUpdateViewportHeight, false);
  3473. } else {
  3474. wasOrientationChange = true;
  3475. }
  3476. }
  3477. }
  3478. /**
  3479. * Event handler for 'keydown' event. Tries to prevent browser from natively
  3480. * scrolling an input into view when a user taps the keyboard while we are
  3481. * scrolling the input into view ourselves with JS.
  3482. */
  3483. function keyboardOnKeyDown(e) {
  3484. if (ionic.scroll.isScrolling) {
  3485. keyboardPreventDefault(e);
  3486. }
  3487. }
  3488. /**
  3489. * Event for 'touchmove' or 'MSPointerMove'. Prevents native scrolling on
  3490. * elements outside the scroll view while the keyboard is open.
  3491. */
  3492. function keyboardPreventDefault(e) {
  3493. if (e.target.tagName !== 'TEXTAREA') {
  3494. e.preventDefault();
  3495. }
  3496. }
  3497. /* Private API */
  3498. /* -------------------------------------------------------------------------- */
  3499. /**
  3500. * Polls window.innerHeight until it has updated to an expected value (or
  3501. * sufficient time has passed) before calling the specified callback function.
  3502. * Only necessary for non-fullscreen Android which sometimes reports multiple
  3503. * window.innerHeight values during interim layouts while it is resizing.
  3504. *
  3505. * On iOS, the window.innerHeight will already be updated, but we use the 50ms
  3506. * delay as essentially a timeout so that scroll view adjustments happen after
  3507. * the keyboard has shown so there isn't a white flash from us resizing too
  3508. * quickly.
  3509. *
  3510. * @param {Function} callback the function to call once the window has resized
  3511. * @param {boolean} isOpening whether the resize is from the keyboard opening
  3512. * or not
  3513. */
  3514. function keyboardWaitForResize(callback, isOpening) {
  3515. clearInterval(waitForResizeTimer);
  3516. var count = 0;
  3517. var maxCount;
  3518. var initialHeight = getViewportHeight();
  3519. var viewportHeight = initialHeight;
  3520. //console.log("waitForResize initial viewport height: " + viewportHeight);
  3521. //var start = Date.now();
  3522. //console.log("start: " + start);
  3523. // want to fail relatively quickly on modern android devices, since it's much
  3524. // more likely we just have a bad keyboard height
  3525. if (ionic.Platform.isAndroid() && ionic.Platform.version() < 4.4) {
  3526. maxCount = 30;
  3527. } else if (ionic.Platform.isAndroid()) {
  3528. maxCount = 10;
  3529. } else {
  3530. maxCount = 1;
  3531. }
  3532. // poll timer
  3533. waitForResizeTimer = setInterval(function(){
  3534. viewportHeight = getViewportHeight();
  3535. // height hasn't updated yet, try again in 50ms
  3536. // if not using plugin, wait for maxCount to ensure we have waited long enough
  3537. // to get an accurate keyboard height
  3538. if (++count < maxCount &&
  3539. ((!isPortraitViewportHeight(viewportHeight) &&
  3540. !isLandscapeViewportHeight(viewportHeight)) ||
  3541. !ionic.keyboard.height)) {
  3542. return;
  3543. }
  3544. // infer the keyboard height from the resize if not using the keyboard plugin
  3545. if (!keyboardHasPlugin()) {
  3546. ionic.keyboard.height = Math.abs(initialHeight - window.innerHeight);
  3547. }
  3548. // set to true if we were waiting for the keyboard to open
  3549. ionic.keyboard.isOpen = isOpening;
  3550. clearInterval(waitForResizeTimer);
  3551. //var end = Date.now();
  3552. //console.log("waitForResize count: " + count);
  3553. //console.log("end: " + end);
  3554. //console.log("difference: " + ( end - start ) + "ms");
  3555. //console.log("callback: " + callback.name);
  3556. callback();
  3557. }, 50);
  3558. return maxCount; //for tests
  3559. }
  3560. /**
  3561. * On keyboard close sets keyboard state to closed, resets the scroll view,
  3562. * removes CSS from body indicating keyboard was open, removes any event
  3563. * listeners for when the keyboard is open and on Android blurs the active
  3564. * element (which in some cases will still have focus even if the keyboard
  3565. * is closed and can cause it to reappear on subsequent taps).
  3566. */
  3567. function keyboardHide() {
  3568. clearTimeout(keyboardFocusOutTimer);
  3569. //console.log("keyboardHide");
  3570. ionic.keyboard.isOpen = false;
  3571. ionic.keyboard.isClosing = false;
  3572. if (keyboardActiveElement || lastKeyboardActiveElement) {
  3573. ionic.trigger('resetScrollView', {
  3574. target: keyboardActiveElement || lastKeyboardActiveElement
  3575. }, true);
  3576. }
  3577. ionic.requestAnimationFrame(function(){
  3578. document.body.classList.remove(KEYBOARD_OPEN_CSS);
  3579. });
  3580. // the keyboard is gone now, remove the touchmove that disables native scroll
  3581. if (window.navigator.msPointerEnabled) {
  3582. document.removeEventListener("MSPointerMove", keyboardPreventDefault);
  3583. } else {
  3584. document.removeEventListener('touchmove', keyboardPreventDefault);
  3585. }
  3586. document.removeEventListener('keydown', keyboardOnKeyDown);
  3587. if (ionic.Platform.isAndroid()) {
  3588. // on android closing the keyboard with the back/dismiss button won't remove
  3589. // focus and keyboard can re-appear on subsequent taps (like scrolling)
  3590. if (keyboardHasPlugin()) cordova.plugins.Keyboard.close();
  3591. keyboardActiveElement && keyboardActiveElement.blur();
  3592. }
  3593. keyboardActiveElement = null;
  3594. lastKeyboardActiveElement = null;
  3595. }
  3596. /**
  3597. * On keyboard open sets keyboard state to open, adds CSS to the body
  3598. * indicating the keyboard is open and tells the scroll view to resize and
  3599. * the currently focused input into view if necessary.
  3600. */
  3601. function keyboardShow() {
  3602. ionic.keyboard.isOpen = true;
  3603. ionic.keyboard.isOpening = false;
  3604. var details = {
  3605. keyboardHeight: keyboardGetHeight(),
  3606. viewportHeight: keyboardCurrentViewportHeight
  3607. };
  3608. if (keyboardActiveElement) {
  3609. details.target = keyboardActiveElement;
  3610. var elementBounds = keyboardActiveElement.getBoundingClientRect();
  3611. details.elementTop = Math.round(elementBounds.top);
  3612. details.elementBottom = Math.round(elementBounds.bottom);
  3613. details.windowHeight = details.viewportHeight - details.keyboardHeight;
  3614. //console.log("keyboardShow viewportHeight: " + details.viewportHeight +
  3615. //", windowHeight: " + details.windowHeight +
  3616. //", keyboardHeight: " + details.keyboardHeight);
  3617. // figure out if the element is under the keyboard
  3618. details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);
  3619. //console.log("isUnderKeyboard: " + details.isElementUnderKeyboard);
  3620. //console.log("elementBottom: " + details.elementBottom);
  3621. // send event so the scroll view adjusts
  3622. ionic.trigger('scrollChildIntoView', details, true);
  3623. }
  3624. setTimeout(function(){
  3625. document.body.classList.add(KEYBOARD_OPEN_CSS);
  3626. }, 400);
  3627. return details; //for testing
  3628. }
  3629. /* eslint no-unused-vars:0 */
  3630. function keyboardGetHeight() {
  3631. // check if we already have a keyboard height from the plugin or resize calculations
  3632. if (ionic.keyboard.height) {
  3633. return ionic.keyboard.height;
  3634. }
  3635. if (ionic.Platform.isAndroid()) {
  3636. // should be using the plugin, no way to know how big the keyboard is, so guess
  3637. if ( ionic.Platform.isFullScreen ) {
  3638. return 275;
  3639. }
  3640. // otherwise just calculate it
  3641. var contentHeight = window.innerHeight;
  3642. if (contentHeight < keyboardCurrentViewportHeight) {
  3643. return keyboardCurrentViewportHeight - contentHeight;
  3644. } else {
  3645. return 0;
  3646. }
  3647. }
  3648. // fallback for when it's the webview without the plugin
  3649. // or for just the standard web browser
  3650. // TODO: have these be based on device
  3651. if (ionic.Platform.isIOS()) {
  3652. if (ionic.keyboard.isLandscape) {
  3653. return 206;
  3654. }
  3655. if (!ionic.Platform.isWebView()) {
  3656. return 216;
  3657. }
  3658. return 260;
  3659. }
  3660. // safe guess
  3661. return 275;
  3662. }
  3663. function isPortraitViewportHeight(viewportHeight) {
  3664. return !!(!ionic.keyboard.isLandscape &&
  3665. keyboardPortraitViewportHeight &&
  3666. (Math.abs(keyboardPortraitViewportHeight - viewportHeight) < 2));
  3667. }
  3668. function isLandscapeViewportHeight(viewportHeight) {
  3669. return !!(ionic.keyboard.isLandscape &&
  3670. keyboardLandscapeViewportHeight &&
  3671. (Math.abs(keyboardLandscapeViewportHeight - viewportHeight) < 2));
  3672. }
  3673. function keyboardUpdateViewportHeight() {
  3674. wasOrientationChange = false;
  3675. keyboardCurrentViewportHeight = getViewportHeight();
  3676. if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {
  3677. //console.log("saved landscape: " + keyboardCurrentViewportHeight);
  3678. keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;
  3679. } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {
  3680. //console.log("saved portrait: " + keyboardCurrentViewportHeight);
  3681. keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;
  3682. }
  3683. if (keyboardActiveElement) {
  3684. ionic.trigger('resetScrollView', {
  3685. target: keyboardActiveElement
  3686. }, true);
  3687. }
  3688. if (ionic.keyboard.isOpen && ionic.tap.isTextInput(keyboardActiveElement)) {
  3689. keyboardShow();
  3690. }
  3691. }
  3692. function keyboardInitViewportHeight() {
  3693. var viewportHeight = getViewportHeight();
  3694. //console.log("Keyboard init VP: " + viewportHeight + " " + window.innerWidth);
  3695. // can't just use window.innerHeight in case the keyboard is opened immediately
  3696. if ((viewportHeight / window.innerWidth) < 1) {
  3697. ionic.keyboard.isLandscape = true;
  3698. }
  3699. //console.log("ionic.keyboard.isLandscape is: " + ionic.keyboard.isLandscape);
  3700. // initialize or update the current viewport height values
  3701. keyboardCurrentViewportHeight = viewportHeight;
  3702. if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {
  3703. keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;
  3704. } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {
  3705. keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;
  3706. }
  3707. }
  3708. function getViewportHeight() {
  3709. var windowHeight = window.innerHeight;
  3710. //console.log('window.innerHeight is: ' + windowHeight);
  3711. //console.log('kb height is: ' + ionic.keyboard.height);
  3712. //console.log('kb isOpen: ' + ionic.keyboard.isOpen);
  3713. //TODO: add iPad undocked/split kb once kb plugin supports it
  3714. // the keyboard overlays the window on Android fullscreen
  3715. if (!(ionic.Platform.isAndroid() && ionic.Platform.isFullScreen) &&
  3716. (ionic.keyboard.isOpen || ionic.keyboard.isOpening) &&
  3717. !ionic.keyboard.isClosing) {
  3718. return windowHeight + keyboardGetHeight();
  3719. }
  3720. return windowHeight;
  3721. }
  3722. function keyboardHasPlugin() {
  3723. return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard);
  3724. }
  3725. ionic.Platform.ready(function() {
  3726. keyboardInitViewportHeight();
  3727. window.addEventListener('orientationchange', keyboardOrientationChange);
  3728. // if orientation changes while app is in background, update on resuming
  3729. /*
  3730. if ( ionic.Platform.isWebView() ) {
  3731. document.addEventListener('resume', keyboardInitViewportHeight);
  3732. if (ionic.Platform.isAndroid()) {
  3733. //TODO: onbackpressed to detect keyboard close without focusout or plugin
  3734. }
  3735. }
  3736. */
  3737. // if orientation changes while app is in background, update on resuming
  3738. /* if ( ionic.Platform.isWebView() ) {
  3739. document.addEventListener('pause', function() {
  3740. window.removeEventListener('orientationchange', keyboardOrientationChange);
  3741. })
  3742. document.addEventListener('resume', function() {
  3743. keyboardInitViewportHeight();
  3744. window.addEventListener('orientationchange', keyboardOrientationChange)
  3745. });
  3746. }*/
  3747. // Android sometimes reports bad innerHeight on window.load
  3748. // try it again in a lil bit to play it safe
  3749. setTimeout(keyboardInitViewportHeight, 999);
  3750. // only initialize the adjustments for the virtual keyboard
  3751. // if a touchstart event happens
  3752. if (window.navigator.msPointerEnabled) {
  3753. document.addEventListener("MSPointerDown", keyboardInit, false);
  3754. } else {
  3755. document.addEventListener('touchstart', keyboardInit, false);
  3756. }
  3757. });
  3758. var viewportTag;
  3759. var viewportProperties = {};
  3760. ionic.viewport = {
  3761. orientation: function() {
  3762. // 0 = Portrait
  3763. // 90 = Landscape
  3764. // not using window.orientation because each device has a different implementation
  3765. return (window.innerWidth > window.innerHeight ? 90 : 0);
  3766. }
  3767. };
  3768. function viewportLoadTag() {
  3769. var x;
  3770. for (x = 0; x < document.head.children.length; x++) {
  3771. if (document.head.children[x].name == 'viewport') {
  3772. viewportTag = document.head.children[x];
  3773. break;
  3774. }
  3775. }
  3776. if (viewportTag) {
  3777. var props = viewportTag.content.toLowerCase().replace(/\s+/g, '').split(',');
  3778. var keyValue;
  3779. for (x = 0; x < props.length; x++) {
  3780. if (props[x]) {
  3781. keyValue = props[x].split('=');
  3782. viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_');
  3783. }
  3784. }
  3785. viewportUpdate();
  3786. }
  3787. }
  3788. function viewportUpdate() {
  3789. // unit tests in viewport.unit.js
  3790. var initWidth = viewportProperties.width;
  3791. var initHeight = viewportProperties.height;
  3792. var p = ionic.Platform;
  3793. var version = p.version();
  3794. var DEVICE_WIDTH = 'device-width';
  3795. var DEVICE_HEIGHT = 'device-height';
  3796. var orientation = ionic.viewport.orientation();
  3797. // Most times we're removing the height and adding the width
  3798. // So this is the default to start with, then modify per platform/version/oreintation
  3799. delete viewportProperties.height;
  3800. viewportProperties.width = DEVICE_WIDTH;
  3801. if (p.isIPad()) {
  3802. // iPad
  3803. if (version > 7) {
  3804. // iPad >= 7.1
  3805. // https://issues.apache.org/jira/browse/CB-4323
  3806. delete viewportProperties.width;
  3807. } else {
  3808. // iPad <= 7.0
  3809. if (p.isWebView()) {
  3810. // iPad <= 7.0 WebView
  3811. if (orientation == 90) {
  3812. // iPad <= 7.0 WebView Landscape
  3813. viewportProperties.height = '0';
  3814. } else if (version == 7) {
  3815. // iPad <= 7.0 WebView Portait
  3816. viewportProperties.height = DEVICE_HEIGHT;
  3817. }
  3818. } else {
  3819. // iPad <= 6.1 Browser
  3820. if (version < 7) {
  3821. viewportProperties.height = '0';
  3822. }
  3823. }
  3824. }
  3825. } else if (p.isIOS()) {
  3826. // iPhone
  3827. if (p.isWebView()) {
  3828. // iPhone WebView
  3829. if (version > 7) {
  3830. // iPhone >= 7.1 WebView
  3831. delete viewportProperties.width;
  3832. } else if (version < 7) {
  3833. // iPhone <= 6.1 WebView
  3834. // if height was set it needs to get removed with this hack for <= 6.1
  3835. if (initHeight) viewportProperties.height = '0';
  3836. } else if (version == 7) {
  3837. //iPhone == 7.0 WebView
  3838. viewportProperties.height = DEVICE_HEIGHT;
  3839. }
  3840. } else {
  3841. // iPhone Browser
  3842. if (version < 7) {
  3843. // iPhone <= 6.1 Browser
  3844. // if height was set it needs to get removed with this hack for <= 6.1
  3845. if (initHeight) viewportProperties.height = '0';
  3846. }
  3847. }
  3848. }
  3849. // only update the viewport tag if there was a change
  3850. if (initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) {
  3851. viewportTagUpdate();
  3852. }
  3853. }
  3854. function viewportTagUpdate() {
  3855. var key, props = [];
  3856. for (key in viewportProperties) {
  3857. if (viewportProperties[key]) {
  3858. props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key]));
  3859. }
  3860. }
  3861. viewportTag.content = props.join(', ');
  3862. }
  3863. ionic.Platform.ready(function() {
  3864. viewportLoadTag();
  3865. window.addEventListener("orientationchange", function() {
  3866. setTimeout(viewportUpdate, 1000);
  3867. }, false);
  3868. });
  3869. (function(ionic) {
  3870. 'use strict';
  3871. ionic.views.View = function() {
  3872. this.initialize.apply(this, arguments);
  3873. };
  3874. ionic.views.View.inherit = ionic.inherit;
  3875. ionic.extend(ionic.views.View.prototype, {
  3876. initialize: function() {}
  3877. });
  3878. })(window.ionic);
  3879. /*
  3880. * Scroller
  3881. * http://github.com/zynga/scroller
  3882. *
  3883. * Copyright 2011, Zynga Inc.
  3884. * Licensed under the MIT License.
  3885. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
  3886. *
  3887. * Based on the work of: Unify Project (unify-project.org)
  3888. * http://unify-project.org
  3889. * Copyright 2011, Deutsche Telekom AG
  3890. * License: MIT + Apache (V2)
  3891. */
  3892. /* jshint eqnull: true */
  3893. /**
  3894. * Generic animation class with support for dropped frames both optional easing and duration.
  3895. *
  3896. * Optional duration is useful when the lifetime is defined by another condition than time
  3897. * e.g. speed of an animating object, etc.
  3898. *
  3899. * Dropped frame logic allows to keep using the same updater logic independent from the actual
  3900. * rendering. This eases a lot of cases where it might be pretty complex to break down a state
  3901. * based on the pure time difference.
  3902. */
  3903. var zyngaCore = { effect: {} };
  3904. (function(global) {
  3905. var time = Date.now || function() {
  3906. return +new Date();
  3907. };
  3908. var desiredFrames = 60;
  3909. var millisecondsPerSecond = 1000;
  3910. var running = {};
  3911. var counter = 1;
  3912. zyngaCore.effect.Animate = {
  3913. /**
  3914. * A requestAnimationFrame wrapper / polyfill.
  3915. *
  3916. * @param callback {Function} The callback to be invoked before the next repaint.
  3917. * @param root {HTMLElement} The root element for the repaint
  3918. */
  3919. requestAnimationFrame: (function() {
  3920. // Check for request animation Frame support
  3921. var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame;
  3922. var isNative = !!requestFrame;
  3923. if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) {
  3924. isNative = false;
  3925. }
  3926. if (isNative) {
  3927. return function(callback, root) {
  3928. requestFrame(callback, root);
  3929. };
  3930. }
  3931. var TARGET_FPS = 60;
  3932. var requests = {};
  3933. var requestCount = 0;
  3934. var rafHandle = 1;
  3935. var intervalHandle = null;
  3936. var lastActive = +new Date();
  3937. return function(callback) {
  3938. var callbackHandle = rafHandle++;
  3939. // Store callback
  3940. requests[callbackHandle] = callback;
  3941. requestCount++;
  3942. // Create timeout at first request
  3943. if (intervalHandle === null) {
  3944. intervalHandle = setInterval(function() {
  3945. var time = +new Date();
  3946. var currentRequests = requests;
  3947. // Reset data structure before executing callbacks
  3948. requests = {};
  3949. requestCount = 0;
  3950. for(var key in currentRequests) {
  3951. if (currentRequests.hasOwnProperty(key)) {
  3952. currentRequests[key](time);
  3953. lastActive = time;
  3954. }
  3955. }
  3956. // Disable the timeout when nothing happens for a certain
  3957. // period of time
  3958. if (time - lastActive > 2500) {
  3959. clearInterval(intervalHandle);
  3960. intervalHandle = null;
  3961. }
  3962. }, 1000 / TARGET_FPS);
  3963. }
  3964. return callbackHandle;
  3965. };
  3966. })(),
  3967. /**
  3968. * Stops the given animation.
  3969. *
  3970. * @param id {Integer} Unique animation ID
  3971. * @return {Boolean} Whether the animation was stopped (aka, was running before)
  3972. */
  3973. stop: function(id) {
  3974. var cleared = running[id] != null;
  3975. if (cleared) {
  3976. running[id] = null;
  3977. }
  3978. return cleared;
  3979. },
  3980. /**
  3981. * Whether the given animation is still running.
  3982. *
  3983. * @param id {Integer} Unique animation ID
  3984. * @return {Boolean} Whether the animation is still running
  3985. */
  3986. isRunning: function(id) {
  3987. return running[id] != null;
  3988. },
  3989. /**
  3990. * Start the animation.
  3991. *
  3992. * @param stepCallback {Function} Pointer to function which is executed on every step.
  3993. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }`
  3994. * @param verifyCallback {Function} Executed before every animation step.
  3995. * Signature of the method should be `function() { return continueWithAnimation; }`
  3996. * @param completedCallback {Function}
  3997. * Signature of the method should be `function(droppedFrames, finishedAnimation) {}`
  3998. * @param duration {Integer} Milliseconds to run the animation
  3999. * @param easingMethod {Function} Pointer to easing function
  4000. * Signature of the method should be `function(percent) { return modifiedValue; }`
  4001. * @param root {Element} Render root, when available. Used for internal
  4002. * usage of requestAnimationFrame.
  4003. * @return {Integer} Identifier of animation. Can be used to stop it any time.
  4004. */
  4005. start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {
  4006. var start = time();
  4007. var lastFrame = start;
  4008. var percent = 0;
  4009. var dropCounter = 0;
  4010. var id = counter++;
  4011. if (!root) {
  4012. root = document.body;
  4013. }
  4014. // Compacting running db automatically every few new animations
  4015. if (id % 20 === 0) {
  4016. var newRunning = {};
  4017. for (var usedId in running) {
  4018. newRunning[usedId] = true;
  4019. }
  4020. running = newRunning;
  4021. }
  4022. // This is the internal step method which is called every few milliseconds
  4023. var step = function(virtual) {
  4024. // Normalize virtual value
  4025. var render = virtual !== true;
  4026. // Get current time
  4027. var now = time();
  4028. // Verification is executed before next animation step
  4029. if (!running[id] || (verifyCallback && !verifyCallback(id))) {
  4030. running[id] = null;
  4031. completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false);
  4032. return;
  4033. }
  4034. // For the current rendering to apply let's update omitted steps in memory.
  4035. // This is important to bring internal state variables up-to-date with progress in time.
  4036. if (render) {
  4037. var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1;
  4038. for (var j = 0; j < Math.min(droppedFrames, 4); j++) {
  4039. step(true);
  4040. dropCounter++;
  4041. }
  4042. }
  4043. // Compute percent value
  4044. if (duration) {
  4045. percent = (now - start) / duration;
  4046. if (percent > 1) {
  4047. percent = 1;
  4048. }
  4049. }
  4050. // Execute step callback, then...
  4051. var value = easingMethod ? easingMethod(percent) : percent;
  4052. if ((stepCallback(value, now, render) === false || percent === 1) && render) {
  4053. running[id] = null;
  4054. completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null);
  4055. } else if (render) {
  4056. lastFrame = now;
  4057. zyngaCore.effect.Animate.requestAnimationFrame(step, root);
  4058. }
  4059. };
  4060. // Mark as running
  4061. running[id] = true;
  4062. // Init first step
  4063. zyngaCore.effect.Animate.requestAnimationFrame(step, root);
  4064. // Return unique animation ID
  4065. return id;
  4066. }
  4067. };
  4068. })(window);
  4069. /*
  4070. * Scroller
  4071. * http://github.com/zynga/scroller
  4072. *
  4073. * Copyright 2011, Zynga Inc.
  4074. * Licensed under the MIT License.
  4075. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
  4076. *
  4077. * Based on the work of: Unify Project (unify-project.org)
  4078. * http://unify-project.org
  4079. * Copyright 2011, Deutsche Telekom AG
  4080. * License: MIT + Apache (V2)
  4081. */
  4082. (function(ionic) {
  4083. var NOOP = function(){};
  4084. // Easing Equations (c) 2003 Robert Penner, all rights reserved.
  4085. // Open source under the BSD License.
  4086. /**
  4087. * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
  4088. **/
  4089. var easeOutCubic = function(pos) {
  4090. return (Math.pow((pos - 1), 3) + 1);
  4091. };
  4092. /**
  4093. * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
  4094. **/
  4095. var easeInOutCubic = function(pos) {
  4096. if ((pos /= 0.5) < 1) {
  4097. return 0.5 * Math.pow(pos, 3);
  4098. }
  4099. return 0.5 * (Math.pow((pos - 2), 3) + 2);
  4100. };
  4101. /**
  4102. * ionic.views.Scroll
  4103. * A powerful scroll view with support for bouncing, pull to refresh, and paging.
  4104. * @param {Object} options options for the scroll view
  4105. * @class A scroll view system
  4106. * @memberof ionic.views
  4107. */
  4108. ionic.views.Scroll = ionic.views.View.inherit({
  4109. initialize: function(options) {
  4110. var self = this;
  4111. self.__container = options.el;
  4112. self.__content = options.el.firstElementChild;
  4113. //Remove any scrollTop attached to these elements; they are virtual scroll now
  4114. //This also stops on-load-scroll-to-window.location.hash that the browser does
  4115. setTimeout(function() {
  4116. if (self.__container && self.__content) {
  4117. self.__container.scrollTop = 0;
  4118. self.__content.scrollTop = 0;
  4119. }
  4120. });
  4121. self.options = {
  4122. /** Disable scrolling on x-axis by default */
  4123. scrollingX: false,
  4124. scrollbarX: true,
  4125. /** Enable scrolling on y-axis */
  4126. scrollingY: true,
  4127. scrollbarY: true,
  4128. startX: 0,
  4129. startY: 0,
  4130. /** The amount to dampen mousewheel events */
  4131. wheelDampen: 6,
  4132. /** The minimum size the scrollbars scale to while scrolling */
  4133. minScrollbarSizeX: 5,
  4134. minScrollbarSizeY: 5,
  4135. /** Scrollbar fading after scrolling */
  4136. scrollbarsFade: true,
  4137. scrollbarFadeDelay: 300,
  4138. /** The initial fade delay when the pane is resized or initialized */
  4139. scrollbarResizeFadeDelay: 1000,
  4140. /** Enable animations for deceleration, snap back, zooming and scrolling */
  4141. animating: true,
  4142. /** duration for animations triggered by scrollTo/zoomTo */
  4143. animationDuration: 250,
  4144. /** The velocity required to make the scroll view "slide" after touchend */
  4145. decelVelocityThreshold: 4,
  4146. /** The velocity required to make the scroll view "slide" after touchend when using paging */
  4147. decelVelocityThresholdPaging: 4,
  4148. /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */
  4149. bouncing: true,
  4150. /** Enable locking to the main axis if user moves only slightly on one of them at start */
  4151. locking: true,
  4152. /** Enable pagination mode (switching between full page content panes) */
  4153. paging: false,
  4154. /** Enable snapping of content to a configured pixel grid */
  4155. snapping: false,
  4156. /** Enable zooming of content via API, fingers and mouse wheel */
  4157. zooming: false,
  4158. /** Minimum zoom level */
  4159. minZoom: 0.5,
  4160. /** Maximum zoom level */
  4161. maxZoom: 3,
  4162. /** Multiply or decrease scrolling speed **/
  4163. speedMultiplier: 1,
  4164. deceleration: 0.97,
  4165. /** Whether to prevent default on a scroll operation to capture drag events **/
  4166. preventDefault: false,
  4167. /** Callback that is fired on the later of touch end or deceleration end,
  4168. provided that another scrolling action has not begun. Used to know
  4169. when to fade out a scrollbar. */
  4170. scrollingComplete: NOOP,
  4171. /** This configures the amount of change applied to deceleration when reaching boundaries **/
  4172. penetrationDeceleration: 0.03,
  4173. /** This configures the amount of change applied to acceleration when reaching boundaries **/
  4174. penetrationAcceleration: 0.08,
  4175. // The ms interval for triggering scroll events
  4176. scrollEventInterval: 10,
  4177. freeze: false,
  4178. getContentWidth: function() {
  4179. return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);
  4180. },
  4181. getContentHeight: function() {
  4182. return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));
  4183. }
  4184. };
  4185. for (var key in options) {
  4186. self.options[key] = options[key];
  4187. }
  4188. self.hintResize = ionic.debounce(function() {
  4189. self.resize();
  4190. }, 1000, true);
  4191. self.onScroll = function() {
  4192. if (!ionic.scroll.isScrolling) {
  4193. setTimeout(self.setScrollStart, 50);
  4194. } else {
  4195. clearTimeout(self.scrollTimer);
  4196. self.scrollTimer = setTimeout(self.setScrollStop, 80);
  4197. }
  4198. };
  4199. self.freeze = function(shouldFreeze) {
  4200. if (arguments.length) {
  4201. self.options.freeze = shouldFreeze;
  4202. }
  4203. return self.options.freeze;
  4204. };
  4205. // We can just use the standard freeze pop in our mouth
  4206. self.freezeShut = self.freeze;
  4207. self.setScrollStart = function() {
  4208. ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1;
  4209. clearTimeout(self.scrollTimer);
  4210. self.scrollTimer = setTimeout(self.setScrollStop, 80);
  4211. };
  4212. self.setScrollStop = function() {
  4213. ionic.scroll.isScrolling = false;
  4214. ionic.scroll.lastTop = self.__scrollTop;
  4215. };
  4216. self.triggerScrollEvent = ionic.throttle(function() {
  4217. self.onScroll();
  4218. ionic.trigger('scroll', {
  4219. scrollTop: self.__scrollTop,
  4220. scrollLeft: self.__scrollLeft,
  4221. target: self.__container
  4222. });
  4223. }, self.options.scrollEventInterval);
  4224. self.triggerScrollEndEvent = function() {
  4225. ionic.trigger('scrollend', {
  4226. scrollTop: self.__scrollTop,
  4227. scrollLeft: self.__scrollLeft,
  4228. target: self.__container
  4229. });
  4230. };
  4231. self.__scrollLeft = self.options.startX;
  4232. self.__scrollTop = self.options.startY;
  4233. // Get the render update function, initialize event handlers,
  4234. // and calculate the size of the scroll container
  4235. self.__callback = self.getRenderFn();
  4236. self.__initEventHandlers();
  4237. self.__createScrollbars();
  4238. },
  4239. run: function() {
  4240. this.resize();
  4241. // Fade them out
  4242. this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay);
  4243. },
  4244. /*
  4245. ---------------------------------------------------------------------------
  4246. INTERNAL FIELDS :: STATUS
  4247. ---------------------------------------------------------------------------
  4248. */
  4249. /** Whether only a single finger is used in touch handling */
  4250. __isSingleTouch: false,
  4251. /** Whether a touch event sequence is in progress */
  4252. __isTracking: false,
  4253. /** Whether a deceleration animation went to completion. */
  4254. __didDecelerationComplete: false,
  4255. /**
  4256. * Whether a gesture zoom/rotate event is in progress. Activates when
  4257. * a gesturestart event happens. This has higher priority than dragging.
  4258. */
  4259. __isGesturing: false,
  4260. /**
  4261. * Whether the user has moved by such a distance that we have enabled
  4262. * dragging mode. Hint: It's only enabled after some pixels of movement to
  4263. * not interrupt with clicks etc.
  4264. */
  4265. __isDragging: false,
  4266. /**
  4267. * Not touching and dragging anymore, and smoothly animating the
  4268. * touch sequence using deceleration.
  4269. */
  4270. __isDecelerating: false,
  4271. /**
  4272. * Smoothly animating the currently configured change
  4273. */
  4274. __isAnimating: false,
  4275. /*
  4276. ---------------------------------------------------------------------------
  4277. INTERNAL FIELDS :: DIMENSIONS
  4278. ---------------------------------------------------------------------------
  4279. */
  4280. /** Available outer left position (from document perspective) */
  4281. __clientLeft: 0,
  4282. /** Available outer top position (from document perspective) */
  4283. __clientTop: 0,
  4284. /** Available outer width */
  4285. __clientWidth: 0,
  4286. /** Available outer height */
  4287. __clientHeight: 0,
  4288. /** Outer width of content */
  4289. __contentWidth: 0,
  4290. /** Outer height of content */
  4291. __contentHeight: 0,
  4292. /** Snapping width for content */
  4293. __snapWidth: 100,
  4294. /** Snapping height for content */
  4295. __snapHeight: 100,
  4296. /** Height to assign to refresh area */
  4297. __refreshHeight: null,
  4298. /** Whether the refresh process is enabled when the event is released now */
  4299. __refreshActive: false,
  4300. /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */
  4301. __refreshActivate: null,
  4302. /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */
  4303. __refreshDeactivate: null,
  4304. /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */
  4305. __refreshStart: null,
  4306. /** Zoom level */
  4307. __zoomLevel: 1,
  4308. /** Scroll position on x-axis */
  4309. __scrollLeft: 0,
  4310. /** Scroll position on y-axis */
  4311. __scrollTop: 0,
  4312. /** Maximum allowed scroll position on x-axis */
  4313. __maxScrollLeft: 0,
  4314. /** Maximum allowed scroll position on y-axis */
  4315. __maxScrollTop: 0,
  4316. /* Scheduled left position (final position when animating) */
  4317. __scheduledLeft: 0,
  4318. /* Scheduled top position (final position when animating) */
  4319. __scheduledTop: 0,
  4320. /* Scheduled zoom level (final scale when animating) */
  4321. __scheduledZoom: 0,
  4322. /*
  4323. ---------------------------------------------------------------------------
  4324. INTERNAL FIELDS :: LAST POSITIONS
  4325. ---------------------------------------------------------------------------
  4326. */
  4327. /** Left position of finger at start */
  4328. __lastTouchLeft: null,
  4329. /** Top position of finger at start */
  4330. __lastTouchTop: null,
  4331. /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */
  4332. __lastTouchMove: null,
  4333. /** List of positions, uses three indexes for each state: left, top, timestamp */
  4334. __positions: null,
  4335. /*
  4336. ---------------------------------------------------------------------------
  4337. INTERNAL FIELDS :: DECELERATION SUPPORT
  4338. ---------------------------------------------------------------------------
  4339. */
  4340. /** Minimum left scroll position during deceleration */
  4341. __minDecelerationScrollLeft: null,
  4342. /** Minimum top scroll position during deceleration */
  4343. __minDecelerationScrollTop: null,
  4344. /** Maximum left scroll position during deceleration */
  4345. __maxDecelerationScrollLeft: null,
  4346. /** Maximum top scroll position during deceleration */
  4347. __maxDecelerationScrollTop: null,
  4348. /** Current factor to modify horizontal scroll position with on every step */
  4349. __decelerationVelocityX: null,
  4350. /** Current factor to modify vertical scroll position with on every step */
  4351. __decelerationVelocityY: null,
  4352. /** the browser-specific property to use for transforms */
  4353. __transformProperty: null,
  4354. __perspectiveProperty: null,
  4355. /** scrollbar indicators */
  4356. __indicatorX: null,
  4357. __indicatorY: null,
  4358. /** Timeout for scrollbar fading */
  4359. __scrollbarFadeTimeout: null,
  4360. /** whether we've tried to wait for size already */
  4361. __didWaitForSize: null,
  4362. __sizerTimeout: null,
  4363. __initEventHandlers: function() {
  4364. var self = this;
  4365. // Event Handler
  4366. var container = self.__container;
  4367. // save height when scroll view is shrunk so we don't need to reflow
  4368. var scrollViewOffsetHeight;
  4369. /**
  4370. * Shrink the scroll view when the keyboard is up if necessary and if the
  4371. * focused input is below the bottom of the shrunk scroll view, scroll it
  4372. * into view.
  4373. */
  4374. self.scrollChildIntoView = function(e) {
  4375. //console.log("scrollChildIntoView at: " + Date.now());
  4376. // D
  4377. var scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  4378. // D - A
  4379. scrollViewOffsetHeight = container.offsetHeight;
  4380. var alreadyShrunk = self.isShrunkForKeyboard;
  4381. var isModal = container.parentNode.classList.contains('modal');
  4382. // 680px is when the media query for 60% modal width kicks in
  4383. var isInsetModal = isModal && window.innerWidth >= 680;
  4384. /*
  4385. * _______
  4386. * |---A---| <- top of scroll view
  4387. * | |
  4388. * |---B---| <- keyboard
  4389. * | C | <- input
  4390. * |---D---| <- initial bottom of scroll view
  4391. * |___E___| <- bottom of viewport
  4392. *
  4393. * All commented calculations relative to the top of the viewport (ie E
  4394. * is the viewport height, not 0)
  4395. */
  4396. if (!alreadyShrunk) {
  4397. // shrink scrollview so we can actually scroll if the input is hidden
  4398. // if it isn't shrink so we can scroll to inputs under the keyboard
  4399. // inset modals won't shrink on Android on their own when the keyboard appears
  4400. if ( ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal ) {
  4401. // if there are things below the scroll view account for them and
  4402. // subtract them from the keyboard height when resizing
  4403. // E - D E D
  4404. var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;
  4405. // 0 or D - B if D > B E - B E - D
  4406. var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom);
  4407. ionic.requestAnimationFrame(function(){
  4408. // D - A or B - A if D > B D - A max(0, D - B)
  4409. scrollViewOffsetHeight = scrollViewOffsetHeight - keyboardOffset;
  4410. container.style.height = scrollViewOffsetHeight + "px";
  4411. container.style.overflow = "visible";
  4412. //update scroll view
  4413. self.resize();
  4414. });
  4415. }
  4416. self.isShrunkForKeyboard = true;
  4417. }
  4418. /*
  4419. * _______
  4420. * |---A---| <- top of scroll view
  4421. * | * | <- where we want to scroll to
  4422. * |--B-D--| <- keyboard, bottom of scroll view
  4423. * | C | <- input
  4424. * | |
  4425. * |___E___| <- bottom of viewport
  4426. *
  4427. * All commented calculations relative to the top of the viewport (ie E
  4428. * is the viewport height, not 0)
  4429. */
  4430. // if the element is positioned under the keyboard scroll it into view
  4431. if (e.detail.isElementUnderKeyboard) {
  4432. ionic.requestAnimationFrame(function(){
  4433. container.scrollTop = 0;
  4434. // update D if we shrunk
  4435. if (self.isShrunkForKeyboard && !alreadyShrunk) {
  4436. scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  4437. }
  4438. // middle of the scrollview, this is where we want to scroll to
  4439. // (D - A) / 2
  4440. var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;
  4441. //console.log("container.offsetHeight: " + scrollViewOffsetHeight);
  4442. // middle of the input we want to scroll into view
  4443. // C
  4444. var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);
  4445. // distance from middle of input to the bottom of the scroll view
  4446. // C - D C D
  4447. var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;
  4448. //C - D + (D - A)/2 C - D (D - A)/ 2
  4449. var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;
  4450. if ( scrollTop > 0) {
  4451. if (ionic.Platform.isIOS()) ionic.tap.cloneFocusedInput(container, self);
  4452. self.scrollBy(0, scrollTop, true);
  4453. self.onScroll();
  4454. }
  4455. });
  4456. }
  4457. // Only the first scrollView parent of the element that broadcasted this event
  4458. // (the active element that needs to be shown) should receive this event
  4459. e.stopPropagation();
  4460. };
  4461. self.resetScrollView = function() {
  4462. //return scrollview to original height once keyboard has hidden
  4463. if ( self.isShrunkForKeyboard ) {
  4464. self.isShrunkForKeyboard = false;
  4465. container.style.height = "";
  4466. container.style.overflow = "";
  4467. }
  4468. self.resize();
  4469. };
  4470. //Broadcasted when keyboard is shown on some platforms.
  4471. //See js/utils/keyboard.js
  4472. container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);
  4473. // Listen on document because container may not have had the last
  4474. // keyboardActiveElement, for example after closing a modal with a focused
  4475. // input and returning to a previously resized scroll view in an ion-content.
  4476. // Since we can only resize scroll views that are currently visible, just resize
  4477. // the current scroll view when the keyboard is closed.
  4478. document.addEventListener('resetScrollView', self.resetScrollView);
  4479. function getEventTouches(e) {
  4480. return e.touches && e.touches.length ? e.touches : [{
  4481. pageX: e.pageX,
  4482. pageY: e.pageY
  4483. }];
  4484. }
  4485. self.touchStart = function(e) {
  4486. self.startCoordinates = ionic.tap.pointerCoord(e);
  4487. if ( ionic.tap.ignoreScrollStart(e) ) {
  4488. return;
  4489. }
  4490. self.__isDown = true;
  4491. if ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) {
  4492. // do not start if the target is a text input
  4493. // if there is a touchmove on this input, then we can start the scroll
  4494. self.__hasStarted = false;
  4495. return;
  4496. }
  4497. self.__isSelectable = true;
  4498. self.__enableScrollY = true;
  4499. self.__hasStarted = true;
  4500. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4501. e.preventDefault();
  4502. };
  4503. self.touchMove = function(e) {
  4504. if (self.options.freeze || !self.__isDown ||
  4505. (!self.__isDown && e.defaultPrevented) ||
  4506. (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) {
  4507. return;
  4508. }
  4509. if ( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) {
  4510. // the target is a text input and scroll has started
  4511. // since the text input doesn't start on touchStart, do it here
  4512. self.__hasStarted = true;
  4513. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4514. e.preventDefault();
  4515. return;
  4516. }
  4517. if (self.startCoordinates) {
  4518. // we have start coordinates, so get this touch move's current coordinates
  4519. var currentCoordinates = ionic.tap.pointerCoord(e);
  4520. if ( self.__isSelectable &&
  4521. ionic.tap.isTextInput(e.target) &&
  4522. Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) {
  4523. // user slid the text input's caret on its x axis, disable any future y scrolling
  4524. self.__enableScrollY = false;
  4525. self.__isSelectable = true;
  4526. }
  4527. if ( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) {
  4528. // user scrolled the entire view on the y axis
  4529. // disabled being able to select text on an input
  4530. // hide the input which has focus, and show a cloned one that doesn't have focus
  4531. self.__isSelectable = false;
  4532. ionic.tap.cloneFocusedInput(container, self);
  4533. }
  4534. }
  4535. self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale);
  4536. self.__isDown = true;
  4537. };
  4538. self.touchMoveBubble = function(e) {
  4539. if(self.__isDown && self.options.preventDefault) {
  4540. e.preventDefault();
  4541. }
  4542. };
  4543. self.touchEnd = function(e) {
  4544. if (!self.__isDown) return;
  4545. self.doTouchEnd(e, e.timeStamp);
  4546. self.__isDown = false;
  4547. self.__hasStarted = false;
  4548. self.__isSelectable = true;
  4549. self.__enableScrollY = true;
  4550. if ( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) {
  4551. ionic.tap.removeClonedInputs(container, self);
  4552. }
  4553. };
  4554. self.mouseWheel = ionic.animationFrameThrottle(function(e) {
  4555. var scrollParent = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'ionic-scroll');
  4556. if (!self.options.freeze && scrollParent === self.__container) {
  4557. self.hintResize();
  4558. self.scrollBy(
  4559. (e.wheelDeltaX || e.deltaX || 0) / self.options.wheelDampen,
  4560. (-e.wheelDeltaY || e.deltaY || 0) / self.options.wheelDampen
  4561. );
  4562. self.__fadeScrollbars('in');
  4563. clearTimeout(self.__wheelHideBarTimeout);
  4564. self.__wheelHideBarTimeout = setTimeout(function() {
  4565. self.__fadeScrollbars('out');
  4566. }, 100);
  4567. }
  4568. });
  4569. if ('ontouchstart' in window) {
  4570. // Touch Events
  4571. container.addEventListener("touchstart", self.touchStart, false);
  4572. if(self.options.preventDefault) container.addEventListener("touchmove", self.touchMoveBubble, false);
  4573. document.addEventListener("touchmove", self.touchMove, false);
  4574. document.addEventListener("touchend", self.touchEnd, false);
  4575. document.addEventListener("touchcancel", self.touchEnd, false);
  4576. document.addEventListener("wheel", self.mouseWheel, false);
  4577. } else if (window.navigator.pointerEnabled) {
  4578. // Pointer Events
  4579. container.addEventListener("pointerdown", self.touchStart, false);
  4580. if(self.options.preventDefault) container.addEventListener("pointermove", self.touchMoveBubble, false);
  4581. document.addEventListener("pointermove", self.touchMove, false);
  4582. document.addEventListener("pointerup", self.touchEnd, false);
  4583. document.addEventListener("pointercancel", self.touchEnd, false);
  4584. document.addEventListener("wheel", self.mouseWheel, false);
  4585. } else if (window.navigator.msPointerEnabled) {
  4586. // IE10, WP8 (Pointer Events)
  4587. container.addEventListener("MSPointerDown", self.touchStart, false);
  4588. if(self.options.preventDefault) container.addEventListener("MSPointerMove", self.touchMoveBubble, false);
  4589. document.addEventListener("MSPointerMove", self.touchMove, false);
  4590. document.addEventListener("MSPointerUp", self.touchEnd, false);
  4591. document.addEventListener("MSPointerCancel", self.touchEnd, false);
  4592. document.addEventListener("wheel", self.mouseWheel, false);
  4593. } else {
  4594. // Mouse Events
  4595. var mousedown = false;
  4596. self.mouseDown = function(e) {
  4597. if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) {
  4598. return;
  4599. }
  4600. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4601. if ( !ionic.tap.isTextInput(e.target) ) {
  4602. e.preventDefault();
  4603. }
  4604. mousedown = true;
  4605. };
  4606. self.mouseMove = function(e) {
  4607. if (self.options.freeze || !mousedown || (!mousedown && e.defaultPrevented)) {
  4608. return;
  4609. }
  4610. self.doTouchMove(getEventTouches(e), e.timeStamp);
  4611. mousedown = true;
  4612. };
  4613. self.mouseMoveBubble = function(e) {
  4614. if (mousedown && self.options.preventDefault) {
  4615. e.preventDefault();
  4616. }
  4617. };
  4618. self.mouseUp = function(e) {
  4619. if (!mousedown) {
  4620. return;
  4621. }
  4622. self.doTouchEnd(e, e.timeStamp);
  4623. mousedown = false;
  4624. };
  4625. container.addEventListener("mousedown", self.mouseDown, false);
  4626. if(self.options.preventDefault) container.addEventListener("mousemove", self.mouseMoveBubble, false);
  4627. document.addEventListener("mousemove", self.mouseMove, false);
  4628. document.addEventListener("mouseup", self.mouseUp, false);
  4629. document.addEventListener('mousewheel', self.mouseWheel, false);
  4630. document.addEventListener('wheel', self.mouseWheel, false);
  4631. }
  4632. },
  4633. __cleanup: function() {
  4634. var self = this;
  4635. var container = self.__container;
  4636. container.removeEventListener('touchstart', self.touchStart);
  4637. container.removeEventListener('touchmove', self.touchMoveBubble);
  4638. document.removeEventListener('touchmove', self.touchMove);
  4639. document.removeEventListener('touchend', self.touchEnd);
  4640. document.removeEventListener('touchcancel', self.touchEnd);
  4641. container.removeEventListener("pointerdown", self.touchStart);
  4642. container.removeEventListener("pointermove", self.touchMoveBubble);
  4643. document.removeEventListener("pointermove", self.touchMove);
  4644. document.removeEventListener("pointerup", self.touchEnd);
  4645. document.removeEventListener("pointercancel", self.touchEnd);
  4646. container.removeEventListener("MSPointerDown", self.touchStart);
  4647. container.removeEventListener("MSPointerMove", self.touchMoveBubble);
  4648. document.removeEventListener("MSPointerMove", self.touchMove);
  4649. document.removeEventListener("MSPointerUp", self.touchEnd);
  4650. document.removeEventListener("MSPointerCancel", self.touchEnd);
  4651. container.removeEventListener("mousedown", self.mouseDown);
  4652. container.removeEventListener("mousemove", self.mouseMoveBubble);
  4653. document.removeEventListener("mousemove", self.mouseMove);
  4654. document.removeEventListener("mouseup", self.mouseUp);
  4655. document.removeEventListener('mousewheel', self.mouseWheel);
  4656. document.removeEventListener('wheel', self.mouseWheel);
  4657. container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);
  4658. document.removeEventListener('resetScrollView', self.resetScrollView);
  4659. ionic.tap.removeClonedInputs(container, self);
  4660. delete self.__container;
  4661. delete self.__content;
  4662. delete self.__indicatorX;
  4663. delete self.__indicatorY;
  4664. delete self.options.el;
  4665. self.__callback = self.scrollChildIntoView = self.resetScrollView = NOOP;
  4666. self.mouseMove = self.mouseDown = self.mouseUp = self.mouseWheel =
  4667. self.touchStart = self.touchMove = self.touchEnd = self.touchCancel = NOOP;
  4668. self.resize = self.scrollTo = self.zoomTo =
  4669. self.__scrollingComplete = NOOP;
  4670. container = null;
  4671. },
  4672. /** Create a scroll bar div with the given direction **/
  4673. __createScrollbar: function(direction) {
  4674. var bar = document.createElement('div'),
  4675. indicator = document.createElement('div');
  4676. indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';
  4677. if (direction == 'h') {
  4678. bar.className = 'scroll-bar scroll-bar-h';
  4679. } else {
  4680. bar.className = 'scroll-bar scroll-bar-v';
  4681. }
  4682. bar.appendChild(indicator);
  4683. return bar;
  4684. },
  4685. __createScrollbars: function() {
  4686. var self = this;
  4687. var indicatorX, indicatorY;
  4688. if (self.options.scrollingX) {
  4689. indicatorX = {
  4690. el: self.__createScrollbar('h'),
  4691. sizeRatio: 1
  4692. };
  4693. indicatorX.indicator = indicatorX.el.children[0];
  4694. if (self.options.scrollbarX) {
  4695. self.__container.appendChild(indicatorX.el);
  4696. }
  4697. self.__indicatorX = indicatorX;
  4698. }
  4699. if (self.options.scrollingY) {
  4700. indicatorY = {
  4701. el: self.__createScrollbar('v'),
  4702. sizeRatio: 1
  4703. };
  4704. indicatorY.indicator = indicatorY.el.children[0];
  4705. if (self.options.scrollbarY) {
  4706. self.__container.appendChild(indicatorY.el);
  4707. }
  4708. self.__indicatorY = indicatorY;
  4709. }
  4710. },
  4711. __resizeScrollbars: function() {
  4712. var self = this;
  4713. // Update horiz bar
  4714. if (self.__indicatorX) {
  4715. var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20);
  4716. if (width > self.__contentWidth) {
  4717. width = 0;
  4718. }
  4719. if (width !== self.__indicatorX.size) {
  4720. ionic.requestAnimationFrame(function(){
  4721. self.__indicatorX.indicator.style.width = width + 'px';
  4722. });
  4723. }
  4724. self.__indicatorX.size = width;
  4725. self.__indicatorX.minScale = self.options.minScrollbarSizeX / width;
  4726. self.__indicatorX.maxPos = self.__clientWidth - width;
  4727. self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1;
  4728. }
  4729. // Update vert bar
  4730. if (self.__indicatorY) {
  4731. var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20);
  4732. if (height > self.__contentHeight) {
  4733. height = 0;
  4734. }
  4735. if (height !== self.__indicatorY.size) {
  4736. ionic.requestAnimationFrame(function(){
  4737. self.__indicatorY && (self.__indicatorY.indicator.style.height = height + 'px');
  4738. });
  4739. }
  4740. self.__indicatorY.size = height;
  4741. self.__indicatorY.minScale = self.options.minScrollbarSizeY / height;
  4742. self.__indicatorY.maxPos = self.__clientHeight - height;
  4743. self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1;
  4744. }
  4745. },
  4746. /**
  4747. * Move and scale the scrollbars as the page scrolls.
  4748. */
  4749. __repositionScrollbars: function() {
  4750. var self = this,
  4751. heightScale, widthScale,
  4752. widthDiff, heightDiff,
  4753. x, y,
  4754. xstop = 0, ystop = 0;
  4755. if (self.__indicatorX) {
  4756. // Handle the X scrollbar
  4757. // Don't go all the way to the right if we have a vertical scrollbar as well
  4758. if (self.__indicatorY) xstop = 10;
  4759. x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0;
  4760. // The the difference between the last content X position, and our overscrolled one
  4761. widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop);
  4762. if (self.__scrollLeft < 0) {
  4763. widthScale = Math.max(self.__indicatorX.minScale,
  4764. (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size);
  4765. // Stay at left
  4766. x = 0;
  4767. // Make sure scale is transformed from the left/center origin point
  4768. self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center';
  4769. } else if (widthDiff > 0) {
  4770. widthScale = Math.max(self.__indicatorX.minScale,
  4771. (self.__indicatorX.size - widthDiff) / self.__indicatorX.size);
  4772. // Stay at the furthest x for the scrollable viewport
  4773. x = self.__indicatorX.maxPos - xstop;
  4774. // Make sure scale is transformed from the right/center origin point
  4775. self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center';
  4776. } else {
  4777. // Normal motion
  4778. x = Math.min(self.__maxScrollLeft, Math.max(0, x));
  4779. widthScale = 1;
  4780. }
  4781. var translate3dX = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')';
  4782. if (self.__indicatorX.transformProp !== translate3dX) {
  4783. self.__indicatorX.indicator.style[self.__transformProperty] = translate3dX;
  4784. self.__indicatorX.transformProp = translate3dX;
  4785. }
  4786. }
  4787. if (self.__indicatorY) {
  4788. y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0;
  4789. // Don't go all the way to the right if we have a vertical scrollbar as well
  4790. if (self.__indicatorX) ystop = 10;
  4791. heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop);
  4792. if (self.__scrollTop < 0) {
  4793. heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size);
  4794. // Stay at top
  4795. y = 0;
  4796. // Make sure scale is transformed from the center/top origin point
  4797. if (self.__indicatorY.originProp !== 'center top') {
  4798. self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top';
  4799. self.__indicatorY.originProp = 'center top';
  4800. }
  4801. } else if (heightDiff > 0) {
  4802. heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size);
  4803. // Stay at bottom of scrollable viewport
  4804. y = self.__indicatorY.maxPos - ystop;
  4805. // Make sure scale is transformed from the center/bottom origin point
  4806. if (self.__indicatorY.originProp !== 'center bottom') {
  4807. self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom';
  4808. self.__indicatorY.originProp = 'center bottom';
  4809. }
  4810. } else {
  4811. // Normal motion
  4812. y = Math.min(self.__maxScrollTop, Math.max(0, y));
  4813. heightScale = 1;
  4814. }
  4815. var translate3dY = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')';
  4816. if (self.__indicatorY.transformProp !== translate3dY) {
  4817. self.__indicatorY.indicator.style[self.__transformProperty] = translate3dY;
  4818. self.__indicatorY.transformProp = translate3dY;
  4819. }
  4820. }
  4821. },
  4822. __fadeScrollbars: function(direction, delay) {
  4823. var self = this;
  4824. if (!self.options.scrollbarsFade) {
  4825. return;
  4826. }
  4827. var className = 'scroll-bar-fade-out';
  4828. if (self.options.scrollbarsFade === true) {
  4829. clearTimeout(self.__scrollbarFadeTimeout);
  4830. if (direction == 'in') {
  4831. if (self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); }
  4832. if (self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); }
  4833. } else {
  4834. self.__scrollbarFadeTimeout = setTimeout(function() {
  4835. if (self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); }
  4836. if (self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); }
  4837. }, delay || self.options.scrollbarFadeDelay);
  4838. }
  4839. }
  4840. },
  4841. __scrollingComplete: function() {
  4842. this.options.scrollingComplete();
  4843. ionic.tap.removeClonedInputs(this.__container, this);
  4844. this.__fadeScrollbars('out');
  4845. },
  4846. resize: function(continueScrolling) {
  4847. var self = this;
  4848. if (!self.__container || !self.options) return;
  4849. // Update Scroller dimensions for changed content
  4850. // Add padding to bottom of content
  4851. self.setDimensions(
  4852. self.__container.clientWidth,
  4853. self.__container.clientHeight,
  4854. self.options.getContentWidth(),
  4855. self.options.getContentHeight(),
  4856. continueScrolling
  4857. );
  4858. },
  4859. /*
  4860. ---------------------------------------------------------------------------
  4861. PUBLIC API
  4862. ---------------------------------------------------------------------------
  4863. */
  4864. getRenderFn: function() {
  4865. var self = this;
  4866. var content = self.__content;
  4867. var docStyle = document.documentElement.style;
  4868. var engine;
  4869. if ('MozAppearance' in docStyle) {
  4870. engine = 'gecko';
  4871. } else if ('WebkitAppearance' in docStyle) {
  4872. engine = 'webkit';
  4873. } else if (typeof navigator.cpuClass === 'string') {
  4874. engine = 'trident';
  4875. }
  4876. var vendorPrefix = {
  4877. trident: 'ms',
  4878. gecko: 'Moz',
  4879. webkit: 'Webkit',
  4880. presto: 'O'
  4881. }[engine];
  4882. var helperElem = document.createElement("div");
  4883. var undef;
  4884. var perspectiveProperty = vendorPrefix + "Perspective";
  4885. var transformProperty = vendorPrefix + "Transform";
  4886. var transformOriginProperty = vendorPrefix + 'TransformOrigin';
  4887. self.__perspectiveProperty = transformProperty;
  4888. self.__transformProperty = transformProperty;
  4889. self.__transformOriginProperty = transformOriginProperty;
  4890. if (helperElem.style[perspectiveProperty] !== undef) {
  4891. return function(left, top, zoom, wasResize) {
  4892. var translate3d = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';
  4893. if (translate3d !== self.contentTransform) {
  4894. content.style[transformProperty] = translate3d;
  4895. self.contentTransform = translate3d;
  4896. }
  4897. self.__repositionScrollbars();
  4898. if (!wasResize) {
  4899. self.triggerScrollEvent();
  4900. }
  4901. };
  4902. } else if (helperElem.style[transformProperty] !== undef) {
  4903. return function(left, top, zoom, wasResize) {
  4904. content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';
  4905. self.__repositionScrollbars();
  4906. if (!wasResize) {
  4907. self.triggerScrollEvent();
  4908. }
  4909. };
  4910. } else {
  4911. return function(left, top, zoom, wasResize) {
  4912. content.style.marginLeft = left ? (-left / zoom) + 'px' : '';
  4913. content.style.marginTop = top ? (-top / zoom) + 'px' : '';
  4914. content.style.zoom = zoom || '';
  4915. self.__repositionScrollbars();
  4916. if (!wasResize) {
  4917. self.triggerScrollEvent();
  4918. }
  4919. };
  4920. }
  4921. },
  4922. /**
  4923. * Configures the dimensions of the client (outer) and content (inner) elements.
  4924. * Requires the available space for the outer element and the outer size of the inner element.
  4925. * All values which are falsy (null or zero etc.) are ignored and the old value is kept.
  4926. *
  4927. * @param clientWidth {Integer} Inner width of outer element
  4928. * @param clientHeight {Integer} Inner height of outer element
  4929. * @param contentWidth {Integer} Outer width of inner element
  4930. * @param contentHeight {Integer} Outer height of inner element
  4931. */
  4932. setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight, continueScrolling) {
  4933. var self = this;
  4934. if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {
  4935. // this scrollview isn't rendered, don't bother
  4936. return;
  4937. }
  4938. // Only update values which are defined
  4939. if (clientWidth === +clientWidth) {
  4940. self.__clientWidth = clientWidth;
  4941. }
  4942. if (clientHeight === +clientHeight) {
  4943. self.__clientHeight = clientHeight;
  4944. }
  4945. if (contentWidth === +contentWidth) {
  4946. self.__contentWidth = contentWidth;
  4947. }
  4948. if (contentHeight === +contentHeight) {
  4949. self.__contentHeight = contentHeight;
  4950. }
  4951. // Refresh maximums
  4952. self.__computeScrollMax();
  4953. self.__resizeScrollbars();
  4954. // Refresh scroll position
  4955. if (!continueScrolling) {
  4956. self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true);
  4957. }
  4958. },
  4959. /**
  4960. * Sets the client coordinates in relation to the document.
  4961. *
  4962. * @param left {Integer} Left position of outer element
  4963. * @param top {Integer} Top position of outer element
  4964. */
  4965. setPosition: function(left, top) {
  4966. this.__clientLeft = left || 0;
  4967. this.__clientTop = top || 0;
  4968. },
  4969. /**
  4970. * Configures the snapping (when snapping is active)
  4971. *
  4972. * @param width {Integer} Snapping width
  4973. * @param height {Integer} Snapping height
  4974. */
  4975. setSnapSize: function(width, height) {
  4976. this.__snapWidth = width;
  4977. this.__snapHeight = height;
  4978. },
  4979. /**
  4980. * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever
  4981. * the user event is released during visibility of this zone. This was introduced by some apps on iOS like
  4982. * the official Twitter client.
  4983. *
  4984. * @param height {Integer} Height of pull-to-refresh zone on top of rendered list
  4985. * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release.
  4986. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled.
  4987. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh.
  4988. * @param showCallback {Function} Callback to execute when the refresher should be shown. This is for showing the refresher during a negative scrollTop.
  4989. * @param hideCallback {Function} Callback to execute when the refresher should be hidden. This is for hiding the refresher when it's behind the nav bar.
  4990. * @param tailCallback {Function} Callback to execute just before the refresher returns to it's original state. This is for zooming out the refresher.
  4991. * @param pullProgressCallback Callback to state the progress while pulling to refresh
  4992. */
  4993. activatePullToRefresh: function(height, refresherMethods) {
  4994. var self = this;
  4995. self.__refreshHeight = height;
  4996. self.__refreshActivate = function() { ionic.requestAnimationFrame(refresherMethods.activate); };
  4997. self.__refreshDeactivate = function() { ionic.requestAnimationFrame(refresherMethods.deactivate); };
  4998. self.__refreshStart = function() { ionic.requestAnimationFrame(refresherMethods.start); };
  4999. self.__refreshShow = function() { ionic.requestAnimationFrame(refresherMethods.show); };
  5000. self.__refreshHide = function() { ionic.requestAnimationFrame(refresherMethods.hide); };
  5001. self.__refreshTail = function() { ionic.requestAnimationFrame(refresherMethods.tail); };
  5002. self.__refreshTailTime = 100;
  5003. self.__minSpinTime = 600;
  5004. },
  5005. /**
  5006. * Starts pull-to-refresh manually.
  5007. */
  5008. triggerPullToRefresh: function() {
  5009. // Use publish instead of scrollTo to allow scrolling to out of boundary position
  5010. // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
  5011. this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true);
  5012. var d = new Date();
  5013. this.refreshStartTime = d.getTime();
  5014. if (this.__refreshStart) {
  5015. this.__refreshStart();
  5016. }
  5017. },
  5018. /**
  5019. * Signalizes that pull-to-refresh is finished.
  5020. */
  5021. finishPullToRefresh: function() {
  5022. var self = this;
  5023. // delay to make sure the spinner has a chance to spin for a split second before it's dismissed
  5024. var d = new Date();
  5025. var delay = 0;
  5026. if (self.refreshStartTime + self.__minSpinTime > d.getTime()) {
  5027. delay = self.refreshStartTime + self.__minSpinTime - d.getTime();
  5028. }
  5029. setTimeout(function() {
  5030. if (self.__refreshTail) {
  5031. self.__refreshTail();
  5032. }
  5033. setTimeout(function() {
  5034. self.__refreshActive = false;
  5035. if (self.__refreshDeactivate) {
  5036. self.__refreshDeactivate();
  5037. }
  5038. if (self.__refreshHide) {
  5039. self.__refreshHide();
  5040. }
  5041. self.scrollTo(self.__scrollLeft, self.__scrollTop, true);
  5042. }, self.__refreshTailTime);
  5043. }, delay);
  5044. },
  5045. /**
  5046. * Returns the scroll position and zooming values
  5047. *
  5048. * @return {Map} `left` and `top` scroll position and `zoom` level
  5049. */
  5050. getValues: function() {
  5051. return {
  5052. left: this.__scrollLeft,
  5053. top: this.__scrollTop,
  5054. zoom: this.__zoomLevel
  5055. };
  5056. },
  5057. /**
  5058. * Returns the maximum scroll values
  5059. *
  5060. * @return {Map} `left` and `top` maximum scroll values
  5061. */
  5062. getScrollMax: function() {
  5063. return {
  5064. left: this.__maxScrollLeft,
  5065. top: this.__maxScrollTop
  5066. };
  5067. },
  5068. /**
  5069. * Zooms to the given level. Supports optional animation. Zooms
  5070. * the center when no coordinates are given.
  5071. *
  5072. * @param level {Number} Level to zoom to
  5073. * @param animate {Boolean} Whether to use animation
  5074. * @param originLeft {Number} Zoom in at given left coordinate
  5075. * @param originTop {Number} Zoom in at given top coordinate
  5076. */
  5077. zoomTo: function(level, animate, originLeft, originTop) {
  5078. var self = this;
  5079. if (!self.options.zooming) {
  5080. throw new Error("Zooming is not enabled!");
  5081. }
  5082. // Stop deceleration
  5083. if (self.__isDecelerating) {
  5084. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5085. self.__isDecelerating = false;
  5086. }
  5087. var oldLevel = self.__zoomLevel;
  5088. // Normalize input origin to center of viewport if not defined
  5089. if (originLeft == null) {
  5090. originLeft = self.__clientWidth / 2;
  5091. }
  5092. if (originTop == null) {
  5093. originTop = self.__clientHeight / 2;
  5094. }
  5095. // Limit level according to configuration
  5096. level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
  5097. // Recompute maximum values while temporary tweaking maximum scroll ranges
  5098. self.__computeScrollMax(level);
  5099. // Recompute left and top coordinates based on new zoom level
  5100. var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft;
  5101. var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop;
  5102. // Limit x-axis
  5103. if (left > self.__maxScrollLeft) {
  5104. left = self.__maxScrollLeft;
  5105. } else if (left < 0) {
  5106. left = 0;
  5107. }
  5108. // Limit y-axis
  5109. if (top > self.__maxScrollTop) {
  5110. top = self.__maxScrollTop;
  5111. } else if (top < 0) {
  5112. top = 0;
  5113. }
  5114. // Push values out
  5115. self.__publish(left, top, level, animate);
  5116. },
  5117. /**
  5118. * Zooms the content by the given factor.
  5119. *
  5120. * @param factor {Number} Zoom by given factor
  5121. * @param animate {Boolean} Whether to use animation
  5122. * @param originLeft {Number} Zoom in at given left coordinate
  5123. * @param originTop {Number} Zoom in at given top coordinate
  5124. */
  5125. zoomBy: function(factor, animate, originLeft, originTop) {
  5126. this.zoomTo(this.__zoomLevel * factor, animate, originLeft, originTop);
  5127. },
  5128. /**
  5129. * Scrolls to the given position. Respect limitations and snapping automatically.
  5130. *
  5131. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5132. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5133. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5134. * @param zoom {Number} Zoom level to go to
  5135. */
  5136. scrollTo: function(left, top, animate, zoom, wasResize) {
  5137. var self = this;
  5138. // Stop deceleration
  5139. if (self.__isDecelerating) {
  5140. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5141. self.__isDecelerating = false;
  5142. }
  5143. // Correct coordinates based on new zoom level
  5144. if (zoom != null && zoom !== self.__zoomLevel) {
  5145. if (!self.options.zooming) {
  5146. throw new Error("Zooming is not enabled!");
  5147. }
  5148. left *= zoom;
  5149. top *= zoom;
  5150. // Recompute maximum values while temporary tweaking maximum scroll ranges
  5151. self.__computeScrollMax(zoom);
  5152. } else {
  5153. // Keep zoom when not defined
  5154. zoom = self.__zoomLevel;
  5155. }
  5156. if (!self.options.scrollingX) {
  5157. left = self.__scrollLeft;
  5158. } else {
  5159. if (self.options.paging) {
  5160. left = Math.round(left / self.__clientWidth) * self.__clientWidth;
  5161. } else if (self.options.snapping) {
  5162. left = Math.round(left / self.__snapWidth) * self.__snapWidth;
  5163. }
  5164. }
  5165. if (!self.options.scrollingY) {
  5166. top = self.__scrollTop;
  5167. } else {
  5168. if (self.options.paging) {
  5169. top = Math.round(top / self.__clientHeight) * self.__clientHeight;
  5170. } else if (self.options.snapping) {
  5171. top = Math.round(top / self.__snapHeight) * self.__snapHeight;
  5172. }
  5173. }
  5174. // Limit for allowed ranges
  5175. left = Math.max(Math.min(self.__maxScrollLeft, left), 0);
  5176. top = Math.max(Math.min(self.__maxScrollTop, top), 0);
  5177. // Don't animate when no change detected, still call publish to make sure
  5178. // that rendered position is really in-sync with internal data
  5179. if (left === self.__scrollLeft && top === self.__scrollTop) {
  5180. animate = false;
  5181. }
  5182. // Publish new values
  5183. self.__publish(left, top, zoom, animate, wasResize);
  5184. },
  5185. /**
  5186. * Scroll by the given offset
  5187. *
  5188. * @param left {Number} Scroll x-axis by given offset
  5189. * @param top {Number} Scroll y-axis by given offset
  5190. * @param animate {Boolean} Whether to animate the given change
  5191. */
  5192. scrollBy: function(left, top, animate) {
  5193. var self = this;
  5194. var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;
  5195. var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;
  5196. self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);
  5197. },
  5198. /*
  5199. ---------------------------------------------------------------------------
  5200. EVENT CALLBACKS
  5201. ---------------------------------------------------------------------------
  5202. */
  5203. /**
  5204. * Mouse wheel handler for zooming support
  5205. */
  5206. doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) {
  5207. var change = wheelDelta > 0 ? 0.97 : 1.03;
  5208. return this.zoomTo(this.__zoomLevel * change, false, pageX - this.__clientLeft, pageY - this.__clientTop);
  5209. },
  5210. /**
  5211. * Touch start handler for scrolling support
  5212. */
  5213. doTouchStart: function(touches, timeStamp) {
  5214. var self = this;
  5215. // remember if the deceleration was just stopped
  5216. self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);
  5217. self.hintResize();
  5218. if (timeStamp instanceof Date) {
  5219. timeStamp = timeStamp.valueOf();
  5220. }
  5221. if (typeof timeStamp !== "number") {
  5222. timeStamp = Date.now();
  5223. }
  5224. // Reset interruptedAnimation flag
  5225. self.__interruptedAnimation = true;
  5226. // Stop deceleration
  5227. if (self.__isDecelerating) {
  5228. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5229. self.__isDecelerating = false;
  5230. self.__interruptedAnimation = true;
  5231. }
  5232. // Stop animation
  5233. if (self.__isAnimating) {
  5234. zyngaCore.effect.Animate.stop(self.__isAnimating);
  5235. self.__isAnimating = false;
  5236. self.__interruptedAnimation = true;
  5237. }
  5238. // Use center point when dealing with two fingers
  5239. var currentTouchLeft, currentTouchTop;
  5240. var isSingleTouch = touches.length === 1;
  5241. if (isSingleTouch) {
  5242. currentTouchLeft = touches[0].pageX;
  5243. currentTouchTop = touches[0].pageY;
  5244. } else {
  5245. currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
  5246. currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
  5247. }
  5248. // Store initial positions
  5249. self.__initialTouchLeft = currentTouchLeft;
  5250. self.__initialTouchTop = currentTouchTop;
  5251. // Store initial touchList for scale calculation
  5252. self.__initialTouches = touches;
  5253. // Store current zoom level
  5254. self.__zoomLevelStart = self.__zoomLevel;
  5255. // Store initial touch positions
  5256. self.__lastTouchLeft = currentTouchLeft;
  5257. self.__lastTouchTop = currentTouchTop;
  5258. // Store initial move time stamp
  5259. self.__lastTouchMove = timeStamp;
  5260. // Reset initial scale
  5261. self.__lastScale = 1;
  5262. // Reset locking flags
  5263. self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
  5264. self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
  5265. // Reset tracking flag
  5266. self.__isTracking = true;
  5267. // Reset deceleration complete flag
  5268. self.__didDecelerationComplete = false;
  5269. // Dragging starts directly with two fingers, otherwise lazy with an offset
  5270. self.__isDragging = !isSingleTouch;
  5271. // Some features are disabled in multi touch scenarios
  5272. self.__isSingleTouch = isSingleTouch;
  5273. // Clearing data structure
  5274. self.__positions = [];
  5275. },
  5276. /**
  5277. * Touch move handler for scrolling support
  5278. */
  5279. doTouchMove: function(touches, timeStamp, scale) {
  5280. if (timeStamp instanceof Date) {
  5281. timeStamp = timeStamp.valueOf();
  5282. }
  5283. if (typeof timeStamp !== "number") {
  5284. timeStamp = Date.now();
  5285. }
  5286. var self = this;
  5287. // Ignore event when tracking is not enabled (event might be outside of element)
  5288. if (!self.__isTracking) {
  5289. return;
  5290. }
  5291. var currentTouchLeft, currentTouchTop;
  5292. // Compute move based around of center of fingers
  5293. if (touches.length === 2) {
  5294. currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
  5295. currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
  5296. // Calculate scale when not present and only when touches are used
  5297. if (!scale && self.options.zooming) {
  5298. scale = self.__getScale(self.__initialTouches, touches);
  5299. }
  5300. } else {
  5301. currentTouchLeft = touches[0].pageX;
  5302. currentTouchTop = touches[0].pageY;
  5303. }
  5304. var positions = self.__positions;
  5305. // Are we already is dragging mode?
  5306. if (self.__isDragging) {
  5307. self.__decStopped = false;
  5308. // Compute move distance
  5309. var moveX = currentTouchLeft - self.__lastTouchLeft;
  5310. var moveY = currentTouchTop - self.__lastTouchTop;
  5311. // Read previous scroll position and zooming
  5312. var scrollLeft = self.__scrollLeft;
  5313. var scrollTop = self.__scrollTop;
  5314. var level = self.__zoomLevel;
  5315. // Work with scaling
  5316. if (scale != null && self.options.zooming) {
  5317. var oldLevel = level;
  5318. // Recompute level based on previous scale and new scale
  5319. level = level / self.__lastScale * scale;
  5320. // Limit level according to configuration
  5321. level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
  5322. // Only do further compution when change happened
  5323. if (oldLevel !== level) {
  5324. // Compute relative event position to container
  5325. var currentTouchLeftRel = currentTouchLeft - self.__clientLeft;
  5326. var currentTouchTopRel = currentTouchTop - self.__clientTop;
  5327. // Recompute left and top coordinates based on new zoom level
  5328. scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel;
  5329. scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel;
  5330. // Recompute max scroll values
  5331. self.__computeScrollMax(level);
  5332. }
  5333. }
  5334. if (self.__enableScrollX) {
  5335. scrollLeft -= moveX * self.options.speedMultiplier;
  5336. var maxScrollLeft = self.__maxScrollLeft;
  5337. if (scrollLeft > maxScrollLeft || scrollLeft < 0) {
  5338. // Slow down on the edges
  5339. if (self.options.bouncing) {
  5340. scrollLeft += (moveX / 2 * self.options.speedMultiplier);
  5341. } else if (scrollLeft > maxScrollLeft) {
  5342. scrollLeft = maxScrollLeft;
  5343. } else {
  5344. scrollLeft = 0;
  5345. }
  5346. }
  5347. }
  5348. // Compute new vertical scroll position
  5349. if (self.__enableScrollY) {
  5350. scrollTop -= moveY * self.options.speedMultiplier;
  5351. var maxScrollTop = self.__maxScrollTop;
  5352. if (scrollTop > maxScrollTop || scrollTop < 0) {
  5353. // Slow down on the edges
  5354. if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) {
  5355. scrollTop += (moveY / 2 * self.options.speedMultiplier);
  5356. // Support pull-to-refresh (only when only y is scrollable)
  5357. if (!self.__enableScrollX && self.__refreshHeight != null) {
  5358. // hide the refresher when it's behind the header bar in case of header transparency
  5359. if (scrollTop < 0) {
  5360. self.__refreshHidden = false;
  5361. self.__refreshShow();
  5362. } else {
  5363. self.__refreshHide();
  5364. self.__refreshHidden = true;
  5365. }
  5366. if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) {
  5367. self.__refreshActive = true;
  5368. if (self.__refreshActivate) {
  5369. self.__refreshActivate();
  5370. }
  5371. } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) {
  5372. self.__refreshActive = false;
  5373. if (self.__refreshDeactivate) {
  5374. self.__refreshDeactivate();
  5375. }
  5376. }
  5377. }
  5378. } else if (scrollTop > maxScrollTop) {
  5379. scrollTop = maxScrollTop;
  5380. } else {
  5381. scrollTop = 0;
  5382. }
  5383. } else if (self.__refreshHeight && !self.__refreshHidden) {
  5384. // if a positive scroll value and the refresher is still not hidden, hide it
  5385. self.__refreshHide();
  5386. self.__refreshHidden = true;
  5387. }
  5388. }
  5389. // Keep list from growing infinitely (holding min 10, max 20 measure points)
  5390. if (positions.length > 60) {
  5391. positions.splice(0, 30);
  5392. }
  5393. // Track scroll movement for decleration
  5394. positions.push(scrollLeft, scrollTop, timeStamp);
  5395. // Sync scroll position
  5396. self.__publish(scrollLeft, scrollTop, level);
  5397. // Otherwise figure out whether we are switching into dragging mode now.
  5398. } else {
  5399. var minimumTrackingForScroll = self.options.locking ? 3 : 0;
  5400. var minimumTrackingForDrag = 5;
  5401. var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft);
  5402. var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);
  5403. self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll;
  5404. self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll;
  5405. positions.push(self.__scrollLeft, self.__scrollTop, timeStamp);
  5406. self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag);
  5407. if (self.__isDragging) {
  5408. self.__interruptedAnimation = false;
  5409. self.__fadeScrollbars('in');
  5410. }
  5411. }
  5412. // Update last touch positions and time stamp for next event
  5413. self.__lastTouchLeft = currentTouchLeft;
  5414. self.__lastTouchTop = currentTouchTop;
  5415. self.__lastTouchMove = timeStamp;
  5416. self.__lastScale = scale;
  5417. },
  5418. /**
  5419. * Touch end handler for scrolling support
  5420. */
  5421. doTouchEnd: function(e, timeStamp) {
  5422. if (timeStamp instanceof Date) {
  5423. timeStamp = timeStamp.valueOf();
  5424. }
  5425. if (typeof timeStamp !== "number") {
  5426. timeStamp = Date.now();
  5427. }
  5428. var self = this;
  5429. // Ignore event when tracking is not enabled (no touchstart event on element)
  5430. // This is required as this listener ('touchmove') sits on the document and not on the element itself.
  5431. if (!self.__isTracking) {
  5432. return;
  5433. }
  5434. // Not touching anymore (when two finger hit the screen there are two touch end events)
  5435. self.__isTracking = false;
  5436. // Be sure to reset the dragging flag now. Here we also detect whether
  5437. // the finger has moved fast enough to switch into a deceleration animation.
  5438. if (self.__isDragging) {
  5439. // Reset dragging flag
  5440. self.__isDragging = false;
  5441. // Start deceleration
  5442. // Verify that the last move detected was in some relevant time frame
  5443. if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) {
  5444. // Then figure out what the scroll position was about 100ms ago
  5445. var positions = self.__positions;
  5446. var endPos = positions.length - 1;
  5447. var startPos = endPos;
  5448. // Move pointer to position measured 100ms ago
  5449. for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) {
  5450. startPos = i;
  5451. }
  5452. // If start and stop position is identical in a 100ms timeframe,
  5453. // we cannot compute any useful deceleration.
  5454. if (startPos !== endPos) {
  5455. // Compute relative movement between these two points
  5456. var timeOffset = positions[endPos] - positions[startPos];
  5457. var movedLeft = self.__scrollLeft - positions[startPos - 2];
  5458. var movedTop = self.__scrollTop - positions[startPos - 1];
  5459. // Based on 50ms compute the movement to apply for each render step
  5460. self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60);
  5461. self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60);
  5462. // How much velocity is required to start the deceleration
  5463. var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? self.options.decelVelocityThresholdPaging : self.options.decelVelocityThreshold;
  5464. // Verify that we have enough velocity to start deceleration
  5465. if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) {
  5466. // Deactivate pull-to-refresh when decelerating
  5467. if (!self.__refreshActive) {
  5468. self.__startDeceleration(timeStamp);
  5469. }
  5470. }
  5471. } else {
  5472. self.__scrollingComplete();
  5473. }
  5474. } else if ((timeStamp - self.__lastTouchMove) > 100) {
  5475. self.__scrollingComplete();
  5476. }
  5477. } else if (self.__decStopped) {
  5478. // the deceleration was stopped
  5479. // user flicked the scroll fast, and stop dragging, then did a touchstart to stop the srolling
  5480. // tell the touchend event code to do nothing, we don't want to actually send a click
  5481. e.isTapHandled = true;
  5482. self.__decStopped = false;
  5483. }
  5484. // If this was a slower move it is per default non decelerated, but this
  5485. // still means that we want snap back to the bounds which is done here.
  5486. // This is placed outside the condition above to improve edge case stability
  5487. // e.g. touchend fired without enabled dragging. This should normally do not
  5488. // have modified the scroll positions or even showed the scrollbars though.
  5489. if (!self.__isDecelerating) {
  5490. if (self.__refreshActive && self.__refreshStart) {
  5491. // Use publish instead of scrollTo to allow scrolling to out of boundary position
  5492. // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
  5493. self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true);
  5494. var d = new Date();
  5495. self.refreshStartTime = d.getTime();
  5496. if (self.__refreshStart) {
  5497. self.__refreshStart();
  5498. }
  5499. // for iOS-ey style scrolling
  5500. if (!ionic.Platform.isAndroid())self.__startDeceleration();
  5501. } else {
  5502. if (self.__interruptedAnimation || self.__isDragging) {
  5503. self.__scrollingComplete();
  5504. }
  5505. self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel);
  5506. // Directly signalize deactivation (nothing todo on refresh?)
  5507. if (self.__refreshActive) {
  5508. self.__refreshActive = false;
  5509. if (self.__refreshDeactivate) {
  5510. self.__refreshDeactivate();
  5511. }
  5512. }
  5513. }
  5514. }
  5515. // Fully cleanup list
  5516. self.__positions.length = 0;
  5517. },
  5518. /*
  5519. ---------------------------------------------------------------------------
  5520. PRIVATE API
  5521. ---------------------------------------------------------------------------
  5522. */
  5523. /**
  5524. * Applies the scroll position to the content element
  5525. *
  5526. * @param left {Number} Left scroll position
  5527. * @param top {Number} Top scroll position
  5528. * @param animate {Boolean} Whether animation should be used to move to the new coordinates
  5529. */
  5530. __publish: function(left, top, zoom, animate, wasResize) {
  5531. var self = this;
  5532. // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation
  5533. var wasAnimating = self.__isAnimating;
  5534. if (wasAnimating) {
  5535. zyngaCore.effect.Animate.stop(wasAnimating);
  5536. self.__isAnimating = false;
  5537. }
  5538. if (animate && self.options.animating) {
  5539. // Keep scheduled positions for scrollBy/zoomBy functionality
  5540. self.__scheduledLeft = left;
  5541. self.__scheduledTop = top;
  5542. self.__scheduledZoom = zoom;
  5543. var oldLeft = self.__scrollLeft;
  5544. var oldTop = self.__scrollTop;
  5545. var oldZoom = self.__zoomLevel;
  5546. var diffLeft = left - oldLeft;
  5547. var diffTop = top - oldTop;
  5548. var diffZoom = zoom - oldZoom;
  5549. var step = function(percent, now, render) {
  5550. if (render) {
  5551. self.__scrollLeft = oldLeft + (diffLeft * percent);
  5552. self.__scrollTop = oldTop + (diffTop * percent);
  5553. self.__zoomLevel = oldZoom + (diffZoom * percent);
  5554. // Push values out
  5555. if (self.__callback) {
  5556. self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize);
  5557. }
  5558. }
  5559. };
  5560. var verify = function(id) {
  5561. return self.__isAnimating === id;
  5562. };
  5563. var completed = function(renderedFramesPerSecond, animationId, wasFinished) {
  5564. if (animationId === self.__isAnimating) {
  5565. self.__isAnimating = false;
  5566. }
  5567. if (self.__didDecelerationComplete || wasFinished) {
  5568. self.__scrollingComplete();
  5569. }
  5570. if (self.options.zooming) {
  5571. self.__computeScrollMax();
  5572. }
  5573. };
  5574. // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out
  5575. self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic);
  5576. } else {
  5577. self.__scheduledLeft = self.__scrollLeft = left;
  5578. self.__scheduledTop = self.__scrollTop = top;
  5579. self.__scheduledZoom = self.__zoomLevel = zoom;
  5580. // Push values out
  5581. if (self.__callback) {
  5582. self.__callback(left, top, zoom, wasResize);
  5583. }
  5584. // Fix max scroll ranges
  5585. if (self.options.zooming) {
  5586. self.__computeScrollMax();
  5587. }
  5588. }
  5589. },
  5590. /**
  5591. * Recomputes scroll minimum values based on client dimensions and content dimensions.
  5592. */
  5593. __computeScrollMax: function(zoomLevel) {
  5594. var self = this;
  5595. if (zoomLevel == null) {
  5596. zoomLevel = self.__zoomLevel;
  5597. }
  5598. self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0);
  5599. self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0);
  5600. if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {
  5601. self.__didWaitForSize = true;
  5602. self.__waitForSize();
  5603. }
  5604. },
  5605. /**
  5606. * If the scroll view isn't sized correctly on start, wait until we have at least some size
  5607. */
  5608. __waitForSize: function() {
  5609. var self = this;
  5610. clearTimeout(self.__sizerTimeout);
  5611. var sizer = function() {
  5612. self.resize(true);
  5613. };
  5614. sizer();
  5615. self.__sizerTimeout = setTimeout(sizer, 500);
  5616. },
  5617. /*
  5618. ---------------------------------------------------------------------------
  5619. ANIMATION (DECELERATION) SUPPORT
  5620. ---------------------------------------------------------------------------
  5621. */
  5622. /**
  5623. * Called when a touch sequence end and the speed of the finger was high enough
  5624. * to switch into deceleration mode.
  5625. */
  5626. __startDeceleration: function() {
  5627. var self = this;
  5628. if (self.options.paging) {
  5629. var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0);
  5630. var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0);
  5631. var clientWidth = self.__clientWidth;
  5632. var clientHeight = self.__clientHeight;
  5633. // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area.
  5634. // Each page should have exactly the size of the client area.
  5635. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth;
  5636. self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight;
  5637. self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth;
  5638. self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight;
  5639. } else {
  5640. self.__minDecelerationScrollLeft = 0;
  5641. self.__minDecelerationScrollTop = 0;
  5642. self.__maxDecelerationScrollLeft = self.__maxScrollLeft;
  5643. self.__maxDecelerationScrollTop = self.__maxScrollTop;
  5644. if (self.__refreshActive) self.__minDecelerationScrollTop = self.__refreshHeight * -1;
  5645. }
  5646. // Wrap class method
  5647. var step = function(percent, now, render) {
  5648. self.__stepThroughDeceleration(render);
  5649. };
  5650. // How much velocity is required to keep the deceleration running
  5651. self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1;
  5652. // Detect whether it's still worth to continue animating steps
  5653. // If we are already slow enough to not being user perceivable anymore, we stop the whole process here.
  5654. var verify = function() {
  5655. var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating ||
  5656. Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating;
  5657. if (!shouldContinue) {
  5658. self.__didDecelerationComplete = true;
  5659. //Make sure the scroll values are within the boundaries after a bounce,
  5660. //not below 0 or above maximum
  5661. if (self.options.bouncing && !self.__refreshActive) {
  5662. self.scrollTo(
  5663. Math.min( Math.max(self.__scrollLeft, 0), self.__maxScrollLeft ),
  5664. Math.min( Math.max(self.__scrollTop, 0), self.__maxScrollTop ),
  5665. self.__refreshActive
  5666. );
  5667. }
  5668. }
  5669. return shouldContinue;
  5670. };
  5671. var completed = function() {
  5672. self.__isDecelerating = false;
  5673. if (self.__didDecelerationComplete) {
  5674. self.__scrollingComplete();
  5675. }
  5676. // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions
  5677. if (self.options.paging) {
  5678. self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping);
  5679. }
  5680. };
  5681. // Start animation and switch on flag
  5682. self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed);
  5683. },
  5684. /**
  5685. * Called on every step of the animation
  5686. *
  5687. * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only!
  5688. */
  5689. __stepThroughDeceleration: function(render) {
  5690. var self = this;
  5691. //
  5692. // COMPUTE NEXT SCROLL POSITION
  5693. //
  5694. // Add deceleration to scroll position
  5695. var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration);
  5696. var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration);
  5697. //
  5698. // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE
  5699. //
  5700. if (!self.options.bouncing) {
  5701. var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);
  5702. if (scrollLeftFixed !== scrollLeft) {
  5703. scrollLeft = scrollLeftFixed;
  5704. self.__decelerationVelocityX = 0;
  5705. }
  5706. var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);
  5707. if (scrollTopFixed !== scrollTop) {
  5708. scrollTop = scrollTopFixed;
  5709. self.__decelerationVelocityY = 0;
  5710. }
  5711. }
  5712. //
  5713. // UPDATE SCROLL POSITION
  5714. //
  5715. if (render) {
  5716. self.__publish(scrollLeft, scrollTop, self.__zoomLevel);
  5717. } else {
  5718. self.__scrollLeft = scrollLeft;
  5719. self.__scrollTop = scrollTop;
  5720. }
  5721. //
  5722. // SLOW DOWN
  5723. //
  5724. // Slow down velocity on every iteration
  5725. if (!self.options.paging) {
  5726. // This is the factor applied to every iteration of the animation
  5727. // to slow down the process. This should emulate natural behavior where
  5728. // objects slow down when the initiator of the movement is removed
  5729. var frictionFactor = self.options.deceleration;
  5730. self.__decelerationVelocityX *= frictionFactor;
  5731. self.__decelerationVelocityY *= frictionFactor;
  5732. }
  5733. //
  5734. // BOUNCING SUPPORT
  5735. //
  5736. if (self.options.bouncing) {
  5737. var scrollOutsideX = 0;
  5738. var scrollOutsideY = 0;
  5739. // This configures the amount of change applied to deceleration/acceleration when reaching boundaries
  5740. var penetrationDeceleration = self.options.penetrationDeceleration;
  5741. var penetrationAcceleration = self.options.penetrationAcceleration;
  5742. // Check limits
  5743. if (scrollLeft < self.__minDecelerationScrollLeft) {
  5744. scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;
  5745. } else if (scrollLeft > self.__maxDecelerationScrollLeft) {
  5746. scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;
  5747. }
  5748. if (scrollTop < self.__minDecelerationScrollTop) {
  5749. scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;
  5750. } else if (scrollTop > self.__maxDecelerationScrollTop) {
  5751. scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;
  5752. }
  5753. // Slow down until slow enough, then flip back to snap position
  5754. if (scrollOutsideX !== 0) {
  5755. var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft;
  5756. if (isHeadingOutwardsX) {
  5757. self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;
  5758. }
  5759. var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating;
  5760. //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
  5761. if (!isHeadingOutwardsX || isStoppedX) {
  5762. self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;
  5763. }
  5764. }
  5765. if (scrollOutsideY !== 0) {
  5766. var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop;
  5767. if (isHeadingOutwardsY) {
  5768. self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;
  5769. }
  5770. var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating;
  5771. //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
  5772. if (!isHeadingOutwardsY || isStoppedY) {
  5773. self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;
  5774. }
  5775. }
  5776. }
  5777. },
  5778. /**
  5779. * calculate the distance between two touches
  5780. * @param {Touch} touch1
  5781. * @param {Touch} touch2
  5782. * @returns {Number} distance
  5783. */
  5784. __getDistance: function getDistance(touch1, touch2) {
  5785. var x = touch2.pageX - touch1.pageX,
  5786. y = touch2.pageY - touch1.pageY;
  5787. return Math.sqrt((x * x) + (y * y));
  5788. },
  5789. /**
  5790. * calculate the scale factor between two touchLists (fingers)
  5791. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  5792. * @param {Array} start
  5793. * @param {Array} end
  5794. * @returns {Number} scale
  5795. */
  5796. __getScale: function getScale(start, end) {
  5797. // need two fingers...
  5798. if (start.length >= 2 && end.length >= 2) {
  5799. return this.__getDistance(end[0], end[1]) /
  5800. this.__getDistance(start[0], start[1]);
  5801. }
  5802. return 1;
  5803. }
  5804. });
  5805. ionic.scroll = {
  5806. isScrolling: false,
  5807. lastTop: 0
  5808. };
  5809. })(ionic);
  5810. (function(ionic) {
  5811. var NOOP = function() {};
  5812. var deprecated = function(name) {
  5813. void 0;
  5814. };
  5815. ionic.views.ScrollNative = ionic.views.View.inherit({
  5816. initialize: function(options) {
  5817. var self = this;
  5818. self.__container = self.el = options.el;
  5819. self.__content = options.el.firstElementChild;
  5820. // Whether scrolling is frozen or not
  5821. self.__frozen = false;
  5822. self.isNative = true;
  5823. self.__scrollTop = self.el.scrollTop;
  5824. self.__scrollLeft = self.el.scrollLeft;
  5825. self.__clientHeight = self.__content.clientHeight;
  5826. self.__clientWidth = self.__content.clientWidth;
  5827. self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);
  5828. self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);
  5829. if(options.startY >= 0 || options.startX >= 0) {
  5830. ionic.requestAnimationFrame(function() {
  5831. self.el.scrollTop = options.startY || 0;
  5832. self.el.scrollLeft = options.startX || 0;
  5833. self.__scrollTop = self.el.scrollTop;
  5834. self.__scrollLeft = self.el.scrollLeft;
  5835. });
  5836. }
  5837. self.options = {
  5838. freeze: false,
  5839. getContentWidth: function() {
  5840. return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);
  5841. },
  5842. getContentHeight: function() {
  5843. return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));
  5844. }
  5845. };
  5846. for (var key in options) {
  5847. self.options[key] = options[key];
  5848. }
  5849. /**
  5850. * Sets isScrolling to true, and automatically deactivates if not called again in 80ms.
  5851. */
  5852. self.onScroll = function() {
  5853. if (!ionic.scroll.isScrolling) {
  5854. ionic.scroll.isScrolling = true;
  5855. }
  5856. clearTimeout(self.scrollTimer);
  5857. self.scrollTimer = setTimeout(function() {
  5858. ionic.scroll.isScrolling = false;
  5859. }, 80);
  5860. };
  5861. self.freeze = function(shouldFreeze) {
  5862. self.__frozen = shouldFreeze;
  5863. };
  5864. // A more powerful freeze pop that dominates all other freeze pops
  5865. self.freezeShut = function(shouldFreezeShut) {
  5866. self.__frozenShut = shouldFreezeShut;
  5867. };
  5868. self.__initEventHandlers();
  5869. },
  5870. /** Methods not used in native scrolling */
  5871. __callback: function() { deprecated('__callback'); },
  5872. zoomTo: function() { deprecated('zoomTo'); },
  5873. zoomBy: function() { deprecated('zoomBy'); },
  5874. activatePullToRefresh: function() { deprecated('activatePullToRefresh'); },
  5875. /**
  5876. * Returns the scroll position and zooming values
  5877. *
  5878. * @return {Map} `left` and `top` scroll position and `zoom` level
  5879. */
  5880. resize: function(continueScrolling) {
  5881. var self = this;
  5882. if (!self.__container || !self.options) return;
  5883. // Update Scroller dimensions for changed content
  5884. // Add padding to bottom of content
  5885. self.setDimensions(
  5886. self.__container.clientWidth,
  5887. self.__container.clientHeight,
  5888. self.options.getContentWidth(),
  5889. self.options.getContentHeight(),
  5890. continueScrolling
  5891. );
  5892. },
  5893. /**
  5894. * Initialize the scrollview
  5895. * In native scrolling, this only means we need to gather size information
  5896. */
  5897. run: function() {
  5898. this.resize();
  5899. },
  5900. /**
  5901. * Returns the scroll position and zooming values
  5902. *
  5903. * @return {Map} `left` and `top` scroll position and `zoom` level
  5904. */
  5905. getValues: function() {
  5906. var self = this;
  5907. self.update();
  5908. return {
  5909. left: self.__scrollLeft,
  5910. top: self.__scrollTop,
  5911. zoom: 1
  5912. };
  5913. },
  5914. /**
  5915. * Updates the __scrollLeft and __scrollTop values to el's current value
  5916. */
  5917. update: function() {
  5918. var self = this;
  5919. self.__scrollLeft = self.el.scrollLeft;
  5920. self.__scrollTop = self.el.scrollTop;
  5921. },
  5922. /**
  5923. * Configures the dimensions of the client (outer) and content (inner) elements.
  5924. * Requires the available space for the outer element and the outer size of the inner element.
  5925. * All values which are falsy (null or zero etc.) are ignored and the old value is kept.
  5926. *
  5927. * @param clientWidth {Integer} Inner width of outer element
  5928. * @param clientHeight {Integer} Inner height of outer element
  5929. * @param contentWidth {Integer} Outer width of inner element
  5930. * @param contentHeight {Integer} Outer height of inner element
  5931. */
  5932. setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) {
  5933. var self = this;
  5934. if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {
  5935. // this scrollview isn't rendered, don't bother
  5936. return;
  5937. }
  5938. // Only update values which are defined
  5939. if (clientWidth === +clientWidth) {
  5940. self.__clientWidth = clientWidth;
  5941. }
  5942. if (clientHeight === +clientHeight) {
  5943. self.__clientHeight = clientHeight;
  5944. }
  5945. if (contentWidth === +contentWidth) {
  5946. self.__contentWidth = contentWidth;
  5947. }
  5948. if (contentHeight === +contentHeight) {
  5949. self.__contentHeight = contentHeight;
  5950. }
  5951. // Refresh maximums
  5952. self.__computeScrollMax();
  5953. },
  5954. /**
  5955. * Returns the maximum scroll values
  5956. *
  5957. * @return {Map} `left` and `top` maximum scroll values
  5958. */
  5959. getScrollMax: function() {
  5960. return {
  5961. left: this.__maxScrollLeft,
  5962. top: this.__maxScrollTop
  5963. };
  5964. },
  5965. /**
  5966. * Scrolls by the given amount in px.
  5967. *
  5968. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5969. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5970. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5971. */
  5972. scrollBy: function(left, top, animate) {
  5973. var self = this;
  5974. // update scroll vars before refferencing them
  5975. self.update();
  5976. var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;
  5977. var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;
  5978. self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);
  5979. },
  5980. /**
  5981. * Scrolls to the given position in px.
  5982. *
  5983. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5984. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5985. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5986. */
  5987. scrollTo: function(left, top, animate) {
  5988. var self = this;
  5989. if (!animate) {
  5990. self.el.scrollTop = top;
  5991. self.el.scrollLeft = left;
  5992. self.resize();
  5993. return;
  5994. }
  5995. var oldOverflowX = self.el.style.overflowX;
  5996. var oldOverflowY = self.el.style.overflowY;
  5997. clearTimeout(self.__scrollToCleanupTimeout);
  5998. self.__scrollToCleanupTimeout = setTimeout(function() {
  5999. self.el.style.overflowX = oldOverflowX;
  6000. self.el.style.overflowY = oldOverflowY;
  6001. }, 500);
  6002. self.el.style.overflowY = 'hidden';
  6003. self.el.style.overflowX = 'hidden';
  6004. animateScroll(top, left);
  6005. function animateScroll(Y, X) {
  6006. // scroll animation loop w/ easing
  6007. // credit https://gist.github.com/dezinezync/5487119
  6008. var start = Date.now(),
  6009. duration = 250, //milliseconds
  6010. fromY = self.el.scrollTop,
  6011. fromX = self.el.scrollLeft;
  6012. if (fromY === Y && fromX === X) {
  6013. self.el.style.overflowX = oldOverflowX;
  6014. self.el.style.overflowY = oldOverflowY;
  6015. self.resize();
  6016. return; /* Prevent scrolling to the Y point if already there */
  6017. }
  6018. // decelerating to zero velocity
  6019. function easeOutCubic(t) {
  6020. return (--t) * t * t + 1;
  6021. }
  6022. // scroll loop
  6023. function animateScrollStep() {
  6024. var currentTime = Date.now(),
  6025. time = Math.min(1, ((currentTime - start) / duration)),
  6026. // where .5 would be 50% of time on a linear scale easedT gives a
  6027. // fraction based on the easing method
  6028. easedT = easeOutCubic(time);
  6029. if (fromY != Y) {
  6030. self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);
  6031. }
  6032. if (fromX != X) {
  6033. self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);
  6034. }
  6035. if (time < 1) {
  6036. ionic.requestAnimationFrame(animateScrollStep);
  6037. } else {
  6038. // done
  6039. ionic.tap.removeClonedInputs(self.__container, self);
  6040. self.el.style.overflowX = oldOverflowX;
  6041. self.el.style.overflowY = oldOverflowY;
  6042. self.resize();
  6043. }
  6044. }
  6045. // start scroll loop
  6046. ionic.requestAnimationFrame(animateScrollStep);
  6047. }
  6048. },
  6049. /*
  6050. ---------------------------------------------------------------------------
  6051. PRIVATE API
  6052. ---------------------------------------------------------------------------
  6053. */
  6054. /**
  6055. * If the scroll view isn't sized correctly on start, wait until we have at least some size
  6056. */
  6057. __waitForSize: function() {
  6058. var self = this;
  6059. clearTimeout(self.__sizerTimeout);
  6060. var sizer = function() {
  6061. self.resize(true);
  6062. };
  6063. sizer();
  6064. self.__sizerTimeout = setTimeout(sizer, 500);
  6065. },
  6066. /**
  6067. * Recomputes scroll minimum values based on client dimensions and content dimensions.
  6068. */
  6069. __computeScrollMax: function() {
  6070. var self = this;
  6071. self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);
  6072. self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);
  6073. if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {
  6074. self.__didWaitForSize = true;
  6075. self.__waitForSize();
  6076. }
  6077. },
  6078. __initEventHandlers: function() {
  6079. var self = this;
  6080. // Event Handler
  6081. var container = self.__container;
  6082. // save height when scroll view is shrunk so we don't need to reflow
  6083. var scrollViewOffsetHeight;
  6084. var lastKeyboardHeight;
  6085. /**
  6086. * Shrink the scroll view when the keyboard is up if necessary and if the
  6087. * focused input is below the bottom of the shrunk scroll view, scroll it
  6088. * into view.
  6089. */
  6090. self.scrollChildIntoView = function(e) {
  6091. var rect = container.getBoundingClientRect();
  6092. if(!self.__originalContainerHeight) {
  6093. self.__originalContainerHeight = rect.height;
  6094. }
  6095. // D
  6096. //var scrollBottomOffsetToTop = rect.bottom;
  6097. // D - A
  6098. scrollViewOffsetHeight = self.__originalContainerHeight;
  6099. //console.log('Scroll view offset height', scrollViewOffsetHeight);
  6100. //console.dir(container);
  6101. var alreadyShrunk = self.isShrunkForKeyboard;
  6102. var isModal = container.parentNode.classList.contains('modal');
  6103. var isPopover = container.parentNode.classList.contains('popover');
  6104. // 680px is when the media query for 60% modal width kicks in
  6105. var isInsetModal = isModal && window.innerWidth >= 680;
  6106. /*
  6107. * _______
  6108. * |---A---| <- top of scroll view
  6109. * | |
  6110. * |---B---| <- keyboard
  6111. * | C | <- input
  6112. * |---D---| <- initial bottom of scroll view
  6113. * |___E___| <- bottom of viewport
  6114. *
  6115. * All commented calculations relative to the top of the viewport (ie E
  6116. * is the viewport height, not 0)
  6117. */
  6118. var changedKeyboardHeight = lastKeyboardHeight && (lastKeyboardHeight !== e.detail.keyboardHeight);
  6119. if (!alreadyShrunk || changedKeyboardHeight) {
  6120. // shrink scrollview so we can actually scroll if the input is hidden
  6121. // if it isn't shrink so we can scroll to inputs under the keyboard
  6122. // inset modals won't shrink on Android on their own when the keyboard appears
  6123. if ( !isPopover && (ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal) ) {
  6124. // if there are things below the scroll view account for them and
  6125. // subtract them from the keyboard height when resizing
  6126. // E - D E D
  6127. //var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;
  6128. // 0 or D - B if D > B E - B E - D
  6129. //var keyboardOffset = e.detail.keyboardHeight - scrollBottomOffsetToBottom;
  6130. ionic.requestAnimationFrame(function(){
  6131. // D - A or B - A if D > B D - A max(0, D - B)
  6132. scrollViewOffsetHeight = Math.max(0, Math.min(self.__originalContainerHeight, self.__originalContainerHeight - (e.detail.keyboardHeight - 43)));//keyboardOffset >= 0 ? scrollViewOffsetHeight - keyboardOffset : scrollViewOffsetHeight + keyboardOffset;
  6133. //console.log('Old container height', self.__originalContainerHeight, 'New container height', scrollViewOffsetHeight, 'Keyboard height', e.detail.keyboardHeight);
  6134. container.style.height = scrollViewOffsetHeight + "px";
  6135. /*
  6136. if (ionic.Platform.isIOS()) {
  6137. // Force redraw to avoid disappearing content
  6138. var disp = container.style.display;
  6139. container.style.display = 'none';
  6140. var trick = container.offsetHeight;
  6141. container.style.display = disp;
  6142. }
  6143. */
  6144. container.classList.add('keyboard-up');
  6145. //update scroll view
  6146. self.resize();
  6147. });
  6148. }
  6149. self.isShrunkForKeyboard = true;
  6150. }
  6151. lastKeyboardHeight = e.detail.keyboardHeight;
  6152. /*
  6153. * _______
  6154. * |---A---| <- top of scroll view
  6155. * | * | <- where we want to scroll to
  6156. * |--B-D--| <- keyboard, bottom of scroll view
  6157. * | C | <- input
  6158. * | |
  6159. * |___E___| <- bottom of viewport
  6160. *
  6161. * All commented calculations relative to the top of the viewport (ie E
  6162. * is the viewport height, not 0)
  6163. */
  6164. // if the element is positioned under the keyboard scroll it into view
  6165. if (e.detail.isElementUnderKeyboard) {
  6166. ionic.requestAnimationFrame(function(){
  6167. var pos = ionic.DomUtil.getOffsetTop(e.detail.target);
  6168. setTimeout(function() {
  6169. if (ionic.Platform.isIOS()) {
  6170. ionic.tap.cloneFocusedInput(container, self);
  6171. }
  6172. // Scroll the input into view, with a 100px buffer
  6173. self.scrollTo(0, pos - (rect.top + 100), true);
  6174. self.onScroll();
  6175. }, 32);
  6176. /*
  6177. // update D if we shrunk
  6178. if (self.isShrunkForKeyboard && !alreadyShrunk) {
  6179. scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  6180. console.log('Scroll bottom', scrollBottomOffsetToTop);
  6181. }
  6182. // middle of the scrollview, this is where we want to scroll to
  6183. // (D - A) / 2
  6184. var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;
  6185. console.log('Midpoint', scrollMidpointOffset);
  6186. //console.log("container.offsetHeight: " + scrollViewOffsetHeight);
  6187. // middle of the input we want to scroll into view
  6188. // C
  6189. var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);
  6190. console.log('Input midpoint');
  6191. // distance from middle of input to the bottom of the scroll view
  6192. // C - D C D
  6193. var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;
  6194. console.log('Input midpoint offset', inputMidpointOffsetToScrollBottom);
  6195. //C - D + (D - A)/2 C - D (D - A)/ 2
  6196. var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;
  6197. console.log('Scroll top', scrollTop);
  6198. if ( scrollTop > 0) {
  6199. if (ionic.Platform.isIOS()) {
  6200. //just shrank scroll view, give it some breathing room before scrolling
  6201. setTimeout(function(){
  6202. ionic.tap.cloneFocusedInput(container, self);
  6203. self.scrollBy(0, scrollTop, true);
  6204. self.onScroll();
  6205. }, 32);
  6206. } else {
  6207. self.scrollBy(0, scrollTop, true);
  6208. self.onScroll();
  6209. }
  6210. }
  6211. */
  6212. });
  6213. }
  6214. // Only the first scrollView parent of the element that broadcasted this event
  6215. // (the active element that needs to be shown) should receive this event
  6216. e.stopPropagation();
  6217. };
  6218. self.resetScrollView = function() {
  6219. //return scrollview to original height once keyboard has hidden
  6220. if (self.isShrunkForKeyboard) {
  6221. self.isShrunkForKeyboard = false;
  6222. container.style.height = "";
  6223. /*
  6224. if (ionic.Platform.isIOS()) {
  6225. // Force redraw to avoid disappearing content
  6226. var disp = container.style.display;
  6227. container.style.display = 'none';
  6228. var trick = container.offsetHeight;
  6229. container.style.display = disp;
  6230. }
  6231. */
  6232. self.__originalContainerHeight = container.getBoundingClientRect().height;
  6233. if (ionic.Platform.isIOS()) {
  6234. ionic.requestAnimationFrame(function() {
  6235. container.classList.remove('keyboard-up');
  6236. });
  6237. }
  6238. }
  6239. self.resize();
  6240. };
  6241. self.handleTouchMove = function(e) {
  6242. if (self.__frozenShut) {
  6243. e.preventDefault();
  6244. e.stopPropagation();
  6245. return false;
  6246. } else if ( self.__frozen ){
  6247. e.preventDefault();
  6248. // let it propagate so other events such as drag events can happen,
  6249. // but don't let it actually scroll
  6250. return false;
  6251. }
  6252. return true;
  6253. };
  6254. container.addEventListener('scroll', self.onScroll);
  6255. //Broadcasted when keyboard is shown on some platforms.
  6256. //See js/utils/keyboard.js
  6257. container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);
  6258. container.addEventListener(ionic.EVENTS.touchstart, self.handleTouchMove);
  6259. container.addEventListener(ionic.EVENTS.touchmove, self.handleTouchMove);
  6260. // Listen on document because container may not have had the last
  6261. // keyboardActiveElement, for example after closing a modal with a focused
  6262. // input and returning to a previously resized scroll view in an ion-content.
  6263. // Since we can only resize scroll views that are currently visible, just resize
  6264. // the current scroll view when the keyboard is closed.
  6265. document.addEventListener('resetScrollView', self.resetScrollView);
  6266. },
  6267. __cleanup: function() {
  6268. var self = this;
  6269. var container = self.__container;
  6270. container.removeEventListener('resetScrollView', self.resetScrollView);
  6271. container.removeEventListener('scroll', self.onScroll);
  6272. container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);
  6273. container.removeEventListener('resetScrollView', self.resetScrollView);
  6274. container.removeEventListener(ionic.EVENTS.touchstart, self.handleTouchMove);
  6275. container.removeEventListener(ionic.EVENTS.touchmove, self.handleTouchMove);
  6276. ionic.tap.removeClonedInputs(container, self);
  6277. delete self.__container;
  6278. delete self.__content;
  6279. delete self.__indicatorX;
  6280. delete self.__indicatorY;
  6281. delete self.options.el;
  6282. self.resize = self.scrollTo = self.onScroll = self.resetScrollView = NOOP;
  6283. self.scrollChildIntoView = NOOP;
  6284. container = null;
  6285. }
  6286. });
  6287. })(ionic);
  6288. (function(ionic) {
  6289. 'use strict';
  6290. var ITEM_CLASS = 'item';
  6291. var ITEM_CONTENT_CLASS = 'item-content';
  6292. var ITEM_SLIDING_CLASS = 'item-sliding';
  6293. var ITEM_OPTIONS_CLASS = 'item-options';
  6294. var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';
  6295. var ITEM_REORDERING_CLASS = 'item-reordering';
  6296. var ITEM_REORDER_BTN_CLASS = 'item-reorder';
  6297. var DragOp = function() {};
  6298. DragOp.prototype = {
  6299. start: function(){},
  6300. drag: function(){},
  6301. end: function(){},
  6302. isSameItem: function() {
  6303. return false;
  6304. }
  6305. };
  6306. var SlideDrag = function(opts) {
  6307. this.dragThresholdX = opts.dragThresholdX || 10;
  6308. this.el = opts.el;
  6309. this.item = opts.item;
  6310. this.canSwipe = opts.canSwipe;
  6311. };
  6312. SlideDrag.prototype = new DragOp();
  6313. SlideDrag.prototype.start = function(e) {
  6314. var content, buttons, offsetX, buttonsWidth;
  6315. if (!this.canSwipe()) {
  6316. return;
  6317. }
  6318. if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {
  6319. content = e.target;
  6320. } else if (e.target.classList.contains(ITEM_CLASS)) {
  6321. content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);
  6322. } else {
  6323. content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);
  6324. }
  6325. // If we don't have a content area as one of our children (or ourselves), skip
  6326. if (!content) {
  6327. return;
  6328. }
  6329. // Make sure we aren't animating as we slide
  6330. content.classList.remove(ITEM_SLIDING_CLASS);
  6331. // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)
  6332. offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;
  6333. // Grab the buttons
  6334. buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);
  6335. if (!buttons) {
  6336. return;
  6337. }
  6338. buttons.classList.remove('invisible');
  6339. buttonsWidth = buttons.offsetWidth;
  6340. this._currentDrag = {
  6341. buttons: buttons,
  6342. buttonsWidth: buttonsWidth,
  6343. content: content,
  6344. startOffsetX: offsetX
  6345. };
  6346. };
  6347. /**
  6348. * Check if this is the same item that was previously dragged.
  6349. */
  6350. SlideDrag.prototype.isSameItem = function(op) {
  6351. if (op._lastDrag && this._currentDrag) {
  6352. return this._currentDrag.content == op._lastDrag.content;
  6353. }
  6354. return false;
  6355. };
  6356. SlideDrag.prototype.clean = function(isInstant) {
  6357. var lastDrag = this._lastDrag;
  6358. if (!lastDrag || !lastDrag.content) return;
  6359. lastDrag.content.style[ionic.CSS.TRANSITION] = '';
  6360. lastDrag.content.style[ionic.CSS.TRANSFORM] = '';
  6361. if (isInstant) {
  6362. lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';
  6363. makeInvisible();
  6364. ionic.requestAnimationFrame(function() {
  6365. lastDrag.content.style[ionic.CSS.TRANSITION] = '';
  6366. });
  6367. } else {
  6368. ionic.requestAnimationFrame(function() {
  6369. setTimeout(makeInvisible, 250);
  6370. });
  6371. }
  6372. function makeInvisible() {
  6373. lastDrag.buttons && lastDrag.buttons.classList.add('invisible');
  6374. }
  6375. };
  6376. SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
  6377. var buttonsWidth;
  6378. // We really aren't dragging
  6379. if (!this._currentDrag) {
  6380. return;
  6381. }
  6382. // Check if we should start dragging. Check if we've dragged past the threshold,
  6383. // or we are starting from the open state.
  6384. if (!this._isDragging &&
  6385. ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||
  6386. (Math.abs(this._currentDrag.startOffsetX) > 0))) {
  6387. this._isDragging = true;
  6388. }
  6389. if (this._isDragging) {
  6390. buttonsWidth = this._currentDrag.buttonsWidth;
  6391. // Grab the new X point, capping it at zero
  6392. var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);
  6393. // If the new X position is past the buttons, we need to slow down the drag (rubber band style)
  6394. if (newX < -buttonsWidth) {
  6395. // Calculate the new X position, capped at the top of the buttons
  6396. newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));
  6397. }
  6398. this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;
  6399. this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';
  6400. this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';
  6401. }
  6402. });
  6403. SlideDrag.prototype.end = function(e, doneCallback) {
  6404. var self = this;
  6405. // There is no drag, just end immediately
  6406. if (!self._currentDrag) {
  6407. doneCallback && doneCallback();
  6408. return;
  6409. }
  6410. // If we are currently dragging, we want to snap back into place
  6411. // The final resting point X will be the width of the exposed buttons
  6412. var restingPoint = -self._currentDrag.buttonsWidth;
  6413. // Check if the drag didn't clear the buttons mid-point
  6414. // and we aren't moving fast enough to swipe open
  6415. if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) {
  6416. // If we are going left but too slow, or going right, go back to resting
  6417. if (e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) {
  6418. restingPoint = 0;
  6419. } else if (e.gesture.direction == "right") {
  6420. restingPoint = 0;
  6421. }
  6422. }
  6423. ionic.requestAnimationFrame(function() {
  6424. if (restingPoint === 0) {
  6425. self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';
  6426. var buttons = self._currentDrag.buttons;
  6427. setTimeout(function() {
  6428. buttons && buttons.classList.add('invisible');
  6429. }, 250);
  6430. } else {
  6431. self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';
  6432. }
  6433. self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';
  6434. // Kill the current drag
  6435. if (!self._lastDrag) {
  6436. self._lastDrag = {};
  6437. }
  6438. ionic.extend(self._lastDrag, self._currentDrag);
  6439. if (self._currentDrag) {
  6440. self._currentDrag.buttons = null;
  6441. self._currentDrag.content = null;
  6442. }
  6443. self._currentDrag = null;
  6444. // We are done, notify caller
  6445. doneCallback && doneCallback();
  6446. });
  6447. };
  6448. var ReorderDrag = function(opts) {
  6449. var self = this;
  6450. self.dragThresholdY = opts.dragThresholdY || 0;
  6451. self.onReorder = opts.onReorder;
  6452. self.listEl = opts.listEl;
  6453. self.el = self.item = opts.el;
  6454. self.scrollEl = opts.scrollEl;
  6455. self.scrollView = opts.scrollView;
  6456. // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html
  6457. self.listElTrueTop = 0;
  6458. if (self.listEl.offsetParent) {
  6459. var obj = self.listEl;
  6460. do {
  6461. self.listElTrueTop += obj.offsetTop;
  6462. obj = obj.offsetParent;
  6463. } while (obj);
  6464. }
  6465. };
  6466. ReorderDrag.prototype = new DragOp();
  6467. ReorderDrag.prototype._moveElement = function(e) {
  6468. var y = e.gesture.center.pageY +
  6469. this.scrollView.getValues().top -
  6470. (this._currentDrag.elementHeight / 2) -
  6471. this.listElTrueTop;
  6472. this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)';
  6473. };
  6474. ReorderDrag.prototype.deregister = function() {
  6475. this.listEl = this.el = this.scrollEl = this.scrollView = null;
  6476. };
  6477. ReorderDrag.prototype.start = function(e) {
  6478. var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());
  6479. var elementHeight = this.el.scrollHeight;
  6480. var placeholder = this.el.cloneNode(true);
  6481. placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);
  6482. this.el.parentNode.insertBefore(placeholder, this.el);
  6483. this.el.classList.add(ITEM_REORDERING_CLASS);
  6484. this._currentDrag = {
  6485. elementHeight: elementHeight,
  6486. startIndex: startIndex,
  6487. placeholder: placeholder,
  6488. scrollHeight: scroll,
  6489. list: placeholder.parentNode
  6490. };
  6491. this._moveElement(e);
  6492. };
  6493. ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
  6494. // We really aren't dragging
  6495. var self = this;
  6496. if (!this._currentDrag) {
  6497. return;
  6498. }
  6499. var scrollY = 0;
  6500. var pageY = e.gesture.center.pageY;
  6501. var offset = this.listElTrueTop;
  6502. //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary
  6503. if (this.scrollView) {
  6504. var container = this.scrollView.__container;
  6505. scrollY = this.scrollView.getValues().top;
  6506. var containerTop = container.offsetTop;
  6507. var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2;
  6508. var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight;
  6509. if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) {
  6510. this.scrollView.scrollBy(null, -pixelsPastTop);
  6511. //Trigger another drag so the scrolling keeps going
  6512. ionic.requestAnimationFrame(function() {
  6513. self.drag(e);
  6514. });
  6515. }
  6516. if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) {
  6517. if (scrollY < this.scrollView.getScrollMax().top) {
  6518. this.scrollView.scrollBy(null, pixelsPastBottom);
  6519. //Trigger another drag so the scrolling keeps going
  6520. ionic.requestAnimationFrame(function() {
  6521. self.drag(e);
  6522. });
  6523. }
  6524. }
  6525. }
  6526. // Check if we should start dragging. Check if we've dragged past the threshold,
  6527. // or we are starting from the open state.
  6528. if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) {
  6529. this._isDragging = true;
  6530. }
  6531. if (this._isDragging) {
  6532. this._moveElement(e);
  6533. this._currentDrag.currentY = scrollY + pageY - offset;
  6534. // this._reorderItems();
  6535. }
  6536. });
  6537. // When an item is dragged, we need to reorder any items for sorting purposes
  6538. ReorderDrag.prototype._getReorderIndex = function() {
  6539. var self = this;
  6540. var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children)
  6541. .filter(function(el) {
  6542. return el.nodeName === self.el.nodeName && el !== self.el;
  6543. });
  6544. var dragOffsetTop = self._currentDrag.currentY;
  6545. var el;
  6546. for (var i = 0, len = siblings.length; i < len; i++) {
  6547. el = siblings[i];
  6548. if (i === len - 1) {
  6549. if (dragOffsetTop > el.offsetTop) {
  6550. return i;
  6551. }
  6552. } else if (i === 0) {
  6553. if (dragOffsetTop < el.offsetTop + el.offsetHeight) {
  6554. return i;
  6555. }
  6556. } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 &&
  6557. dragOffsetTop < el.offsetTop + el.offsetHeight) {
  6558. return i;
  6559. }
  6560. }
  6561. return self._currentDrag.startIndex;
  6562. };
  6563. ReorderDrag.prototype.end = function(e, doneCallback) {
  6564. if (!this._currentDrag) {
  6565. doneCallback && doneCallback();
  6566. return;
  6567. }
  6568. var placeholder = this._currentDrag.placeholder;
  6569. var finalIndex = this._getReorderIndex();
  6570. // Reposition the element
  6571. this.el.classList.remove(ITEM_REORDERING_CLASS);
  6572. this.el.style[ionic.CSS.TRANSFORM] = '';
  6573. placeholder.parentNode.insertBefore(this.el, placeholder);
  6574. placeholder.parentNode.removeChild(placeholder);
  6575. this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex);
  6576. this._currentDrag = {
  6577. placeholder: null,
  6578. content: null
  6579. };
  6580. this._currentDrag = null;
  6581. doneCallback && doneCallback();
  6582. };
  6583. /**
  6584. * The ListView handles a list of items. It will process drag animations, edit mode,
  6585. * and other operations that are common on mobile lists or table views.
  6586. */
  6587. ionic.views.ListView = ionic.views.View.inherit({
  6588. initialize: function(opts) {
  6589. var self = this;
  6590. opts = ionic.extend({
  6591. onReorder: function() {},
  6592. virtualRemoveThreshold: -200,
  6593. virtualAddThreshold: 200,
  6594. canSwipe: function() {
  6595. return true;
  6596. }
  6597. }, opts);
  6598. ionic.extend(self, opts);
  6599. if (!self.itemHeight && self.listEl) {
  6600. self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10);
  6601. }
  6602. self.onRefresh = opts.onRefresh || function() {};
  6603. self.onRefreshOpening = opts.onRefreshOpening || function() {};
  6604. self.onRefreshHolding = opts.onRefreshHolding || function() {};
  6605. var gestureOpts = {};
  6606. // don't prevent native scrolling
  6607. if (ionic.DomUtil.getParentOrSelfWithClass(self.el, 'overflow-scroll')) {
  6608. gestureOpts.prevent_default_directions = ['left', 'right'];
  6609. }
  6610. window.ionic.onGesture('release', function(e) {
  6611. self._handleEndDrag(e);
  6612. }, self.el, gestureOpts);
  6613. window.ionic.onGesture('drag', function(e) {
  6614. self._handleDrag(e);
  6615. }, self.el, gestureOpts);
  6616. // Start the drag states
  6617. self._initDrag();
  6618. },
  6619. /**
  6620. * Be sure to cleanup references.
  6621. */
  6622. deregister: function() {
  6623. this.el = this.listEl = this.scrollEl = this.scrollView = null;
  6624. // ensure no scrolls have been left frozen
  6625. if (this.isScrollFreeze) {
  6626. self.scrollView.freeze(false);
  6627. }
  6628. },
  6629. /**
  6630. * Called to tell the list to stop refreshing. This is useful
  6631. * if you are refreshing the list and are done with refreshing.
  6632. */
  6633. stopRefreshing: function() {
  6634. var refresher = this.el.querySelector('.list-refresher');
  6635. refresher.style.height = '0';
  6636. },
  6637. /**
  6638. * If we scrolled and have virtual mode enabled, compute the window
  6639. * of active elements in order to figure out the viewport to render.
  6640. */
  6641. didScroll: function(e) {
  6642. var self = this;
  6643. if (self.isVirtual) {
  6644. var itemHeight = self.itemHeight;
  6645. // Grab the total height of the list
  6646. var scrollHeight = e.target.scrollHeight;
  6647. // Get the viewport height
  6648. var viewportHeight = self.el.parentNode.offsetHeight;
  6649. // High water is the pixel position of the first element to include (everything before
  6650. // that will be removed)
  6651. var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold);
  6652. // Low water is the pixel position of the last element to include (everything after
  6653. // that will be removed)
  6654. var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold);
  6655. // Get the first and last elements in the list based on how many can fit
  6656. // between the pixel range of lowWater and highWater
  6657. var first = parseInt(Math.abs(highWater / itemHeight), 10);
  6658. var last = parseInt(Math.abs(lowWater / itemHeight), 10);
  6659. // Get the items we need to remove
  6660. self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first);
  6661. self.renderViewport && self.renderViewport(highWater, lowWater, first, last);
  6662. }
  6663. },
  6664. didStopScrolling: function() {
  6665. if (this.isVirtual) {
  6666. for (var i = 0; i < this._virtualItemsToRemove.length; i++) {
  6667. //el.parentNode.removeChild(el);
  6668. this.didHideItem && this.didHideItem(i);
  6669. }
  6670. // Once scrolling stops, check if we need to remove old items
  6671. }
  6672. },
  6673. /**
  6674. * Clear any active drag effects on the list.
  6675. */
  6676. clearDragEffects: function(isInstant) {
  6677. if (this._lastDragOp) {
  6678. this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
  6679. this._lastDragOp.deregister && this._lastDragOp.deregister();
  6680. this._lastDragOp = null;
  6681. }
  6682. },
  6683. _initDrag: function() {
  6684. // Store the last one
  6685. if (this._lastDragOp) {
  6686. this._lastDragOp.deregister && this._lastDragOp.deregister();
  6687. }
  6688. this._lastDragOp = this._dragOp;
  6689. this._dragOp = null;
  6690. },
  6691. // Return the list item from the given target
  6692. _getItem: function(target) {
  6693. while (target) {
  6694. if (target.classList && target.classList.contains(ITEM_CLASS)) {
  6695. return target;
  6696. }
  6697. target = target.parentNode;
  6698. }
  6699. return null;
  6700. },
  6701. _startDrag: function(e) {
  6702. var self = this;
  6703. self._isDragging = false;
  6704. var lastDragOp = self._lastDragOp;
  6705. var item;
  6706. // If we have an open SlideDrag and we're scrolling the list. Clear it.
  6707. if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) {
  6708. lastDragOp.clean && lastDragOp.clean();
  6709. }
  6710. // Check if this is a reorder drag
  6711. if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
  6712. item = self._getItem(e.target);
  6713. if (item) {
  6714. self._dragOp = new ReorderDrag({
  6715. listEl: self.el,
  6716. el: item,
  6717. scrollEl: self.scrollEl,
  6718. scrollView: self.scrollView,
  6719. onReorder: function(el, start, end) {
  6720. self.onReorder && self.onReorder(el, start, end);
  6721. }
  6722. });
  6723. self._dragOp.start(e);
  6724. e.preventDefault();
  6725. }
  6726. }
  6727. // Or check if this is a swipe to the side drag
  6728. else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {
  6729. // Make sure this is an item with buttons
  6730. item = self._getItem(e.target);
  6731. if (item && item.querySelector('.item-options')) {
  6732. self._dragOp = new SlideDrag({
  6733. el: self.el,
  6734. item: item,
  6735. canSwipe: self.canSwipe
  6736. });
  6737. self._dragOp.start(e);
  6738. e.preventDefault();
  6739. self.isScrollFreeze = self.scrollView.freeze(true);
  6740. }
  6741. }
  6742. // If we had a last drag operation and this is a new one on a different item, clean that last one
  6743. if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) {
  6744. lastDragOp.clean && lastDragOp.clean();
  6745. }
  6746. },
  6747. _handleEndDrag: function(e) {
  6748. var self = this;
  6749. if (self.scrollView) {
  6750. self.isScrollFreeze = self.scrollView.freeze(false);
  6751. }
  6752. self._didDragUpOrDown = false;
  6753. if (!self._dragOp) {
  6754. return;
  6755. }
  6756. self._dragOp.end(e, function() {
  6757. self._initDrag();
  6758. });
  6759. },
  6760. /**
  6761. * Process the drag event to move the item to the left or right.
  6762. */
  6763. _handleDrag: function(e) {
  6764. var self = this;
  6765. if (Math.abs(e.gesture.deltaY) > 5) {
  6766. self._didDragUpOrDown = true;
  6767. }
  6768. // If we get a drag event, make sure we aren't in another drag, then check if we should
  6769. // start one
  6770. if (!self.isDragging && !self._dragOp) {
  6771. self._startDrag(e);
  6772. }
  6773. // No drag still, pass it up
  6774. if (!self._dragOp) {
  6775. return;
  6776. }
  6777. e.gesture.srcEvent.preventDefault();
  6778. self._dragOp.drag(e);
  6779. }
  6780. });
  6781. })(ionic);
  6782. (function(ionic) {
  6783. 'use strict';
  6784. ionic.views.Modal = ionic.views.View.inherit({
  6785. initialize: function(opts) {
  6786. opts = ionic.extend({
  6787. focusFirstInput: false,
  6788. unfocusOnHide: true,
  6789. focusFirstDelay: 600,
  6790. backdropClickToClose: true,
  6791. hardwareBackButtonClose: true,
  6792. }, opts);
  6793. ionic.extend(this, opts);
  6794. this.el = opts.el;
  6795. },
  6796. show: function() {
  6797. var self = this;
  6798. if(self.focusFirstInput) {
  6799. // Let any animations run first
  6800. window.setTimeout(function() {
  6801. var input = self.el.querySelector('input, textarea');
  6802. input && input.focus && input.focus();
  6803. }, self.focusFirstDelay);
  6804. }
  6805. },
  6806. hide: function() {
  6807. // Unfocus all elements
  6808. if(this.unfocusOnHide) {
  6809. var inputs = this.el.querySelectorAll('input, textarea');
  6810. // Let any animations run first
  6811. window.setTimeout(function() {
  6812. for(var i = 0; i < inputs.length; i++) {
  6813. inputs[i].blur && inputs[i].blur();
  6814. }
  6815. });
  6816. }
  6817. }
  6818. });
  6819. })(ionic);
  6820. (function(ionic) {
  6821. 'use strict';
  6822. /**
  6823. * The side menu view handles one of the side menu's in a Side Menu Controller
  6824. * configuration.
  6825. * It takes a DOM reference to that side menu element.
  6826. */
  6827. ionic.views.SideMenu = ionic.views.View.inherit({
  6828. initialize: function(opts) {
  6829. this.el = opts.el;
  6830. this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled;
  6831. this.setWidth(opts.width);
  6832. },
  6833. getFullWidth: function() {
  6834. return this.width;
  6835. },
  6836. setWidth: function(width) {
  6837. this.width = width;
  6838. this.el.style.width = width + 'px';
  6839. },
  6840. setIsEnabled: function(isEnabled) {
  6841. this.isEnabled = isEnabled;
  6842. },
  6843. bringUp: function() {
  6844. if(this.el.style.zIndex !== '0') {
  6845. this.el.style.zIndex = '0';
  6846. }
  6847. },
  6848. pushDown: function() {
  6849. if(this.el.style.zIndex !== '-1') {
  6850. this.el.style.zIndex = '-1';
  6851. }
  6852. }
  6853. });
  6854. ionic.views.SideMenuContent = ionic.views.View.inherit({
  6855. initialize: function(opts) {
  6856. ionic.extend(this, {
  6857. animationClass: 'menu-animated',
  6858. onDrag: function() {},
  6859. onEndDrag: function() {}
  6860. }, opts);
  6861. ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);
  6862. ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);
  6863. },
  6864. _onDrag: function(e) {
  6865. this.onDrag && this.onDrag(e);
  6866. },
  6867. _onEndDrag: function(e) {
  6868. this.onEndDrag && this.onEndDrag(e);
  6869. },
  6870. disableAnimation: function() {
  6871. this.el.classList.remove(this.animationClass);
  6872. },
  6873. enableAnimation: function() {
  6874. this.el.classList.add(this.animationClass);
  6875. },
  6876. getTranslateX: function() {
  6877. return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]);
  6878. },
  6879. setTranslateX: ionic.animationFrameThrottle(function(x) {
  6880. this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)';
  6881. })
  6882. });
  6883. })(ionic);
  6884. /*
  6885. * Adapted from Swipe.js 2.0
  6886. *
  6887. * Brad Birdsall
  6888. * Copyright 2013, MIT License
  6889. *
  6890. */
  6891. (function(ionic) {
  6892. 'use strict';
  6893. ionic.views.Slider = ionic.views.View.inherit({
  6894. initialize: function (options) {
  6895. var slider = this;
  6896. var touchStartEvent, touchMoveEvent, touchEndEvent;
  6897. if (window.navigator.pointerEnabled) {
  6898. touchStartEvent = 'pointerdown';
  6899. touchMoveEvent = 'pointermove';
  6900. touchEndEvent = 'pointerup';
  6901. } else if (window.navigator.msPointerEnabled) {
  6902. touchStartEvent = 'MSPointerDown';
  6903. touchMoveEvent = 'MSPointerMove';
  6904. touchEndEvent = 'MSPointerUp';
  6905. } else {
  6906. touchStartEvent = 'touchstart';
  6907. touchMoveEvent = 'touchmove';
  6908. touchEndEvent = 'touchend';
  6909. }
  6910. var mouseStartEvent = 'mousedown';
  6911. var mouseMoveEvent = 'mousemove';
  6912. var mouseEndEvent = 'mouseup';
  6913. // utilities
  6914. var noop = function() {}; // simple no operation function
  6915. var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution
  6916. // check browser capabilities
  6917. var browser = {
  6918. addEventListener: !!window.addEventListener,
  6919. transitions: (function(temp) {
  6920. var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
  6921. for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
  6922. return false;
  6923. })(document.createElement('swipe'))
  6924. };
  6925. var container = options.el;
  6926. // quit if no root element
  6927. if (!container) return;
  6928. var element = container.children[0];
  6929. var slides, slidePos, width, length;
  6930. options = options || {};
  6931. var index = parseInt(options.startSlide, 10) || 0;
  6932. var speed = options.speed || 300;
  6933. options.continuous = options.continuous !== undefined ? options.continuous : true;
  6934. function setup() {
  6935. // do not setup if the container has no width
  6936. if (!container.offsetWidth) {
  6937. return;
  6938. }
  6939. // cache slides
  6940. slides = element.children;
  6941. length = slides.length;
  6942. // set continuous to false if only one slide
  6943. if (slides.length < 2) options.continuous = false;
  6944. //special case if two slides
  6945. if (browser.transitions && options.continuous && slides.length < 3) {
  6946. element.appendChild(slides[0].cloneNode(true));
  6947. element.appendChild(element.children[1].cloneNode(true));
  6948. slides = element.children;
  6949. }
  6950. // create an array to store current positions of each slide
  6951. slidePos = new Array(slides.length);
  6952. // determine width of each slide
  6953. width = container.offsetWidth || container.getBoundingClientRect().width;
  6954. element.style.width = (slides.length * width) + 'px';
  6955. // stack elements
  6956. var pos = slides.length;
  6957. while(pos--) {
  6958. var slide = slides[pos];
  6959. slide.style.width = width + 'px';
  6960. slide.setAttribute('data-index', pos);
  6961. if (browser.transitions) {
  6962. slide.style.left = (pos * -width) + 'px';
  6963. move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
  6964. }
  6965. }
  6966. // reposition elements before and after index
  6967. if (options.continuous && browser.transitions) {
  6968. move(circle(index - 1), -width, 0);
  6969. move(circle(index + 1), width, 0);
  6970. }
  6971. if (!browser.transitions) element.style.left = (index * -width) + 'px';
  6972. container.style.visibility = 'visible';
  6973. options.slidesChanged && options.slidesChanged();
  6974. }
  6975. function prev(slideSpeed) {
  6976. if (options.continuous) slide(index - 1, slideSpeed);
  6977. else if (index) slide(index - 1, slideSpeed);
  6978. }
  6979. function next(slideSpeed) {
  6980. if (options.continuous) slide(index + 1, slideSpeed);
  6981. else if (index < slides.length - 1) slide(index + 1, slideSpeed);
  6982. }
  6983. function circle(index) {
  6984. // a simple positive modulo using slides.length
  6985. return (slides.length + (index % slides.length)) % slides.length;
  6986. }
  6987. function slide(to, slideSpeed) {
  6988. // do nothing if already on requested slide
  6989. if (index == to) return;
  6990. if (!slides) {
  6991. index = to;
  6992. return;
  6993. }
  6994. if (browser.transitions) {
  6995. var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
  6996. // get the actual position of the slide
  6997. if (options.continuous) {
  6998. var naturalDirection = direction;
  6999. direction = -slidePos[circle(to)] / width;
  7000. // if going forward but to < index, use to = slides.length + to
  7001. // if going backward but to > index, use to = -slides.length + to
  7002. if (direction !== naturalDirection) to = -direction * slides.length + to;
  7003. }
  7004. var diff = Math.abs(index - to) - 1;
  7005. // move all the slides between index and to in the right direction
  7006. while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
  7007. to = circle(to);
  7008. move(index, width * direction, slideSpeed || speed);
  7009. move(to, 0, slideSpeed || speed);
  7010. if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
  7011. } else {
  7012. to = circle(to);
  7013. animate(index * -width, to * -width, slideSpeed || speed);
  7014. //no fallback for a circular continuous if the browser does not accept transitions
  7015. }
  7016. index = to;
  7017. offloadFn(options.callback && options.callback(index, slides[index]));
  7018. }
  7019. function move(index, dist, speed) {
  7020. translate(index, dist, speed);
  7021. slidePos[index] = dist;
  7022. }
  7023. function translate(index, dist, speed) {
  7024. var slide = slides[index];
  7025. var style = slide && slide.style;
  7026. if (!style) return;
  7027. style.webkitTransitionDuration =
  7028. style.MozTransitionDuration =
  7029. style.msTransitionDuration =
  7030. style.OTransitionDuration =
  7031. style.transitionDuration = speed + 'ms';
  7032. style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
  7033. style.msTransform =
  7034. style.MozTransform =
  7035. style.OTransform = 'translateX(' + dist + 'px)';
  7036. }
  7037. function animate(from, to, speed) {
  7038. // if not an animation, just reposition
  7039. if (!speed) {
  7040. element.style.left = to + 'px';
  7041. return;
  7042. }
  7043. var start = +new Date();
  7044. var timer = setInterval(function() {
  7045. var timeElap = +new Date() - start;
  7046. if (timeElap > speed) {
  7047. element.style.left = to + 'px';
  7048. if (delay) begin();
  7049. options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
  7050. clearInterval(timer);
  7051. return;
  7052. }
  7053. element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
  7054. }, 4);
  7055. }
  7056. // setup auto slideshow
  7057. var delay = options.auto || 0;
  7058. var interval;
  7059. function begin() {
  7060. interval = setTimeout(next, delay);
  7061. }
  7062. function stop() {
  7063. delay = options.auto || 0;
  7064. clearTimeout(interval);
  7065. }
  7066. // setup initial vars
  7067. var start = {};
  7068. var delta = {};
  7069. var isScrolling;
  7070. // setup event capturing
  7071. var events = {
  7072. handleEvent: function(event) {
  7073. if(!event.touches && event.pageX && event.pageY) {
  7074. event.touches = [{
  7075. pageX: event.pageX,
  7076. pageY: event.pageY
  7077. }];
  7078. }
  7079. switch (event.type) {
  7080. case touchStartEvent: this.start(event); break;
  7081. case mouseStartEvent: this.start(event); break;
  7082. case touchMoveEvent: this.touchmove(event); break;
  7083. case mouseMoveEvent: this.touchmove(event); break;
  7084. case touchEndEvent: offloadFn(this.end(event)); break;
  7085. case mouseEndEvent: offloadFn(this.end(event)); break;
  7086. case 'webkitTransitionEnd':
  7087. case 'msTransitionEnd':
  7088. case 'oTransitionEnd':
  7089. case 'otransitionend':
  7090. case 'transitionend': offloadFn(this.transitionEnd(event)); break;
  7091. case 'resize': offloadFn(setup); break;
  7092. }
  7093. if (options.stopPropagation) event.stopPropagation();
  7094. },
  7095. start: function(event) {
  7096. // prevent to start if there is no valid event
  7097. if (!event.touches) {
  7098. return;
  7099. }
  7100. var touches = event.touches[0];
  7101. // measure start values
  7102. start = {
  7103. // get initial touch coords
  7104. x: touches.pageX,
  7105. y: touches.pageY,
  7106. // store time to determine touch duration
  7107. time: +new Date()
  7108. };
  7109. // used for testing first move event
  7110. isScrolling = undefined;
  7111. // reset delta and end measurements
  7112. delta = {};
  7113. // attach touchmove and touchend listeners
  7114. element.addEventListener(touchMoveEvent, this, false);
  7115. element.addEventListener(mouseMoveEvent, this, false);
  7116. element.addEventListener(touchEndEvent, this, false);
  7117. element.addEventListener(mouseEndEvent, this, false);
  7118. document.addEventListener(touchEndEvent, this, false);
  7119. document.addEventListener(mouseEndEvent, this, false);
  7120. },
  7121. touchmove: function(event) {
  7122. // ensure there is a valid event
  7123. // ensure swiping with one touch and not pinching
  7124. // ensure sliding is enabled
  7125. if (!event.touches ||
  7126. event.touches.length > 1 ||
  7127. event.scale && event.scale !== 1 ||
  7128. slider.slideIsDisabled) {
  7129. return;
  7130. }
  7131. if (options.disableScroll) event.preventDefault();
  7132. var touches = event.touches[0];
  7133. // measure change in x and y
  7134. delta = {
  7135. x: touches.pageX - start.x,
  7136. y: touches.pageY - start.y
  7137. };
  7138. // determine if scrolling test has run - one time test
  7139. if ( typeof isScrolling == 'undefined') {
  7140. isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
  7141. }
  7142. // if user is not trying to scroll vertically
  7143. if (!isScrolling) {
  7144. // prevent native scrolling
  7145. event.preventDefault();
  7146. // stop slideshow
  7147. stop();
  7148. // increase resistance if first or last slide
  7149. if (options.continuous) { // we don't add resistance at the end
  7150. translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
  7151. translate(index, delta.x + slidePos[index], 0);
  7152. translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
  7153. } else {
  7154. // If the slider bounces, do the bounce!
  7155. if(options.bouncing) {
  7156. delta.x =
  7157. delta.x /
  7158. ( (!index && delta.x > 0 || // if first slide and sliding left
  7159. index == slides.length - 1 && // or if last slide and sliding right
  7160. delta.x < 0 // and if sliding at all
  7161. ) ?
  7162. ( Math.abs(delta.x) / width + 1 ) // determine resistance level
  7163. : 1 ); // no resistance if false
  7164. } else {
  7165. if(width * index - delta.x < 0) { //We are trying scroll past left boundary
  7166. delta.x = Math.min(delta.x, width * index); //Set delta.x so we don't go past left screen
  7167. }
  7168. if(Math.abs(delta.x) > width * (slides.length - index - 1)){ //We are trying to scroll past right bondary
  7169. delta.x = Math.max( -width * (slides.length - index - 1), delta.x); //Set delta.x so we don't go past right screen
  7170. }
  7171. }
  7172. // translate 1:1
  7173. translate(index - 1, delta.x + slidePos[index - 1], 0);
  7174. translate(index, delta.x + slidePos[index], 0);
  7175. translate(index + 1, delta.x + slidePos[index + 1], 0);
  7176. }
  7177. options.onDrag && options.onDrag();
  7178. }
  7179. },
  7180. end: function() {
  7181. // measure duration
  7182. var duration = +new Date() - start.time;
  7183. // determine if slide attempt triggers next/prev slide
  7184. var isValidSlide =
  7185. Number(duration) < 250 && // if slide duration is less than 250ms
  7186. Math.abs(delta.x) > 20 || // and if slide amt is greater than 20px
  7187. Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
  7188. // determine if slide attempt is past start and end
  7189. var isPastBounds = (!index && delta.x > 0) || // if first slide and slide amt is greater than 0
  7190. (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0
  7191. if (options.continuous) isPastBounds = false;
  7192. // determine direction of swipe (true:right, false:left)
  7193. var direction = delta.x < 0;
  7194. // if not scrolling vertically
  7195. if (!isScrolling) {
  7196. if (isValidSlide && !isPastBounds) {
  7197. if (direction) {
  7198. if (options.continuous) { // we need to get the next in this direction in place
  7199. move(circle(index - 1), -width, 0);
  7200. move(circle(index + 2), width, 0);
  7201. } else {
  7202. move(index - 1, -width, 0);
  7203. }
  7204. move(index, slidePos[index] - width, speed);
  7205. move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
  7206. index = circle(index + 1);
  7207. } else {
  7208. if (options.continuous) { // we need to get the next in this direction in place
  7209. move(circle(index + 1), width, 0);
  7210. move(circle(index - 2), -width, 0);
  7211. } else {
  7212. move(index + 1, width, 0);
  7213. }
  7214. move(index, slidePos[index] + width, speed);
  7215. move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
  7216. index = circle(index - 1);
  7217. }
  7218. options.callback && options.callback(index, slides[index]);
  7219. } else {
  7220. if (options.continuous) {
  7221. move(circle(index - 1), -width, speed);
  7222. move(index, 0, speed);
  7223. move(circle(index + 1), width, speed);
  7224. } else {
  7225. move(index - 1, -width, speed);
  7226. move(index, 0, speed);
  7227. move(index + 1, width, speed);
  7228. }
  7229. }
  7230. }
  7231. // kill touchmove and touchend event listeners until touchstart called again
  7232. element.removeEventListener(touchMoveEvent, events, false);
  7233. element.removeEventListener(mouseMoveEvent, events, false);
  7234. element.removeEventListener(touchEndEvent, events, false);
  7235. element.removeEventListener(mouseEndEvent, events, false);
  7236. document.removeEventListener(touchEndEvent, events, false);
  7237. document.removeEventListener(mouseEndEvent, events, false);
  7238. options.onDragEnd && options.onDragEnd();
  7239. },
  7240. transitionEnd: function(event) {
  7241. if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
  7242. if (delay) begin();
  7243. options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
  7244. }
  7245. }
  7246. };
  7247. // Public API
  7248. this.update = function() {
  7249. setTimeout(setup);
  7250. };
  7251. this.setup = function() {
  7252. setup();
  7253. };
  7254. this.loop = function(value) {
  7255. if (arguments.length) options.continuous = !!value;
  7256. return options.continuous;
  7257. };
  7258. this.enableSlide = function(shouldEnable) {
  7259. if (arguments.length) {
  7260. this.slideIsDisabled = !shouldEnable;
  7261. }
  7262. return !this.slideIsDisabled;
  7263. };
  7264. this.slide = this.select = function(to, speed) {
  7265. // cancel slideshow
  7266. stop();
  7267. slide(to, speed);
  7268. };
  7269. this.prev = this.previous = function() {
  7270. // cancel slideshow
  7271. stop();
  7272. prev();
  7273. };
  7274. this.next = function() {
  7275. // cancel slideshow
  7276. stop();
  7277. next();
  7278. };
  7279. this.stop = function() {
  7280. // cancel slideshow
  7281. stop();
  7282. };
  7283. this.start = function() {
  7284. begin();
  7285. };
  7286. this.autoPlay = function(newDelay) {
  7287. if (!delay || delay < 0) {
  7288. stop();
  7289. } else {
  7290. delay = newDelay;
  7291. begin();
  7292. }
  7293. };
  7294. this.currentIndex = this.selected = function() {
  7295. // return current index position
  7296. return index;
  7297. };
  7298. this.slidesCount = this.count = function() {
  7299. // return total number of slides
  7300. return length;
  7301. };
  7302. this.kill = function() {
  7303. // cancel slideshow
  7304. stop();
  7305. // reset element
  7306. element.style.width = '';
  7307. element.style.left = '';
  7308. // reset slides so no refs are held on to
  7309. slides && (slides = []);
  7310. // removed event listeners
  7311. if (browser.addEventListener) {
  7312. // remove current event listeners
  7313. element.removeEventListener(touchStartEvent, events, false);
  7314. element.removeEventListener(mouseStartEvent, events, false);
  7315. element.removeEventListener('webkitTransitionEnd', events, false);
  7316. element.removeEventListener('msTransitionEnd', events, false);
  7317. element.removeEventListener('oTransitionEnd', events, false);
  7318. element.removeEventListener('otransitionend', events, false);
  7319. element.removeEventListener('transitionend', events, false);
  7320. window.removeEventListener('resize', events, false);
  7321. }
  7322. else {
  7323. window.onresize = null;
  7324. }
  7325. };
  7326. this.load = function() {
  7327. // trigger setup
  7328. setup();
  7329. // start auto slideshow if applicable
  7330. if (delay) begin();
  7331. // add event listeners
  7332. if (browser.addEventListener) {
  7333. // set touchstart event on element
  7334. element.addEventListener(touchStartEvent, events, false);
  7335. element.addEventListener(mouseStartEvent, events, false);
  7336. if (browser.transitions) {
  7337. element.addEventListener('webkitTransitionEnd', events, false);
  7338. element.addEventListener('msTransitionEnd', events, false);
  7339. element.addEventListener('oTransitionEnd', events, false);
  7340. element.addEventListener('otransitionend', events, false);
  7341. element.addEventListener('transitionend', events, false);
  7342. }
  7343. // set resize event on window
  7344. window.addEventListener('resize', events, false);
  7345. } else {
  7346. window.onresize = function () { setup(); }; // to play nice with old IE
  7347. }
  7348. };
  7349. }
  7350. });
  7351. })(ionic);
  7352. /*eslint space-after-keywords: 0*/
  7353. /**
  7354. * Swiper 3.2.7
  7355. * Most modern mobile touch slider and framework with hardware accelerated transitions
  7356. *
  7357. * http://www.idangero.us/swiper/
  7358. *
  7359. * Copyright 2015, Vladimir Kharlampidi
  7360. * The iDangero.us
  7361. * http://www.idangero.us/
  7362. *
  7363. * Licensed under MIT
  7364. *
  7365. * Released on: December 7, 2015
  7366. */
  7367. (function () {
  7368. 'use strict';
  7369. var $;
  7370. /*===========================
  7371. Swiper
  7372. ===========================*/
  7373. var Swiper = function (container, params, _scope, $compile) {
  7374. if (!(this instanceof Swiper)) return new Swiper(container, params);
  7375. var defaults = {
  7376. direction: 'horizontal',
  7377. touchEventsTarget: 'container',
  7378. initialSlide: 0,
  7379. speed: 300,
  7380. // autoplay
  7381. autoplay: false,
  7382. autoplayDisableOnInteraction: true,
  7383. // To support iOS's swipe-to-go-back gesture (when being used in-app, with UIWebView).
  7384. iOSEdgeSwipeDetection: false,
  7385. iOSEdgeSwipeThreshold: 20,
  7386. // Free mode
  7387. freeMode: false,
  7388. freeModeMomentum: true,
  7389. freeModeMomentumRatio: 1,
  7390. freeModeMomentumBounce: true,
  7391. freeModeMomentumBounceRatio: 1,
  7392. freeModeSticky: false,
  7393. freeModeMinimumVelocity: 0.02,
  7394. // Autoheight
  7395. autoHeight: false,
  7396. // Set wrapper width
  7397. setWrapperSize: false,
  7398. // Virtual Translate
  7399. virtualTranslate: false,
  7400. // Effects
  7401. effect: 'slide', // 'slide' or 'fade' or 'cube' or 'coverflow'
  7402. coverflow: {
  7403. rotate: 50,
  7404. stretch: 0,
  7405. depth: 100,
  7406. modifier: 1,
  7407. slideShadows : true
  7408. },
  7409. cube: {
  7410. slideShadows: true,
  7411. shadow: true,
  7412. shadowOffset: 20,
  7413. shadowScale: 0.94
  7414. },
  7415. fade: {
  7416. crossFade: false
  7417. },
  7418. // Parallax
  7419. parallax: false,
  7420. // Scrollbar
  7421. scrollbar: null,
  7422. scrollbarHide: true,
  7423. scrollbarDraggable: false,
  7424. scrollbarSnapOnRelease: false,
  7425. // Keyboard Mousewheel
  7426. keyboardControl: false,
  7427. mousewheelControl: false,
  7428. mousewheelReleaseOnEdges: false,
  7429. mousewheelInvert: false,
  7430. mousewheelForceToAxis: false,
  7431. mousewheelSensitivity: 1,
  7432. // Hash Navigation
  7433. hashnav: false,
  7434. // Breakpoints
  7435. breakpoints: undefined,
  7436. // Slides grid
  7437. spaceBetween: 0,
  7438. slidesPerView: 1,
  7439. slidesPerColumn: 1,
  7440. slidesPerColumnFill: 'column',
  7441. slidesPerGroup: 1,
  7442. centeredSlides: false,
  7443. slidesOffsetBefore: 0, // in px
  7444. slidesOffsetAfter: 0, // in px
  7445. // Round length
  7446. roundLengths: false,
  7447. // Touches
  7448. touchRatio: 1,
  7449. touchAngle: 45,
  7450. simulateTouch: true,
  7451. shortSwipes: true,
  7452. longSwipes: true,
  7453. longSwipesRatio: 0.5,
  7454. longSwipesMs: 300,
  7455. followFinger: true,
  7456. onlyExternal: false,
  7457. threshold: 0,
  7458. touchMoveStopPropagation: true,
  7459. // Pagination
  7460. pagination: null,
  7461. paginationElement: 'span',
  7462. paginationClickable: false,
  7463. paginationHide: false,
  7464. paginationBulletRender: null,
  7465. // Resistance
  7466. resistance: true,
  7467. resistanceRatio: 0.85,
  7468. // Next/prev buttons
  7469. nextButton: null,
  7470. prevButton: null,
  7471. // Progress
  7472. watchSlidesProgress: false,
  7473. watchSlidesVisibility: false,
  7474. // Cursor
  7475. grabCursor: false,
  7476. // Clicks
  7477. preventClicks: true,
  7478. preventClicksPropagation: true,
  7479. slideToClickedSlide: false,
  7480. // Lazy Loading
  7481. lazyLoading: false,
  7482. lazyLoadingInPrevNext: false,
  7483. lazyLoadingOnTransitionStart: false,
  7484. // Images
  7485. preloadImages: true,
  7486. updateOnImagesReady: true,
  7487. // loop
  7488. loop: false,
  7489. loopAdditionalSlides: 0,
  7490. loopedSlides: null,
  7491. // Control
  7492. control: undefined,
  7493. controlInverse: false,
  7494. controlBy: 'slide', //or 'container'
  7495. // Swiping/no swiping
  7496. allowSwipeToPrev: true,
  7497. allowSwipeToNext: true,
  7498. swipeHandler: null, //'.swipe-handler',
  7499. noSwiping: true,
  7500. noSwipingClass: 'swiper-no-swiping',
  7501. // NS
  7502. slideClass: 'swiper-slide',
  7503. slideActiveClass: 'swiper-slide-active',
  7504. slideVisibleClass: 'swiper-slide-visible',
  7505. slideDuplicateClass: 'swiper-slide-duplicate',
  7506. slideNextClass: 'swiper-slide-next',
  7507. slidePrevClass: 'swiper-slide-prev',
  7508. wrapperClass: 'swiper-wrapper',
  7509. bulletClass: 'swiper-pagination-bullet',
  7510. bulletActiveClass: 'swiper-pagination-bullet-active',
  7511. buttonDisabledClass: 'swiper-button-disabled',
  7512. paginationHiddenClass: 'swiper-pagination-hidden',
  7513. // Observer
  7514. observer: false,
  7515. observeParents: false,
  7516. // Accessibility
  7517. a11y: false,
  7518. prevSlideMessage: 'Previous slide',
  7519. nextSlideMessage: 'Next slide',
  7520. firstSlideMessage: 'This is the first slide',
  7521. lastSlideMessage: 'This is the last slide',
  7522. paginationBulletMessage: 'Go to slide {{index}}',
  7523. // Callbacks
  7524. runCallbacksOnInit: true
  7525. /*
  7526. Callbacks:
  7527. onInit: function (swiper)
  7528. onDestroy: function (swiper)
  7529. onClick: function (swiper, e)
  7530. onTap: function (swiper, e)
  7531. onDoubleTap: function (swiper, e)
  7532. onSliderMove: function (swiper, e)
  7533. onSlideChangeStart: function (swiper)
  7534. onSlideChangeEnd: function (swiper)
  7535. onTransitionStart: function (swiper)
  7536. onTransitionEnd: function (swiper)
  7537. onImagesReady: function (swiper)
  7538. onProgress: function (swiper, progress)
  7539. onTouchStart: function (swiper, e)
  7540. onTouchMove: function (swiper, e)
  7541. onTouchMoveOpposite: function (swiper, e)
  7542. onTouchEnd: function (swiper, e)
  7543. onReachBeginning: function (swiper)
  7544. onReachEnd: function (swiper)
  7545. onSetTransition: function (swiper, duration)
  7546. onSetTranslate: function (swiper, translate)
  7547. onAutoplayStart: function (swiper)
  7548. onAutoplayStop: function (swiper),
  7549. onLazyImageLoad: function (swiper, slide, image)
  7550. onLazyImageReady: function (swiper, slide, image)
  7551. */
  7552. };
  7553. var initialVirtualTranslate = params && params.virtualTranslate;
  7554. params = params || {};
  7555. var originalParams = {};
  7556. for (var param in params) {
  7557. if (typeof params[param] === 'object' && !(params[param].nodeType || params[param] === window || params[param] === document || (typeof Dom7 !== 'undefined' && params[param] instanceof Dom7) || (typeof jQuery !== 'undefined' && params[param] instanceof jQuery))) {
  7558. originalParams[param] = {};
  7559. for (var deepParam in params[param]) {
  7560. originalParams[param][deepParam] = params[param][deepParam];
  7561. }
  7562. }
  7563. else {
  7564. originalParams[param] = params[param];
  7565. }
  7566. }
  7567. for (var def in defaults) {
  7568. if (typeof params[def] === 'undefined') {
  7569. params[def] = defaults[def];
  7570. }
  7571. else if (typeof params[def] === 'object') {
  7572. for (var deepDef in defaults[def]) {
  7573. if (typeof params[def][deepDef] === 'undefined') {
  7574. params[def][deepDef] = defaults[def][deepDef];
  7575. }
  7576. }
  7577. }
  7578. }
  7579. // Swiper
  7580. var s = this;
  7581. // Params
  7582. s.params = params;
  7583. s.originalParams = originalParams;
  7584. // Classname
  7585. s.classNames = [];
  7586. /*=========================
  7587. Dom Library and plugins
  7588. ===========================*/
  7589. if (typeof $ !== 'undefined' && typeof Dom7 !== 'undefined'){
  7590. $ = Dom7;
  7591. }
  7592. if (typeof $ === 'undefined') {
  7593. if (typeof Dom7 === 'undefined') {
  7594. $ = window.Dom7 || window.Zepto || window.jQuery;
  7595. }
  7596. else {
  7597. $ = Dom7;
  7598. }
  7599. if (!$) return;
  7600. }
  7601. // Export it to Swiper instance
  7602. s.$ = $;
  7603. /*=========================
  7604. Breakpoints
  7605. ===========================*/
  7606. s.currentBreakpoint = undefined;
  7607. s.getActiveBreakpoint = function () {
  7608. //Get breakpoint for window width
  7609. if (!s.params.breakpoints) return false;
  7610. var breakpoint = false;
  7611. var points = [], point;
  7612. for ( point in s.params.breakpoints ) {
  7613. if (s.params.breakpoints.hasOwnProperty(point)) {
  7614. points.push(point);
  7615. }
  7616. }
  7617. points.sort(function (a, b) {
  7618. return parseInt(a, 10) > parseInt(b, 10);
  7619. });
  7620. for (var i = 0; i < points.length; i++) {
  7621. point = points[i];
  7622. if (point >= window.innerWidth && !breakpoint) {
  7623. breakpoint = point;
  7624. }
  7625. }
  7626. return breakpoint || 'max';
  7627. };
  7628. s.setBreakpoint = function () {
  7629. //Set breakpoint for window width and update parameters
  7630. var breakpoint = s.getActiveBreakpoint();
  7631. if (breakpoint && s.currentBreakpoint !== breakpoint) {
  7632. var breakPointsParams = breakpoint in s.params.breakpoints ? s.params.breakpoints[breakpoint] : s.originalParams;
  7633. for ( var param in breakPointsParams ) {
  7634. s.params[param] = breakPointsParams[param];
  7635. }
  7636. s.currentBreakpoint = breakpoint;
  7637. }
  7638. };
  7639. // Set breakpoint on load
  7640. if (s.params.breakpoints) {
  7641. s.setBreakpoint();
  7642. }
  7643. /*=========================
  7644. Preparation - Define Container, Wrapper and Pagination
  7645. ===========================*/
  7646. s.container = $(container);
  7647. if (s.container.length === 0) return;
  7648. if (s.container.length > 1) {
  7649. s.container.each(function () {
  7650. new Swiper(this, params);
  7651. });
  7652. return;
  7653. }
  7654. // Save instance in container HTML Element and in data
  7655. s.container[0].swiper = s;
  7656. s.container.data('swiper', s);
  7657. s.classNames.push('swiper-container-' + s.params.direction);
  7658. if (s.params.freeMode) {
  7659. s.classNames.push('swiper-container-free-mode');
  7660. }
  7661. if (!s.support.flexbox) {
  7662. s.classNames.push('swiper-container-no-flexbox');
  7663. s.params.slidesPerColumn = 1;
  7664. }
  7665. if (s.params.autoHeight) {
  7666. s.classNames.push('swiper-container-autoheight');
  7667. }
  7668. // Enable slides progress when required
  7669. if (s.params.parallax || s.params.watchSlidesVisibility) {
  7670. s.params.watchSlidesProgress = true;
  7671. }
  7672. // Coverflow / 3D
  7673. if (['cube', 'coverflow'].indexOf(s.params.effect) >= 0) {
  7674. if (s.support.transforms3d) {
  7675. s.params.watchSlidesProgress = true;
  7676. s.classNames.push('swiper-container-3d');
  7677. }
  7678. else {
  7679. s.params.effect = 'slide';
  7680. }
  7681. }
  7682. if (s.params.effect !== 'slide') {
  7683. s.classNames.push('swiper-container-' + s.params.effect);
  7684. }
  7685. if (s.params.effect === 'cube') {
  7686. s.params.resistanceRatio = 0;
  7687. s.params.slidesPerView = 1;
  7688. s.params.slidesPerColumn = 1;
  7689. s.params.slidesPerGroup = 1;
  7690. s.params.centeredSlides = false;
  7691. s.params.spaceBetween = 0;
  7692. s.params.virtualTranslate = true;
  7693. s.params.setWrapperSize = false;
  7694. }
  7695. if (s.params.effect === 'fade') {
  7696. s.params.slidesPerView = 1;
  7697. s.params.slidesPerColumn = 1;
  7698. s.params.slidesPerGroup = 1;
  7699. s.params.watchSlidesProgress = true;
  7700. s.params.spaceBetween = 0;
  7701. if (typeof initialVirtualTranslate === 'undefined') {
  7702. s.params.virtualTranslate = true;
  7703. }
  7704. }
  7705. // Grab Cursor
  7706. if (s.params.grabCursor && s.support.touch) {
  7707. s.params.grabCursor = false;
  7708. }
  7709. // Wrapper
  7710. s.wrapper = s.container.children('.' + s.params.wrapperClass);
  7711. // Pagination
  7712. if (s.params.pagination) {
  7713. s.paginationContainer = $(s.params.pagination);
  7714. if (s.params.paginationClickable) {
  7715. s.paginationContainer.addClass('swiper-pagination-clickable');
  7716. }
  7717. }
  7718. // Is Horizontal
  7719. function isH() {
  7720. return s.params.direction === 'horizontal';
  7721. }
  7722. // RTL
  7723. s.rtl = isH() && (s.container[0].dir.toLowerCase() === 'rtl' || s.container.css('direction') === 'rtl');
  7724. if (s.rtl) {
  7725. s.classNames.push('swiper-container-rtl');
  7726. }
  7727. // Wrong RTL support
  7728. if (s.rtl) {
  7729. s.wrongRTL = s.wrapper.css('display') === '-webkit-box';
  7730. }
  7731. // Columns
  7732. if (s.params.slidesPerColumn > 1) {
  7733. s.classNames.push('swiper-container-multirow');
  7734. }
  7735. // Check for Android
  7736. if (s.device.android) {
  7737. s.classNames.push('swiper-container-android');
  7738. }
  7739. // Add classes
  7740. s.container.addClass(s.classNames.join(' '));
  7741. // Translate
  7742. s.translate = 0;
  7743. // Progress
  7744. s.progress = 0;
  7745. // Velocity
  7746. s.velocity = 0;
  7747. /*=========================
  7748. Locks, unlocks
  7749. ===========================*/
  7750. s.lockSwipeToNext = function () {
  7751. s.params.allowSwipeToNext = false;
  7752. };
  7753. s.lockSwipeToPrev = function () {
  7754. s.params.allowSwipeToPrev = false;
  7755. };
  7756. s.lockSwipes = function () {
  7757. s.params.allowSwipeToNext = s.params.allowSwipeToPrev = false;
  7758. };
  7759. s.unlockSwipeToNext = function () {
  7760. s.params.allowSwipeToNext = true;
  7761. };
  7762. s.unlockSwipeToPrev = function () {
  7763. s.params.allowSwipeToPrev = true;
  7764. };
  7765. s.unlockSwipes = function () {
  7766. s.params.allowSwipeToNext = s.params.allowSwipeToPrev = true;
  7767. };
  7768. /*=========================
  7769. Round helper
  7770. ===========================*/
  7771. function round(a) {
  7772. return Math.floor(a);
  7773. }
  7774. /*=========================
  7775. Set grab cursor
  7776. ===========================*/
  7777. if (s.params.grabCursor) {
  7778. s.container[0].style.cursor = 'move';
  7779. s.container[0].style.cursor = '-webkit-grab';
  7780. s.container[0].style.cursor = '-moz-grab';
  7781. s.container[0].style.cursor = 'grab';
  7782. }
  7783. /*=========================
  7784. Update on Images Ready
  7785. ===========================*/
  7786. s.imagesToLoad = [];
  7787. s.imagesLoaded = 0;
  7788. s.loadImage = function (imgElement, src, srcset, checkForComplete, callback) {
  7789. var image;
  7790. function onReady () {
  7791. if (callback) callback();
  7792. }
  7793. if (!imgElement.complete || !checkForComplete) {
  7794. if (src) {
  7795. image = new window.Image();
  7796. image.onload = onReady;
  7797. image.onerror = onReady;
  7798. if (srcset) {
  7799. image.srcset = srcset;
  7800. }
  7801. if (src) {
  7802. image.src = src;
  7803. }
  7804. } else {
  7805. onReady();
  7806. }
  7807. } else {//image already loaded...
  7808. onReady();
  7809. }
  7810. };
  7811. s.preloadImages = function () {
  7812. s.imagesToLoad = s.container.find('img');
  7813. function _onReady() {
  7814. if (typeof s === 'undefined' || s === null) return;
  7815. if (s.imagesLoaded !== undefined) s.imagesLoaded++;
  7816. if (s.imagesLoaded === s.imagesToLoad.length) {
  7817. if (s.params.updateOnImagesReady) s.update();
  7818. s.emit('onImagesReady', s);
  7819. }
  7820. }
  7821. for (var i = 0; i < s.imagesToLoad.length; i++) {
  7822. s.loadImage(s.imagesToLoad[i], (s.imagesToLoad[i].currentSrc || s.imagesToLoad[i].getAttribute('src')), (s.imagesToLoad[i].srcset || s.imagesToLoad[i].getAttribute('srcset')), true, _onReady);
  7823. }
  7824. };
  7825. /*=========================
  7826. Autoplay
  7827. ===========================*/
  7828. s.autoplayTimeoutId = undefined;
  7829. s.autoplaying = false;
  7830. s.autoplayPaused = false;
  7831. function autoplay() {
  7832. s.autoplayTimeoutId = setTimeout(function () {
  7833. if (s.params.loop) {
  7834. s.fixLoop();
  7835. s._slideNext();
  7836. }
  7837. else {
  7838. if (!s.isEnd) {
  7839. s._slideNext();
  7840. }
  7841. else {
  7842. if (!params.autoplayStopOnLast) {
  7843. s._slideTo(0);
  7844. }
  7845. else {
  7846. s.stopAutoplay();
  7847. }
  7848. }
  7849. }
  7850. }, s.params.autoplay);
  7851. }
  7852. s.startAutoplay = function () {
  7853. if (typeof s.autoplayTimeoutId !== 'undefined') return false;
  7854. if (!s.params.autoplay) return false;
  7855. if (s.autoplaying) return false;
  7856. s.autoplaying = true;
  7857. s.emit('onAutoplayStart', s);
  7858. autoplay();
  7859. };
  7860. s.stopAutoplay = function (internal) {
  7861. if (!s.autoplayTimeoutId) return;
  7862. if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId);
  7863. s.autoplaying = false;
  7864. s.autoplayTimeoutId = undefined;
  7865. s.emit('onAutoplayStop', s);
  7866. };
  7867. s.pauseAutoplay = function (speed) {
  7868. if (s.autoplayPaused) return;
  7869. if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId);
  7870. s.autoplayPaused = true;
  7871. if (speed === 0) {
  7872. s.autoplayPaused = false;
  7873. autoplay();
  7874. }
  7875. else {
  7876. s.wrapper.transitionEnd(function () {
  7877. if (!s) return;
  7878. s.autoplayPaused = false;
  7879. if (!s.autoplaying) {
  7880. s.stopAutoplay();
  7881. }
  7882. else {
  7883. autoplay();
  7884. }
  7885. });
  7886. }
  7887. };
  7888. /*=========================
  7889. Min/Max Translate
  7890. ===========================*/
  7891. s.minTranslate = function () {
  7892. return (-s.snapGrid[0]);
  7893. };
  7894. s.maxTranslate = function () {
  7895. return (-s.snapGrid[s.snapGrid.length - 1]);
  7896. };
  7897. /*=========================
  7898. Slider/slides sizes
  7899. ===========================*/
  7900. s.updateAutoHeight = function () {
  7901. // Update Height
  7902. var newHeight = s.slides.eq(s.activeIndex)[0].offsetHeight;
  7903. if (newHeight) s.wrapper.css('height', s.slides.eq(s.activeIndex)[0].offsetHeight + 'px');
  7904. };
  7905. s.updateContainerSize = function () {
  7906. var width, height;
  7907. if (typeof s.params.width !== 'undefined') {
  7908. width = s.params.width;
  7909. }
  7910. else {
  7911. width = s.container[0].clientWidth;
  7912. }
  7913. if (typeof s.params.height !== 'undefined') {
  7914. height = s.params.height;
  7915. }
  7916. else {
  7917. height = s.container[0].clientHeight;
  7918. }
  7919. if (width === 0 && isH() || height === 0 && !isH()) {
  7920. return;
  7921. }
  7922. //Subtract paddings
  7923. width = width - parseInt(s.container.css('padding-left'), 10) - parseInt(s.container.css('padding-right'), 10);
  7924. height = height - parseInt(s.container.css('padding-top'), 10) - parseInt(s.container.css('padding-bottom'), 10);
  7925. // Store values
  7926. s.width = width;
  7927. s.height = height;
  7928. s.size = isH() ? s.width : s.height;
  7929. };
  7930. s.updateSlidesSize = function () {
  7931. s.slides = s.wrapper.children('.' + s.params.slideClass);
  7932. s.snapGrid = [];
  7933. s.slidesGrid = [];
  7934. s.slidesSizesGrid = [];
  7935. var spaceBetween = s.params.spaceBetween,
  7936. slidePosition = -s.params.slidesOffsetBefore,
  7937. i,
  7938. prevSlideSize = 0,
  7939. index = 0;
  7940. if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
  7941. spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * s.size;
  7942. }
  7943. s.virtualSize = -spaceBetween;
  7944. // reset margins
  7945. if (s.rtl) s.slides.css({marginLeft: '', marginTop: ''});
  7946. else s.slides.css({marginRight: '', marginBottom: ''});
  7947. var slidesNumberEvenToRows;
  7948. if (s.params.slidesPerColumn > 1) {
  7949. if (Math.floor(s.slides.length / s.params.slidesPerColumn) === s.slides.length / s.params.slidesPerColumn) {
  7950. slidesNumberEvenToRows = s.slides.length;
  7951. }
  7952. else {
  7953. slidesNumberEvenToRows = Math.ceil(s.slides.length / s.params.slidesPerColumn) * s.params.slidesPerColumn;
  7954. }
  7955. if (s.params.slidesPerView !== 'auto' && s.params.slidesPerColumnFill === 'row') {
  7956. slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, s.params.slidesPerView * s.params.slidesPerColumn);
  7957. }
  7958. }
  7959. // Calc slides
  7960. var slideSize;
  7961. var slidesPerColumn = s.params.slidesPerColumn;
  7962. var slidesPerRow = slidesNumberEvenToRows / slidesPerColumn;
  7963. var numFullColumns = slidesPerRow - (s.params.slidesPerColumn * slidesPerRow - s.slides.length);
  7964. for (i = 0; i < s.slides.length; i++) {
  7965. slideSize = 0;
  7966. var slide = s.slides.eq(i);
  7967. if (s.params.slidesPerColumn > 1) {
  7968. // Set slides order
  7969. var newSlideOrderIndex;
  7970. var column, row;
  7971. if (s.params.slidesPerColumnFill === 'column') {
  7972. column = Math.floor(i / slidesPerColumn);
  7973. row = i - column * slidesPerColumn;
  7974. if (column > numFullColumns || (column === numFullColumns && row === slidesPerColumn-1)) {
  7975. if (++row >= slidesPerColumn) {
  7976. row = 0;
  7977. column++;
  7978. }
  7979. }
  7980. newSlideOrderIndex = column + row * slidesNumberEvenToRows / slidesPerColumn;
  7981. slide
  7982. .css({
  7983. '-webkit-box-ordinal-group': newSlideOrderIndex,
  7984. '-moz-box-ordinal-group': newSlideOrderIndex,
  7985. '-ms-flex-order': newSlideOrderIndex,
  7986. '-webkit-order': newSlideOrderIndex,
  7987. 'order': newSlideOrderIndex
  7988. });
  7989. }
  7990. else {
  7991. row = Math.floor(i / slidesPerRow);
  7992. column = i - row * slidesPerRow;
  7993. }
  7994. slide
  7995. .css({
  7996. 'margin-top': (row !== 0 && s.params.spaceBetween) && (s.params.spaceBetween + 'px')
  7997. })
  7998. .attr('data-swiper-column', column)
  7999. .attr('data-swiper-row', row);
  8000. }
  8001. if (slide.css('display') === 'none') continue;
  8002. if (s.params.slidesPerView === 'auto') {
  8003. slideSize = isH() ? slide.outerWidth(true) : slide.outerHeight(true);
  8004. if (s.params.roundLengths) slideSize = round(slideSize);
  8005. }
  8006. else {
  8007. slideSize = (s.size - (s.params.slidesPerView - 1) * spaceBetween) / s.params.slidesPerView;
  8008. if (s.params.roundLengths) slideSize = round(slideSize);
  8009. if (isH()) {
  8010. s.slides[i].style.width = slideSize + 'px';
  8011. }
  8012. else {
  8013. s.slides[i].style.height = slideSize + 'px';
  8014. }
  8015. }
  8016. s.slides[i].swiperSlideSize = slideSize;
  8017. s.slidesSizesGrid.push(slideSize);
  8018. if (s.params.centeredSlides) {
  8019. slidePosition = slidePosition + slideSize / 2 + prevSlideSize / 2 + spaceBetween;
  8020. if (i === 0) slidePosition = slidePosition - s.size / 2 - spaceBetween;
  8021. if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0;
  8022. if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition);
  8023. s.slidesGrid.push(slidePosition);
  8024. }
  8025. else {
  8026. if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition);
  8027. s.slidesGrid.push(slidePosition);
  8028. slidePosition = slidePosition + slideSize + spaceBetween;
  8029. }
  8030. s.virtualSize += slideSize + spaceBetween;
  8031. prevSlideSize = slideSize;
  8032. index ++;
  8033. }
  8034. s.virtualSize = Math.max(s.virtualSize, s.size) + s.params.slidesOffsetAfter;
  8035. var newSlidesGrid;
  8036. if (
  8037. s.rtl && s.wrongRTL && (s.params.effect === 'slide' || s.params.effect === 'coverflow')) {
  8038. s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8039. }
  8040. if (!s.support.flexbox || s.params.setWrapperSize) {
  8041. if (isH()) s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8042. else s.wrapper.css({height: s.virtualSize + s.params.spaceBetween + 'px'});
  8043. }
  8044. if (s.params.slidesPerColumn > 1) {
  8045. s.virtualSize = (slideSize + s.params.spaceBetween) * slidesNumberEvenToRows;
  8046. s.virtualSize = Math.ceil(s.virtualSize / s.params.slidesPerColumn) - s.params.spaceBetween;
  8047. s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8048. if (s.params.centeredSlides) {
  8049. newSlidesGrid = [];
  8050. for (i = 0; i < s.snapGrid.length; i++) {
  8051. if (s.snapGrid[i] < s.virtualSize + s.snapGrid[0]) newSlidesGrid.push(s.snapGrid[i]);
  8052. }
  8053. s.snapGrid = newSlidesGrid;
  8054. }
  8055. }
  8056. // Remove last grid elements depending on width
  8057. if (!s.params.centeredSlides) {
  8058. newSlidesGrid = [];
  8059. for (i = 0; i < s.snapGrid.length; i++) {
  8060. if (s.snapGrid[i] <= s.virtualSize - s.size) {
  8061. newSlidesGrid.push(s.snapGrid[i]);
  8062. }
  8063. }
  8064. s.snapGrid = newSlidesGrid;
  8065. if (Math.floor(s.virtualSize - s.size) > Math.floor(s.snapGrid[s.snapGrid.length - 1])) {
  8066. s.snapGrid.push(s.virtualSize - s.size);
  8067. }
  8068. }
  8069. if (s.snapGrid.length === 0) s.snapGrid = [0];
  8070. if (s.params.spaceBetween !== 0) {
  8071. if (isH()) {
  8072. if (s.rtl) s.slides.css({marginLeft: spaceBetween + 'px'});
  8073. else s.slides.css({marginRight: spaceBetween + 'px'});
  8074. }
  8075. else s.slides.css({marginBottom: spaceBetween + 'px'});
  8076. }
  8077. if (s.params.watchSlidesProgress) {
  8078. s.updateSlidesOffset();
  8079. }
  8080. };
  8081. s.updateSlidesOffset = function () {
  8082. for (var i = 0; i < s.slides.length; i++) {
  8083. s.slides[i].swiperSlideOffset = isH() ? s.slides[i].offsetLeft : s.slides[i].offsetTop;
  8084. }
  8085. };
  8086. /*=========================
  8087. Slider/slides progress
  8088. ===========================*/
  8089. s.updateSlidesProgress = function (translate) {
  8090. if (typeof translate === 'undefined') {
  8091. translate = s.translate || 0;
  8092. }
  8093. if (s.slides.length === 0) return;
  8094. if (typeof s.slides[0].swiperSlideOffset === 'undefined') s.updateSlidesOffset();
  8095. var offsetCenter = -translate;
  8096. if (s.rtl) offsetCenter = translate;
  8097. // Visible Slides
  8098. s.slides.removeClass(s.params.slideVisibleClass);
  8099. for (var i = 0; i < s.slides.length; i++) {
  8100. var slide = s.slides[i];
  8101. var slideProgress = (offsetCenter - slide.swiperSlideOffset) / (slide.swiperSlideSize + s.params.spaceBetween);
  8102. if (s.params.watchSlidesVisibility) {
  8103. var slideBefore = -(offsetCenter - slide.swiperSlideOffset);
  8104. var slideAfter = slideBefore + s.slidesSizesGrid[i];
  8105. var isVisible =
  8106. (slideBefore >= 0 && slideBefore < s.size) ||
  8107. (slideAfter > 0 && slideAfter <= s.size) ||
  8108. (slideBefore <= 0 && slideAfter >= s.size);
  8109. if (isVisible) {
  8110. s.slides.eq(i).addClass(s.params.slideVisibleClass);
  8111. }
  8112. }
  8113. slide.progress = s.rtl ? -slideProgress : slideProgress;
  8114. }
  8115. };
  8116. s.updateProgress = function (translate) {
  8117. if (typeof translate === 'undefined') {
  8118. translate = s.translate || 0;
  8119. }
  8120. var translatesDiff = s.maxTranslate() - s.minTranslate();
  8121. var wasBeginning = s.isBeginning;
  8122. var wasEnd = s.isEnd;
  8123. if (translatesDiff === 0) {
  8124. s.progress = 0;
  8125. s.isBeginning = s.isEnd = true;
  8126. }
  8127. else {
  8128. s.progress = (translate - s.minTranslate()) / (translatesDiff);
  8129. s.isBeginning = s.progress <= 0;
  8130. s.isEnd = s.progress >= 1;
  8131. }
  8132. if (s.isBeginning && !wasBeginning) s.emit('onReachBeginning', s);
  8133. if (s.isEnd && !wasEnd) s.emit('onReachEnd', s);
  8134. if (s.params.watchSlidesProgress) s.updateSlidesProgress(translate);
  8135. s.emit('onProgress', s, s.progress);
  8136. };
  8137. s.updateActiveIndex = function () {
  8138. var translate = s.rtl ? s.translate : -s.translate;
  8139. var newActiveIndex, i, snapIndex;
  8140. for (i = 0; i < s.slidesGrid.length; i ++) {
  8141. if (typeof s.slidesGrid[i + 1] !== 'undefined') {
  8142. if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1] - (s.slidesGrid[i + 1] - s.slidesGrid[i]) / 2) {
  8143. newActiveIndex = i;
  8144. }
  8145. else if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1]) {
  8146. newActiveIndex = i + 1;
  8147. }
  8148. }
  8149. else {
  8150. if (translate >= s.slidesGrid[i]) {
  8151. newActiveIndex = i;
  8152. }
  8153. }
  8154. }
  8155. // Normalize slideIndex
  8156. if (newActiveIndex < 0 || typeof newActiveIndex === 'undefined') newActiveIndex = 0;
  8157. // for (i = 0; i < s.slidesGrid.length; i++) {
  8158. // if (- translate >= s.slidesGrid[i]) {
  8159. // newActiveIndex = i;
  8160. // }
  8161. // }
  8162. snapIndex = Math.floor(newActiveIndex / s.params.slidesPerGroup);
  8163. if (snapIndex >= s.snapGrid.length) snapIndex = s.snapGrid.length - 1;
  8164. if (newActiveIndex === s.activeIndex) {
  8165. return;
  8166. }
  8167. s.snapIndex = snapIndex;
  8168. s.previousIndex = s.activeIndex;
  8169. s.activeIndex = newActiveIndex;
  8170. s.updateClasses();
  8171. };
  8172. /*=========================
  8173. Classes
  8174. ===========================*/
  8175. s.updateClasses = function () {
  8176. s.slides.removeClass(s.params.slideActiveClass + ' ' + s.params.slideNextClass + ' ' + s.params.slidePrevClass);
  8177. var activeSlide = s.slides.eq(s.activeIndex);
  8178. // Active classes
  8179. activeSlide.addClass(s.params.slideActiveClass);
  8180. activeSlide.next('.' + s.params.slideClass).addClass(s.params.slideNextClass);
  8181. activeSlide.prev('.' + s.params.slideClass).addClass(s.params.slidePrevClass);
  8182. // Pagination
  8183. if (s.bullets && s.bullets.length > 0) {
  8184. s.bullets.removeClass(s.params.bulletActiveClass);
  8185. var bulletIndex;
  8186. if (s.params.loop) {
  8187. bulletIndex = Math.ceil(s.activeIndex - s.loopedSlides)/s.params.slidesPerGroup;
  8188. if (bulletIndex > s.slides.length - 1 - s.loopedSlides * 2) {
  8189. bulletIndex = bulletIndex - (s.slides.length - s.loopedSlides * 2);
  8190. }
  8191. if (bulletIndex > s.bullets.length - 1) bulletIndex = bulletIndex - s.bullets.length;
  8192. }
  8193. else {
  8194. if (typeof s.snapIndex !== 'undefined') {
  8195. bulletIndex = s.snapIndex;
  8196. }
  8197. else {
  8198. bulletIndex = s.activeIndex || 0;
  8199. }
  8200. }
  8201. if (s.paginationContainer.length > 1) {
  8202. s.bullets.each(function () {
  8203. if ($(this).index() === bulletIndex) $(this).addClass(s.params.bulletActiveClass);
  8204. });
  8205. }
  8206. else {
  8207. s.bullets.eq(bulletIndex).addClass(s.params.bulletActiveClass);
  8208. }
  8209. }
  8210. // Next/active buttons
  8211. if (!s.params.loop) {
  8212. if (s.params.prevButton) {
  8213. if (s.isBeginning) {
  8214. $(s.params.prevButton).addClass(s.params.buttonDisabledClass);
  8215. if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.prevButton));
  8216. }
  8217. else {
  8218. $(s.params.prevButton).removeClass(s.params.buttonDisabledClass);
  8219. if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.prevButton));
  8220. }
  8221. }
  8222. if (s.params.nextButton) {
  8223. if (s.isEnd) {
  8224. $(s.params.nextButton).addClass(s.params.buttonDisabledClass);
  8225. if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.nextButton));
  8226. }
  8227. else {
  8228. $(s.params.nextButton).removeClass(s.params.buttonDisabledClass);
  8229. if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.nextButton));
  8230. }
  8231. }
  8232. }
  8233. };
  8234. /*=========================
  8235. Pagination
  8236. ===========================*/
  8237. s.updatePagination = function () {
  8238. if (!s.params.pagination) return;
  8239. if (s.paginationContainer && s.paginationContainer.length > 0) {
  8240. var bulletsHTML = '';
  8241. var numberOfBullets = s.params.loop ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup) : s.snapGrid.length;
  8242. for (var i = 0; i < numberOfBullets; i++) {
  8243. if (s.params.paginationBulletRender) {
  8244. bulletsHTML += s.params.paginationBulletRender(i, s.params.bulletClass);
  8245. }
  8246. else {
  8247. bulletsHTML += '<' + s.params.paginationElement+' class="' + s.params.bulletClass + '"></' + s.params.paginationElement + '>';
  8248. }
  8249. }
  8250. s.paginationContainer.html(bulletsHTML);
  8251. s.bullets = s.paginationContainer.find('.' + s.params.bulletClass);
  8252. if (s.params.paginationClickable && s.params.a11y && s.a11y) {
  8253. s.a11y.initPagination();
  8254. }
  8255. }
  8256. };
  8257. /*=========================
  8258. Common update method
  8259. ===========================*/
  8260. s.update = function (updateTranslate) {
  8261. s.updateContainerSize();
  8262. s.updateSlidesSize();
  8263. s.updateProgress();
  8264. s.updatePagination();
  8265. s.updateClasses();
  8266. if (s.params.scrollbar && s.scrollbar) {
  8267. s.scrollbar.set();
  8268. }
  8269. function forceSetTranslate() {
  8270. newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate());
  8271. s.setWrapperTranslate(newTranslate);
  8272. s.updateActiveIndex();
  8273. s.updateClasses();
  8274. }
  8275. if (updateTranslate) {
  8276. var translated, newTranslate;
  8277. if (s.controller && s.controller.spline) {
  8278. s.controller.spline = undefined;
  8279. }
  8280. if (s.params.freeMode) {
  8281. forceSetTranslate();
  8282. if (s.params.autoHeight) {
  8283. s.updateAutoHeight();
  8284. }
  8285. }
  8286. else {
  8287. if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) {
  8288. translated = s.slideTo(s.slides.length - 1, 0, false, true);
  8289. }
  8290. else {
  8291. translated = s.slideTo(s.activeIndex, 0, false, true);
  8292. }
  8293. if (!translated) {
  8294. forceSetTranslate();
  8295. }
  8296. }
  8297. }
  8298. else if (s.params.autoHeight) {
  8299. s.updateAutoHeight();
  8300. }
  8301. };
  8302. /*=========================
  8303. Resize Handler
  8304. ===========================*/
  8305. s.onResize = function (forceUpdatePagination) {
  8306. //Breakpoints
  8307. if (s.params.breakpoints) {
  8308. s.setBreakpoint();
  8309. }
  8310. // Disable locks on resize
  8311. var allowSwipeToPrev = s.params.allowSwipeToPrev;
  8312. var allowSwipeToNext = s.params.allowSwipeToNext;
  8313. s.params.allowSwipeToPrev = s.params.allowSwipeToNext = true;
  8314. s.updateContainerSize();
  8315. s.updateSlidesSize();
  8316. if (s.params.slidesPerView === 'auto' || s.params.freeMode || forceUpdatePagination) s.updatePagination();
  8317. if (s.params.scrollbar && s.scrollbar) {
  8318. s.scrollbar.set();
  8319. }
  8320. if (s.controller && s.controller.spline) {
  8321. s.controller.spline = undefined;
  8322. }
  8323. if (s.params.freeMode) {
  8324. var newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate());
  8325. s.setWrapperTranslate(newTranslate);
  8326. s.updateActiveIndex();
  8327. s.updateClasses();
  8328. if (s.params.autoHeight) {
  8329. s.updateAutoHeight();
  8330. }
  8331. }
  8332. else {
  8333. s.updateClasses();
  8334. if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) {
  8335. s.slideTo(s.slides.length - 1, 0, false, true);
  8336. }
  8337. else {
  8338. s.slideTo(s.activeIndex, 0, false, true);
  8339. }
  8340. }
  8341. // Return locks after resize
  8342. s.params.allowSwipeToPrev = allowSwipeToPrev;
  8343. s.params.allowSwipeToNext = allowSwipeToNext;
  8344. };
  8345. /*=========================
  8346. Events
  8347. ===========================*/
  8348. //Define Touch Events
  8349. var desktopEvents = ['mousedown', 'mousemove', 'mouseup'];
  8350. if (window.navigator.pointerEnabled) desktopEvents = ['pointerdown', 'pointermove', 'pointerup'];
  8351. else if (window.navigator.msPointerEnabled) desktopEvents = ['MSPointerDown', 'MSPointerMove', 'MSPointerUp'];
  8352. s.touchEvents = {
  8353. start : s.support.touch || !s.params.simulateTouch ? 'touchstart' : desktopEvents[0],
  8354. move : s.support.touch || !s.params.simulateTouch ? 'touchmove' : desktopEvents[1],
  8355. end : s.support.touch || !s.params.simulateTouch ? 'touchend' : desktopEvents[2]
  8356. };
  8357. // WP8 Touch Events Fix
  8358. if (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) {
  8359. (s.params.touchEventsTarget === 'container' ? s.container : s.wrapper).addClass('swiper-wp8-' + s.params.direction);
  8360. }
  8361. // Attach/detach events
  8362. s.initEvents = function (detach) {
  8363. var actionDom = detach ? 'off' : 'on';
  8364. var action = detach ? 'removeEventListener' : 'addEventListener';
  8365. var touchEventsTarget = s.params.touchEventsTarget === 'container' ? s.container[0] : s.wrapper[0];
  8366. var target = s.support.touch ? touchEventsTarget : document;
  8367. var moveCapture = s.params.nested ? true : false;
  8368. //Touch Events
  8369. if (s.browser.ie) {
  8370. touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false);
  8371. target[action](s.touchEvents.move, s.onTouchMove, moveCapture);
  8372. target[action](s.touchEvents.end, s.onTouchEnd, false);
  8373. }
  8374. else {
  8375. if (s.support.touch) {
  8376. touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false);
  8377. touchEventsTarget[action](s.touchEvents.move, s.onTouchMove, moveCapture);
  8378. touchEventsTarget[action](s.touchEvents.end, s.onTouchEnd, false);
  8379. }
  8380. if (params.simulateTouch && !s.device.ios && !s.device.android) {
  8381. touchEventsTarget[action]('mousedown', s.onTouchStart, false);
  8382. document[action]('mousemove', s.onTouchMove, moveCapture);
  8383. document[action]('mouseup', s.onTouchEnd, false);
  8384. }
  8385. }
  8386. window[action]('resize', s.onResize);
  8387. // Next, Prev, Index
  8388. if (s.params.nextButton) {
  8389. $(s.params.nextButton)[actionDom]('click', s.onClickNext);
  8390. if (s.params.a11y && s.a11y) $(s.params.nextButton)[actionDom]('keydown', s.a11y.onEnterKey);
  8391. }
  8392. if (s.params.prevButton) {
  8393. $(s.params.prevButton)[actionDom]('click', s.onClickPrev);
  8394. if (s.params.a11y && s.a11y) $(s.params.prevButton)[actionDom]('keydown', s.a11y.onEnterKey);
  8395. }
  8396. if (s.params.pagination && s.params.paginationClickable) {
  8397. $(s.paginationContainer)[actionDom]('click', '.' + s.params.bulletClass, s.onClickIndex);
  8398. if (s.params.a11y && s.a11y) $(s.paginationContainer)[actionDom]('keydown', '.' + s.params.bulletClass, s.a11y.onEnterKey);
  8399. }
  8400. // Prevent Links Clicks
  8401. if (s.params.preventClicks || s.params.preventClicksPropagation) touchEventsTarget[action]('click', s.preventClicks, true);
  8402. };
  8403. s.attachEvents = function (detach) {
  8404. s.initEvents();
  8405. };
  8406. s.detachEvents = function () {
  8407. s.initEvents(true);
  8408. };
  8409. /*=========================
  8410. Handle Clicks
  8411. ===========================*/
  8412. // Prevent Clicks
  8413. s.allowClick = true;
  8414. s.preventClicks = function (e) {
  8415. if (!s.allowClick) {
  8416. if (s.params.preventClicks) e.preventDefault();
  8417. if (s.params.preventClicksPropagation && s.animating) {
  8418. e.stopPropagation();
  8419. e.stopImmediatePropagation();
  8420. }
  8421. }
  8422. };
  8423. // Clicks
  8424. s.onClickNext = function (e) {
  8425. e.preventDefault();
  8426. if (s.isEnd && !s.params.loop) return;
  8427. s.slideNext();
  8428. };
  8429. s.onClickPrev = function (e) {
  8430. e.preventDefault();
  8431. if (s.isBeginning && !s.params.loop) return;
  8432. s.slidePrev();
  8433. };
  8434. s.onClickIndex = function (e) {
  8435. e.preventDefault();
  8436. var index = $(this).index() * s.params.slidesPerGroup;
  8437. if (s.params.loop) index = index + s.loopedSlides;
  8438. s.slideTo(index);
  8439. };
  8440. /*=========================
  8441. Handle Touches
  8442. ===========================*/
  8443. function findElementInEvent(e, selector) {
  8444. var el = $(e.target);
  8445. if (!el.is(selector)) {
  8446. if (typeof selector === 'string') {
  8447. el = el.parents(selector);
  8448. }
  8449. else if (selector.nodeType) {
  8450. var found;
  8451. el.parents().each(function (index, _el) {
  8452. if (_el === selector) found = selector;
  8453. });
  8454. if (!found) return undefined;
  8455. else return selector;
  8456. }
  8457. }
  8458. if (el.length === 0) {
  8459. return undefined;
  8460. }
  8461. return el[0];
  8462. }
  8463. s.updateClickedSlide = function (e) {
  8464. var slide = findElementInEvent(e, '.' + s.params.slideClass);
  8465. var slideFound = false;
  8466. if (slide) {
  8467. for (var i = 0; i < s.slides.length; i++) {
  8468. if (s.slides[i] === slide) slideFound = true;
  8469. }
  8470. }
  8471. if (slide && slideFound) {
  8472. s.clickedSlide = slide;
  8473. s.clickedIndex = $(slide).index();
  8474. }
  8475. else {
  8476. s.clickedSlide = undefined;
  8477. s.clickedIndex = undefined;
  8478. return;
  8479. }
  8480. if (s.params.slideToClickedSlide && s.clickedIndex !== undefined && s.clickedIndex !== s.activeIndex) {
  8481. var slideToIndex = s.clickedIndex,
  8482. realIndex,
  8483. duplicatedSlides;
  8484. if (s.params.loop) {
  8485. if (s.animating) return;
  8486. realIndex = $(s.clickedSlide).attr('data-swiper-slide-index');
  8487. if (s.params.centeredSlides) {
  8488. if ((slideToIndex < s.loopedSlides - s.params.slidesPerView/2) || (slideToIndex > s.slides.length - s.loopedSlides + s.params.slidesPerView/2)) {
  8489. s.fixLoop();
  8490. slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index();
  8491. setTimeout(function () {
  8492. s.slideTo(slideToIndex);
  8493. }, 0);
  8494. }
  8495. else {
  8496. s.slideTo(slideToIndex);
  8497. }
  8498. }
  8499. else {
  8500. if (slideToIndex > s.slides.length - s.params.slidesPerView) {
  8501. s.fixLoop();
  8502. slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index();
  8503. setTimeout(function () {
  8504. s.slideTo(slideToIndex);
  8505. }, 0);
  8506. }
  8507. else {
  8508. s.slideTo(slideToIndex);
  8509. }
  8510. }
  8511. }
  8512. else {
  8513. s.slideTo(slideToIndex);
  8514. }
  8515. }
  8516. };
  8517. var isTouched,
  8518. isMoved,
  8519. allowTouchCallbacks,
  8520. touchStartTime,
  8521. isScrolling,
  8522. currentTranslate,
  8523. startTranslate,
  8524. allowThresholdMove,
  8525. // Form elements to match
  8526. formElements = 'input, select, textarea, button',
  8527. // Last click time
  8528. lastClickTime = Date.now(), clickTimeout,
  8529. //Velocities
  8530. velocities = [],
  8531. allowMomentumBounce;
  8532. // Animating Flag
  8533. s.animating = false;
  8534. // Touches information
  8535. s.touches = {
  8536. startX: 0,
  8537. startY: 0,
  8538. currentX: 0,
  8539. currentY: 0,
  8540. diff: 0
  8541. };
  8542. // Touch handlers
  8543. var isTouchEvent, startMoving;
  8544. s.onTouchStart = function (e) {
  8545. if (e.originalEvent) e = e.originalEvent;
  8546. isTouchEvent = e.type === 'touchstart';
  8547. if (!isTouchEvent && 'which' in e && e.which === 3) return;
  8548. if (s.params.noSwiping && findElementInEvent(e, '.' + s.params.noSwipingClass)) {
  8549. s.allowClick = true;
  8550. return;
  8551. }
  8552. if (s.params.swipeHandler) {
  8553. if (!findElementInEvent(e, s.params.swipeHandler)) return;
  8554. }
  8555. var startX = s.touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
  8556. var startY = s.touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
  8557. // Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore
  8558. if(s.device.ios && s.params.iOSEdgeSwipeDetection && startX <= s.params.iOSEdgeSwipeThreshold) {
  8559. return;
  8560. }
  8561. isTouched = true;
  8562. isMoved = false;
  8563. allowTouchCallbacks = true;
  8564. isScrolling = undefined;
  8565. startMoving = undefined;
  8566. s.touches.startX = startX;
  8567. s.touches.startY = startY;
  8568. touchStartTime = Date.now();
  8569. s.allowClick = true;
  8570. s.updateContainerSize();
  8571. s.swipeDirection = undefined;
  8572. if (s.params.threshold > 0) allowThresholdMove = false;
  8573. if (e.type !== 'touchstart') {
  8574. var preventDefault = true;
  8575. if ($(e.target).is(formElements)) preventDefault = false;
  8576. if (document.activeElement && $(document.activeElement).is(formElements)) {
  8577. document.activeElement.blur();
  8578. }
  8579. if (preventDefault) {
  8580. e.preventDefault();
  8581. }
  8582. }
  8583. s.emit('onTouchStart', s, e);
  8584. };
  8585. s.onTouchMove = function (e) {
  8586. if (e.originalEvent) e = e.originalEvent;
  8587. if (isTouchEvent && e.type === 'mousemove') return;
  8588. if (e.preventedByNestedSwiper) return;
  8589. if (s.params.onlyExternal) {
  8590. // isMoved = true;
  8591. s.allowClick = false;
  8592. if (isTouched) {
  8593. s.touches.startX = s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
  8594. s.touches.startY = s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
  8595. touchStartTime = Date.now();
  8596. }
  8597. return;
  8598. }
  8599. if (isTouchEvent && document.activeElement) {
  8600. if (e.target === document.activeElement && $(e.target).is(formElements)) {
  8601. isMoved = true;
  8602. s.allowClick = false;
  8603. return;
  8604. }
  8605. }
  8606. if (allowTouchCallbacks) {
  8607. s.emit('onTouchMove', s, e);
  8608. }
  8609. if (e.targetTouches && e.targetTouches.length > 1) return;
  8610. s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
  8611. s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
  8612. if (typeof isScrolling === 'undefined') {
  8613. var touchAngle = Math.atan2(Math.abs(s.touches.currentY - s.touches.startY), Math.abs(s.touches.currentX - s.touches.startX)) * 180 / Math.PI;
  8614. isScrolling = isH() ? touchAngle > s.params.touchAngle : (90 - touchAngle > s.params.touchAngle);
  8615. }
  8616. if (isScrolling) {
  8617. s.emit('onTouchMoveOpposite', s, e);
  8618. }
  8619. if (typeof startMoving === 'undefined' && s.browser.ieTouch) {
  8620. if (s.touches.currentX !== s.touches.startX || s.touches.currentY !== s.touches.startY) {
  8621. startMoving = true;
  8622. }
  8623. }
  8624. if (!isTouched) return;
  8625. if (isScrolling) {
  8626. isTouched = false;
  8627. return;
  8628. }
  8629. if (!startMoving && s.browser.ieTouch) {
  8630. return;
  8631. }
  8632. s.allowClick = false;
  8633. s.emit('onSliderMove', s, e);
  8634. e.preventDefault();
  8635. if (s.params.touchMoveStopPropagation && !s.params.nested) {
  8636. e.stopPropagation();
  8637. }
  8638. if (!isMoved) {
  8639. if (params.loop) {
  8640. s.fixLoop();
  8641. }
  8642. startTranslate = s.getWrapperTranslate();
  8643. s.setWrapperTransition(0);
  8644. if (s.animating) {
  8645. s.wrapper.trigger('webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd msTransitionEnd');
  8646. }
  8647. if (s.params.autoplay && s.autoplaying) {
  8648. if (s.params.autoplayDisableOnInteraction) {
  8649. s.stopAutoplay();
  8650. }
  8651. else {
  8652. s.pauseAutoplay();
  8653. }
  8654. }
  8655. allowMomentumBounce = false;
  8656. //Grab Cursor
  8657. if (s.params.grabCursor) {
  8658. s.container[0].style.cursor = 'move';
  8659. s.container[0].style.cursor = '-webkit-grabbing';
  8660. s.container[0].style.cursor = '-moz-grabbin';
  8661. s.container[0].style.cursor = 'grabbing';
  8662. }
  8663. }
  8664. isMoved = true;
  8665. var diff = s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY;
  8666. diff = diff * s.params.touchRatio;
  8667. if (s.rtl) diff = -diff;
  8668. s.swipeDirection = diff > 0 ? 'prev' : 'next';
  8669. currentTranslate = diff + startTranslate;
  8670. var disableParentSwiper = true;
  8671. if ((diff > 0 && currentTranslate > s.minTranslate())) {
  8672. disableParentSwiper = false;
  8673. if (s.params.resistance) currentTranslate = s.minTranslate() - 1 + Math.pow(-s.minTranslate() + startTranslate + diff, s.params.resistanceRatio);
  8674. }
  8675. else if (diff < 0 && currentTranslate < s.maxTranslate()) {
  8676. disableParentSwiper = false;
  8677. if (s.params.resistance) currentTranslate = s.maxTranslate() + 1 - Math.pow(s.maxTranslate() - startTranslate - diff, s.params.resistanceRatio);
  8678. }
  8679. if (disableParentSwiper) {
  8680. e.preventedByNestedSwiper = true;
  8681. }
  8682. // Directions locks
  8683. if (!s.params.allowSwipeToNext && s.swipeDirection === 'next' && currentTranslate < startTranslate) {
  8684. currentTranslate = startTranslate;
  8685. }
  8686. if (!s.params.allowSwipeToPrev && s.swipeDirection === 'prev' && currentTranslate > startTranslate) {
  8687. currentTranslate = startTranslate;
  8688. }
  8689. if (!s.params.followFinger) return;
  8690. // Threshold
  8691. if (s.params.threshold > 0) {
  8692. if (Math.abs(diff) > s.params.threshold || allowThresholdMove) {
  8693. if (!allowThresholdMove) {
  8694. allowThresholdMove = true;
  8695. s.touches.startX = s.touches.currentX;
  8696. s.touches.startY = s.touches.currentY;
  8697. currentTranslate = startTranslate;
  8698. s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY;
  8699. return;
  8700. }
  8701. }
  8702. else {
  8703. currentTranslate = startTranslate;
  8704. return;
  8705. }
  8706. }
  8707. // Update active index in free mode
  8708. if (s.params.freeMode || s.params.watchSlidesProgress) {
  8709. s.updateActiveIndex();
  8710. }
  8711. if (s.params.freeMode) {
  8712. //Velocity
  8713. if (velocities.length === 0) {
  8714. velocities.push({
  8715. position: s.touches[isH() ? 'startX' : 'startY'],
  8716. time: touchStartTime
  8717. });
  8718. }
  8719. velocities.push({
  8720. position: s.touches[isH() ? 'currentX' : 'currentY'],
  8721. time: (new window.Date()).getTime()
  8722. });
  8723. }
  8724. // Update progress
  8725. s.updateProgress(currentTranslate);
  8726. // Update translate
  8727. s.setWrapperTranslate(currentTranslate);
  8728. };
  8729. s.onTouchEnd = function (e) {
  8730. if (e.originalEvent) e = e.originalEvent;
  8731. if (allowTouchCallbacks) {
  8732. s.emit('onTouchEnd', s, e);
  8733. }
  8734. allowTouchCallbacks = false;
  8735. if (!isTouched) return;
  8736. //Return Grab Cursor
  8737. if (s.params.grabCursor && isMoved && isTouched) {
  8738. s.container[0].style.cursor = 'move';
  8739. s.container[0].style.cursor = '-webkit-grab';
  8740. s.container[0].style.cursor = '-moz-grab';
  8741. s.container[0].style.cursor = 'grab';
  8742. }
  8743. // Time diff
  8744. var touchEndTime = Date.now();
  8745. var timeDiff = touchEndTime - touchStartTime;
  8746. // Tap, doubleTap, Click
  8747. if (s.allowClick) {
  8748. s.updateClickedSlide(e);
  8749. s.emit('onTap', s, e);
  8750. if (timeDiff < 300 && (touchEndTime - lastClickTime) > 300) {
  8751. if (clickTimeout) clearTimeout(clickTimeout);
  8752. clickTimeout = setTimeout(function () {
  8753. if (!s) return;
  8754. if (s.params.paginationHide && s.paginationContainer.length > 0 && !$(e.target).hasClass(s.params.bulletClass)) {
  8755. s.paginationContainer.toggleClass(s.params.paginationHiddenClass);
  8756. }
  8757. s.emit('onClick', s, e);
  8758. }, 300);
  8759. }
  8760. if (timeDiff < 300 && (touchEndTime - lastClickTime) < 300) {
  8761. if (clickTimeout) clearTimeout(clickTimeout);
  8762. s.emit('onDoubleTap', s, e);
  8763. }
  8764. }
  8765. lastClickTime = Date.now();
  8766. setTimeout(function () {
  8767. if (s) s.allowClick = true;
  8768. }, 0);
  8769. if (!isTouched || !isMoved || !s.swipeDirection || s.touches.diff === 0 || currentTranslate === startTranslate) {
  8770. isTouched = isMoved = false;
  8771. return;
  8772. }
  8773. isTouched = isMoved = false;
  8774. var currentPos;
  8775. if (s.params.followFinger) {
  8776. currentPos = s.rtl ? s.translate : -s.translate;
  8777. }
  8778. else {
  8779. currentPos = -currentTranslate;
  8780. }
  8781. if (s.params.freeMode) {
  8782. if (currentPos < -s.minTranslate()) {
  8783. s.slideTo(s.activeIndex);
  8784. return;
  8785. }
  8786. else if (currentPos > -s.maxTranslate()) {
  8787. if (s.slides.length < s.snapGrid.length) {
  8788. s.slideTo(s.snapGrid.length - 1);
  8789. }
  8790. else {
  8791. s.slideTo(s.slides.length - 1);
  8792. }
  8793. return;
  8794. }
  8795. if (s.params.freeModeMomentum) {
  8796. if (velocities.length > 1) {
  8797. var lastMoveEvent = velocities.pop(), velocityEvent = velocities.pop();
  8798. var distance = lastMoveEvent.position - velocityEvent.position;
  8799. var time = lastMoveEvent.time - velocityEvent.time;
  8800. s.velocity = distance / time;
  8801. s.velocity = s.velocity / 2;
  8802. if (Math.abs(s.velocity) < s.params.freeModeMinimumVelocity) {
  8803. s.velocity = 0;
  8804. }
  8805. // this implies that the user stopped moving a finger then released.
  8806. // There would be no events with distance zero, so the last event is stale.
  8807. if (time > 150 || (new window.Date().getTime() - lastMoveEvent.time) > 300) {
  8808. s.velocity = 0;
  8809. }
  8810. } else {
  8811. s.velocity = 0;
  8812. }
  8813. velocities.length = 0;
  8814. var momentumDuration = 1000 * s.params.freeModeMomentumRatio;
  8815. var momentumDistance = s.velocity * momentumDuration;
  8816. var newPosition = s.translate + momentumDistance;
  8817. if (s.rtl) newPosition = - newPosition;
  8818. var doBounce = false;
  8819. var afterBouncePosition;
  8820. var bounceAmount = Math.abs(s.velocity) * 20 * s.params.freeModeMomentumBounceRatio;
  8821. if (newPosition < s.maxTranslate()) {
  8822. if (s.params.freeModeMomentumBounce) {
  8823. if (newPosition + s.maxTranslate() < -bounceAmount) {
  8824. newPosition = s.maxTranslate() - bounceAmount;
  8825. }
  8826. afterBouncePosition = s.maxTranslate();
  8827. doBounce = true;
  8828. allowMomentumBounce = true;
  8829. }
  8830. else {
  8831. newPosition = s.maxTranslate();
  8832. }
  8833. }
  8834. else if (newPosition > s.minTranslate()) {
  8835. if (s.params.freeModeMomentumBounce) {
  8836. if (newPosition - s.minTranslate() > bounceAmount) {
  8837. newPosition = s.minTranslate() + bounceAmount;
  8838. }
  8839. afterBouncePosition = s.minTranslate();
  8840. doBounce = true;
  8841. allowMomentumBounce = true;
  8842. }
  8843. else {
  8844. newPosition = s.minTranslate();
  8845. }
  8846. }
  8847. else if (s.params.freeModeSticky) {
  8848. var j = 0,
  8849. nextSlide;
  8850. for (j = 0; j < s.snapGrid.length; j += 1) {
  8851. if (s.snapGrid[j] > -newPosition) {
  8852. nextSlide = j;
  8853. break;
  8854. }
  8855. }
  8856. if (Math.abs(s.snapGrid[nextSlide] - newPosition) < Math.abs(s.snapGrid[nextSlide - 1] - newPosition) || s.swipeDirection === 'next') {
  8857. newPosition = s.snapGrid[nextSlide];
  8858. } else {
  8859. newPosition = s.snapGrid[nextSlide - 1];
  8860. }
  8861. if (!s.rtl) newPosition = - newPosition;
  8862. }
  8863. //Fix duration
  8864. if (s.velocity !== 0) {
  8865. if (s.rtl) {
  8866. momentumDuration = Math.abs((-newPosition - s.translate) / s.velocity);
  8867. }
  8868. else {
  8869. momentumDuration = Math.abs((newPosition - s.translate) / s.velocity);
  8870. }
  8871. }
  8872. else if (s.params.freeModeSticky) {
  8873. s.slideReset();
  8874. return;
  8875. }
  8876. if (s.params.freeModeMomentumBounce && doBounce) {
  8877. s.updateProgress(afterBouncePosition);
  8878. s.setWrapperTransition(momentumDuration);
  8879. s.setWrapperTranslate(newPosition);
  8880. s.onTransitionStart();
  8881. s.animating = true;
  8882. s.wrapper.transitionEnd(function () {
  8883. if (!s || !allowMomentumBounce) return;
  8884. s.emit('onMomentumBounce', s);
  8885. s.setWrapperTransition(s.params.speed);
  8886. s.setWrapperTranslate(afterBouncePosition);
  8887. s.wrapper.transitionEnd(function () {
  8888. if (!s) return;
  8889. s.onTransitionEnd();
  8890. });
  8891. });
  8892. } else if (s.velocity) {
  8893. s.updateProgress(newPosition);
  8894. s.setWrapperTransition(momentumDuration);
  8895. s.setWrapperTranslate(newPosition);
  8896. s.onTransitionStart();
  8897. if (!s.animating) {
  8898. s.animating = true;
  8899. s.wrapper.transitionEnd(function () {
  8900. if (!s) return;
  8901. s.onTransitionEnd();
  8902. });
  8903. }
  8904. } else {
  8905. s.updateProgress(newPosition);
  8906. }
  8907. s.updateActiveIndex();
  8908. }
  8909. if (!s.params.freeModeMomentum || timeDiff >= s.params.longSwipesMs) {
  8910. s.updateProgress();
  8911. s.updateActiveIndex();
  8912. }
  8913. return;
  8914. }
  8915. // Find current slide
  8916. var i, stopIndex = 0, groupSize = s.slidesSizesGrid[0];
  8917. for (i = 0; i < s.slidesGrid.length; i += s.params.slidesPerGroup) {
  8918. if (typeof s.slidesGrid[i + s.params.slidesPerGroup] !== 'undefined') {
  8919. if (currentPos >= s.slidesGrid[i] && currentPos < s.slidesGrid[i + s.params.slidesPerGroup]) {
  8920. stopIndex = i;
  8921. groupSize = s.slidesGrid[i + s.params.slidesPerGroup] - s.slidesGrid[i];
  8922. }
  8923. }
  8924. else {
  8925. if (currentPos >= s.slidesGrid[i]) {
  8926. stopIndex = i;
  8927. groupSize = s.slidesGrid[s.slidesGrid.length - 1] - s.slidesGrid[s.slidesGrid.length - 2];
  8928. }
  8929. }
  8930. }
  8931. // Find current slide size
  8932. var ratio = (currentPos - s.slidesGrid[stopIndex]) / groupSize;
  8933. if (timeDiff > s.params.longSwipesMs) {
  8934. // Long touches
  8935. if (!s.params.longSwipes) {
  8936. s.slideTo(s.activeIndex);
  8937. return;
  8938. }
  8939. if (s.swipeDirection === 'next') {
  8940. if (ratio >= s.params.longSwipesRatio) s.slideTo(stopIndex + s.params.slidesPerGroup);
  8941. else s.slideTo(stopIndex);
  8942. }
  8943. if (s.swipeDirection === 'prev') {
  8944. if (ratio > (1 - s.params.longSwipesRatio)) s.slideTo(stopIndex + s.params.slidesPerGroup);
  8945. else s.slideTo(stopIndex);
  8946. }
  8947. }
  8948. else {
  8949. // Short swipes
  8950. if (!s.params.shortSwipes) {
  8951. s.slideTo(s.activeIndex);
  8952. return;
  8953. }
  8954. if (s.swipeDirection === 'next') {
  8955. s.slideTo(stopIndex + s.params.slidesPerGroup);
  8956. }
  8957. if (s.swipeDirection === 'prev') {
  8958. s.slideTo(stopIndex);
  8959. }
  8960. }
  8961. };
  8962. /*=========================
  8963. Transitions
  8964. ===========================*/
  8965. s._slideTo = function (slideIndex, speed) {
  8966. return s.slideTo(slideIndex, speed, true, true);
  8967. };
  8968. s.slideTo = function (slideIndex, speed, runCallbacks, internal) {
  8969. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  8970. if (typeof slideIndex === 'undefined') slideIndex = 0;
  8971. if (slideIndex < 0) slideIndex = 0;
  8972. s.snapIndex = Math.floor(slideIndex / s.params.slidesPerGroup);
  8973. if (s.snapIndex >= s.snapGrid.length) s.snapIndex = s.snapGrid.length - 1;
  8974. var translate = - s.snapGrid[s.snapIndex];
  8975. // Stop autoplay
  8976. if (s.params.autoplay && s.autoplaying) {
  8977. if (internal || !s.params.autoplayDisableOnInteraction) {
  8978. s.pauseAutoplay(speed);
  8979. }
  8980. else {
  8981. s.stopAutoplay();
  8982. }
  8983. }
  8984. // Update progress
  8985. s.updateProgress(translate);
  8986. // Normalize slideIndex
  8987. for (var i = 0; i < s.slidesGrid.length; i++) {
  8988. if (- Math.floor(translate * 100) >= Math.floor(s.slidesGrid[i] * 100)) {
  8989. slideIndex = i;
  8990. }
  8991. }
  8992. // Directions locks
  8993. if (!s.params.allowSwipeToNext && translate < s.translate && translate < s.minTranslate()) {
  8994. return false;
  8995. }
  8996. if (!s.params.allowSwipeToPrev && translate > s.translate && translate > s.maxTranslate()) {
  8997. if ((s.activeIndex || 0) !== slideIndex ) return false;
  8998. }
  8999. // Update Index
  9000. if (typeof speed === 'undefined') speed = s.params.speed;
  9001. s.previousIndex = s.activeIndex || 0;
  9002. s.activeIndex = slideIndex;
  9003. if ((s.rtl && -translate === s.translate) || (!s.rtl && translate === s.translate)) {
  9004. // Update Height
  9005. if (s.params.autoHeight) {
  9006. s.updateAutoHeight();
  9007. }
  9008. s.updateClasses();
  9009. if (s.params.effect !== 'slide') {
  9010. s.setWrapperTranslate(translate);
  9011. }
  9012. return false;
  9013. }
  9014. s.updateClasses();
  9015. s.onTransitionStart(runCallbacks);
  9016. if (speed === 0) {
  9017. s.setWrapperTranslate(translate);
  9018. s.setWrapperTransition(0);
  9019. s.onTransitionEnd(runCallbacks);
  9020. }
  9021. else {
  9022. s.setWrapperTranslate(translate);
  9023. s.setWrapperTransition(speed);
  9024. if (!s.animating) {
  9025. s.animating = true;
  9026. s.wrapper.transitionEnd(function () {
  9027. if (!s) return;
  9028. s.onTransitionEnd(runCallbacks);
  9029. });
  9030. }
  9031. }
  9032. return true;
  9033. };
  9034. s.onTransitionStart = function (runCallbacks) {
  9035. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  9036. if (s.params.autoHeight) {
  9037. s.updateAutoHeight();
  9038. }
  9039. if (s.lazy) s.lazy.onTransitionStart();
  9040. if (runCallbacks) {
  9041. s.emit('onTransitionStart', s);
  9042. if (s.activeIndex !== s.previousIndex) {
  9043. s.emit('onSlideChangeStart', s);
  9044. _scope.$emit("$ionicSlides.slideChangeStart", {
  9045. slider: s,
  9046. activeIndex: s.getSlideDataIndex(s.activeIndex),
  9047. previousIndex: s.getSlideDataIndex(s.previousIndex)
  9048. });
  9049. if (s.activeIndex > s.previousIndex) {
  9050. s.emit('onSlideNextStart', s);
  9051. }
  9052. else {
  9053. s.emit('onSlidePrevStart', s);
  9054. }
  9055. }
  9056. }
  9057. };
  9058. s.onTransitionEnd = function (runCallbacks) {
  9059. s.animating = false;
  9060. s.setWrapperTransition(0);
  9061. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  9062. if (s.lazy) s.lazy.onTransitionEnd();
  9063. if (runCallbacks) {
  9064. s.emit('onTransitionEnd', s);
  9065. if (s.activeIndex !== s.previousIndex) {
  9066. s.emit('onSlideChangeEnd', s);
  9067. _scope.$emit("$ionicSlides.slideChangeEnd", {
  9068. slider: s,
  9069. activeIndex: s.getSlideDataIndex(s.activeIndex),
  9070. previousIndex: s.getSlideDataIndex(s.previousIndex)
  9071. });
  9072. if (s.activeIndex > s.previousIndex) {
  9073. s.emit('onSlideNextEnd', s);
  9074. }
  9075. else {
  9076. s.emit('onSlidePrevEnd', s);
  9077. }
  9078. }
  9079. }
  9080. if (s.params.hashnav && s.hashnav) {
  9081. s.hashnav.setHash();
  9082. }
  9083. };
  9084. s.slideNext = function (runCallbacks, speed, internal) {
  9085. if (s.params.loop) {
  9086. if (s.animating) return false;
  9087. s.fixLoop();
  9088. var clientLeft = s.container[0].clientLeft;
  9089. return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal);
  9090. }
  9091. else return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal);
  9092. };
  9093. s._slideNext = function (speed) {
  9094. return s.slideNext(true, speed, true);
  9095. };
  9096. s.slidePrev = function (runCallbacks, speed, internal) {
  9097. if (s.params.loop) {
  9098. if (s.animating) return false;
  9099. s.fixLoop();
  9100. var clientLeft = s.container[0].clientLeft;
  9101. return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal);
  9102. }
  9103. else return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal);
  9104. };
  9105. s._slidePrev = function (speed) {
  9106. return s.slidePrev(true, speed, true);
  9107. };
  9108. s.slideReset = function (runCallbacks, speed, internal) {
  9109. return s.slideTo(s.activeIndex, speed, runCallbacks);
  9110. };
  9111. /*=========================
  9112. Translate/transition helpers
  9113. ===========================*/
  9114. s.setWrapperTransition = function (duration, byController) {
  9115. s.wrapper.transition(duration);
  9116. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  9117. s.effects[s.params.effect].setTransition(duration);
  9118. }
  9119. if (s.params.parallax && s.parallax) {
  9120. s.parallax.setTransition(duration);
  9121. }
  9122. if (s.params.scrollbar && s.scrollbar) {
  9123. s.scrollbar.setTransition(duration);
  9124. }
  9125. if (s.params.control && s.controller) {
  9126. s.controller.setTransition(duration, byController);
  9127. }
  9128. s.emit('onSetTransition', s, duration);
  9129. };
  9130. s.setWrapperTranslate = function (translate, updateActiveIndex, byController) {
  9131. var x = 0, y = 0, z = 0;
  9132. if (isH()) {
  9133. x = s.rtl ? -translate : translate;
  9134. }
  9135. else {
  9136. y = translate;
  9137. }
  9138. if (s.params.roundLengths) {
  9139. x = round(x);
  9140. y = round(y);
  9141. }
  9142. if (!s.params.virtualTranslate) {
  9143. if (s.support.transforms3d) s.wrapper.transform('translate3d(' + x + 'px, ' + y + 'px, ' + z + 'px)');
  9144. else s.wrapper.transform('translate(' + x + 'px, ' + y + 'px)');
  9145. }
  9146. s.translate = isH() ? x : y;
  9147. // Check if we need to update progress
  9148. var progress;
  9149. var translatesDiff = s.maxTranslate() - s.minTranslate();
  9150. if (translatesDiff === 0) {
  9151. progress = 0;
  9152. }
  9153. else {
  9154. progress = (translate - s.minTranslate()) / (translatesDiff);
  9155. }
  9156. if (progress !== s.progress) {
  9157. s.updateProgress(translate);
  9158. }
  9159. if (updateActiveIndex) s.updateActiveIndex();
  9160. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  9161. s.effects[s.params.effect].setTranslate(s.translate);
  9162. }
  9163. if (s.params.parallax && s.parallax) {
  9164. s.parallax.setTranslate(s.translate);
  9165. }
  9166. if (s.params.scrollbar && s.scrollbar) {
  9167. s.scrollbar.setTranslate(s.translate);
  9168. }
  9169. if (s.params.control && s.controller) {
  9170. s.controller.setTranslate(s.translate, byController);
  9171. }
  9172. s.emit('onSetTranslate', s, s.translate);
  9173. };
  9174. s.getTranslate = function (el, axis) {
  9175. var matrix, curTransform, curStyle, transformMatrix;
  9176. // automatic axis detection
  9177. if (typeof axis === 'undefined') {
  9178. axis = 'x';
  9179. }
  9180. if (s.params.virtualTranslate) {
  9181. return s.rtl ? -s.translate : s.translate;
  9182. }
  9183. curStyle = window.getComputedStyle(el, null);
  9184. if (window.WebKitCSSMatrix) {
  9185. curTransform = curStyle.transform || curStyle.webkitTransform;
  9186. if (curTransform.split(',').length > 6) {
  9187. curTransform = curTransform.split(', ').map(function(a){
  9188. return a.replace(',','.');
  9189. }).join(', ');
  9190. }
  9191. // Some old versions of Webkit choke when 'none' is passed; pass
  9192. // empty string instead in this case
  9193. transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform);
  9194. }
  9195. else {
  9196. transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,');
  9197. matrix = transformMatrix.toString().split(',');
  9198. }
  9199. if (axis === 'x') {
  9200. //Latest Chrome and webkits Fix
  9201. if (window.WebKitCSSMatrix)
  9202. curTransform = transformMatrix.m41;
  9203. //Crazy IE10 Matrix
  9204. else if (matrix.length === 16)
  9205. curTransform = parseFloat(matrix[12]);
  9206. //Normal Browsers
  9207. else
  9208. curTransform = parseFloat(matrix[4]);
  9209. }
  9210. if (axis === 'y') {
  9211. //Latest Chrome and webkits Fix
  9212. if (window.WebKitCSSMatrix)
  9213. curTransform = transformMatrix.m42;
  9214. //Crazy IE10 Matrix
  9215. else if (matrix.length === 16)
  9216. curTransform = parseFloat(matrix[13]);
  9217. //Normal Browsers
  9218. else
  9219. curTransform = parseFloat(matrix[5]);
  9220. }
  9221. if (s.rtl && curTransform) curTransform = -curTransform;
  9222. return curTransform || 0;
  9223. };
  9224. s.getWrapperTranslate = function (axis) {
  9225. if (typeof axis === 'undefined') {
  9226. axis = isH() ? 'x' : 'y';
  9227. }
  9228. return s.getTranslate(s.wrapper[0], axis);
  9229. };
  9230. /*=========================
  9231. Observer
  9232. ===========================*/
  9233. s.observers = [];
  9234. function initObserver(target, options) {
  9235. options = options || {};
  9236. // create an observer instance
  9237. var ObserverFunc = window.MutationObserver || window.WebkitMutationObserver;
  9238. var observer = new ObserverFunc(function (mutations) {
  9239. mutations.forEach(function (mutation) {
  9240. s.onResize(true);
  9241. s.emit('onObserverUpdate', s, mutation);
  9242. });
  9243. });
  9244. observer.observe(target, {
  9245. attributes: typeof options.attributes === 'undefined' ? true : options.attributes,
  9246. childList: typeof options.childList === 'undefined' ? true : options.childList,
  9247. characterData: typeof options.characterData === 'undefined' ? true : options.characterData
  9248. });
  9249. s.observers.push(observer);
  9250. }
  9251. s.initObservers = function () {
  9252. if (s.params.observeParents) {
  9253. var containerParents = s.container.parents();
  9254. for (var i = 0; i < containerParents.length; i++) {
  9255. initObserver(containerParents[i]);
  9256. }
  9257. }
  9258. // Observe container
  9259. initObserver(s.container[0], {childList: false});
  9260. // Observe wrapper
  9261. initObserver(s.wrapper[0], {attributes: false});
  9262. };
  9263. s.disconnectObservers = function () {
  9264. for (var i = 0; i < s.observers.length; i++) {
  9265. s.observers[i].disconnect();
  9266. }
  9267. s.observers = [];
  9268. };
  9269. s.updateLoop = function(){
  9270. var currentSlide = s.slides.eq(s.activeIndex);
  9271. if ( angular.element(currentSlide).hasClass(s.params.slideDuplicateClass) ){
  9272. // we're on a duplicate, so slide to the non-duplicate
  9273. var swiperSlideIndex = angular.element(currentSlide).attr("data-swiper-slide-index");
  9274. var slides = s.wrapper.children('.' + s.params.slideClass);
  9275. for ( var i = 0; i < slides.length; i++ ){
  9276. if ( !angular.element(slides[i]).hasClass(s.params.slideDuplicateClass) && angular.element(slides[i]).attr("data-swiper-slide-index") === swiperSlideIndex ){
  9277. s.slideTo(i, 0, false, true);
  9278. break;
  9279. }
  9280. }
  9281. // if we needed to switch slides, we did that. So, now call the createLoop function internally
  9282. setTimeout(function(){
  9283. s.createLoop();
  9284. }, 50);
  9285. }
  9286. }
  9287. s.getSlideDataIndex = function(slideIndex){
  9288. // this is an Ionic custom function
  9289. // Swiper loops utilize duplicate DOM elements for slides when in a loop
  9290. // which means that we cannot rely on the actual slide index for our events
  9291. // because index 0 does not necessarily point to index 0
  9292. // and index n+1 does not necessarily point to the expected piece of data
  9293. // therefore, rather than using the actual slide index we should
  9294. // use the data index that swiper includes as an attribute on the dom elements
  9295. // because this is what will be meaningful to the consumer of our events
  9296. var slide = s.slides.eq(slideIndex);
  9297. var attributeIndex = angular.element(slide).attr("data-swiper-slide-index");
  9298. return parseInt(attributeIndex);
  9299. }
  9300. /*=========================
  9301. Loop
  9302. ===========================*/
  9303. // Create looped slides
  9304. s.createLoop = function () {
  9305. //console.log("Slider create loop method");
  9306. //var toRemove = s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass);
  9307. //angular.element(toRemove).remove();
  9308. s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass).remove();
  9309. var slides = s.wrapper.children('.' + s.params.slideClass);
  9310. if(s.params.slidesPerView === 'auto' && !s.params.loopedSlides) s.params.loopedSlides = slides.length;
  9311. s.loopedSlides = parseInt(s.params.loopedSlides || s.params.slidesPerView, 10);
  9312. s.loopedSlides = s.loopedSlides + s.params.loopAdditionalSlides;
  9313. if (s.loopedSlides > slides.length) {
  9314. s.loopedSlides = slides.length;
  9315. }
  9316. var prependSlides = [], appendSlides = [], i, scope, newNode;
  9317. slides.each(function (index, el) {
  9318. var slide = $(this);
  9319. if (index < s.loopedSlides) appendSlides.push(el);
  9320. if (index < slides.length && index >= slides.length - s.loopedSlides) prependSlides.push(el);
  9321. slide.attr('data-swiper-slide-index', index);
  9322. });
  9323. for (i = 0; i < appendSlides.length; i++) {
  9324. newNode = angular.element(appendSlides[i]).clone().addClass(s.params.slideDuplicateClass);
  9325. newNode.removeAttr('ng-transclude');
  9326. newNode.removeAttr('ng-repeat');
  9327. scope = angular.element(appendSlides[i]).scope();
  9328. newNode = $compile(newNode)(scope);
  9329. angular.element(s.wrapper).append(newNode);
  9330. //s.wrapper.append($(appendSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));
  9331. }
  9332. for (i = prependSlides.length - 1; i >= 0; i--) {
  9333. //s.wrapper.prepend($(prependSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));
  9334. newNode = angular.element(prependSlides[i]).clone().addClass(s.params.slideDuplicateClass);
  9335. newNode.removeAttr('ng-transclude');
  9336. newNode.removeAttr('ng-repeat');
  9337. scope = angular.element(prependSlides[i]).scope();
  9338. newNode = $compile(newNode)(scope);
  9339. angular.element(s.wrapper).prepend(newNode);
  9340. }
  9341. };
  9342. s.destroyLoop = function () {
  9343. s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass).remove();
  9344. s.slides.removeAttr('data-swiper-slide-index');
  9345. };
  9346. s.fixLoop = function () {
  9347. var newIndex;
  9348. //Fix For Negative Oversliding
  9349. if (s.activeIndex < s.loopedSlides) {
  9350. newIndex = s.slides.length - s.loopedSlides * 3 + s.activeIndex;
  9351. newIndex = newIndex + s.loopedSlides;
  9352. s.slideTo(newIndex, 0, false, true);
  9353. }
  9354. //Fix For Positive Oversliding
  9355. else if ((s.params.slidesPerView === 'auto' && s.activeIndex >= s.loopedSlides * 2) || (s.activeIndex > s.slides.length - s.params.slidesPerView * 2)) {
  9356. newIndex = -s.slides.length + s.activeIndex + s.loopedSlides;
  9357. newIndex = newIndex + s.loopedSlides;
  9358. s.slideTo(newIndex, 0, false, true);
  9359. }
  9360. };
  9361. /*=========================
  9362. Append/Prepend/Remove Slides
  9363. ===========================*/
  9364. s.appendSlide = function (slides) {
  9365. if (s.params.loop) {
  9366. s.destroyLoop();
  9367. }
  9368. if (typeof slides === 'object' && slides.length) {
  9369. for (var i = 0; i < slides.length; i++) {
  9370. if (slides[i]) s.wrapper.append(slides[i]);
  9371. }
  9372. }
  9373. else {
  9374. s.wrapper.append(slides);
  9375. }
  9376. if (s.params.loop) {
  9377. s.createLoop();
  9378. }
  9379. if (!(s.params.observer && s.support.observer)) {
  9380. s.update(true);
  9381. }
  9382. };
  9383. s.prependSlide = function (slides) {
  9384. if (s.params.loop) {
  9385. s.destroyLoop();
  9386. }
  9387. var newActiveIndex = s.activeIndex + 1;
  9388. if (typeof slides === 'object' && slides.length) {
  9389. for (var i = 0; i < slides.length; i++) {
  9390. if (slides[i]) s.wrapper.prepend(slides[i]);
  9391. }
  9392. newActiveIndex = s.activeIndex + slides.length;
  9393. }
  9394. else {
  9395. s.wrapper.prepend(slides);
  9396. }
  9397. if (s.params.loop) {
  9398. s.createLoop();
  9399. }
  9400. if (!(s.params.observer && s.support.observer)) {
  9401. s.update(true);
  9402. }
  9403. s.slideTo(newActiveIndex, 0, false);
  9404. };
  9405. s.removeSlide = function (slidesIndexes) {
  9406. if (s.params.loop) {
  9407. s.destroyLoop();
  9408. s.slides = s.wrapper.children('.' + s.params.slideClass);
  9409. }
  9410. var newActiveIndex = s.activeIndex,
  9411. indexToRemove;
  9412. if (typeof slidesIndexes === 'object' && slidesIndexes.length) {
  9413. for (var i = 0; i < slidesIndexes.length; i++) {
  9414. indexToRemove = slidesIndexes[i];
  9415. if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove();
  9416. if (indexToRemove < newActiveIndex) newActiveIndex--;
  9417. }
  9418. newActiveIndex = Math.max(newActiveIndex, 0);
  9419. }
  9420. else {
  9421. indexToRemove = slidesIndexes;
  9422. if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove();
  9423. if (indexToRemove < newActiveIndex) newActiveIndex--;
  9424. newActiveIndex = Math.max(newActiveIndex, 0);
  9425. }
  9426. if (s.params.loop) {
  9427. s.createLoop();
  9428. }
  9429. if (!(s.params.observer && s.support.observer)) {
  9430. s.update(true);
  9431. }
  9432. if (s.params.loop) {
  9433. s.slideTo(newActiveIndex + s.loopedSlides, 0, false);
  9434. }
  9435. else {
  9436. s.slideTo(newActiveIndex, 0, false);
  9437. }
  9438. };
  9439. s.removeAllSlides = function () {
  9440. var slidesIndexes = [];
  9441. for (var i = 0; i < s.slides.length; i++) {
  9442. slidesIndexes.push(i);
  9443. }
  9444. s.removeSlide(slidesIndexes);
  9445. };
  9446. /*=========================
  9447. Effects
  9448. ===========================*/
  9449. s.effects = {
  9450. fade: {
  9451. setTranslate: function () {
  9452. for (var i = 0; i < s.slides.length; i++) {
  9453. var slide = s.slides.eq(i);
  9454. var offset = slide[0].swiperSlideOffset;
  9455. var tx = -offset;
  9456. if (!s.params.virtualTranslate) tx = tx - s.translate;
  9457. var ty = 0;
  9458. if (!isH()) {
  9459. ty = tx;
  9460. tx = 0;
  9461. }
  9462. var slideOpacity = s.params.fade.crossFade ?
  9463. Math.max(1 - Math.abs(slide[0].progress), 0) :
  9464. 1 + Math.min(Math.max(slide[0].progress, -1), 0);
  9465. slide
  9466. .css({
  9467. opacity: slideOpacity
  9468. })
  9469. .transform('translate3d(' + tx + 'px, ' + ty + 'px, 0px)');
  9470. }
  9471. },
  9472. setTransition: function (duration) {
  9473. s.slides.transition(duration);
  9474. if (s.params.virtualTranslate && duration !== 0) {
  9475. var eventTriggered = false;
  9476. s.slides.transitionEnd(function () {
  9477. if (eventTriggered) return;
  9478. if (!s) return;
  9479. eventTriggered = true;
  9480. s.animating = false;
  9481. var triggerEvents = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
  9482. for (var i = 0; i < triggerEvents.length; i++) {
  9483. s.wrapper.trigger(triggerEvents[i]);
  9484. }
  9485. });
  9486. }
  9487. }
  9488. },
  9489. cube: {
  9490. setTranslate: function () {
  9491. var wrapperRotate = 0, cubeShadow;
  9492. if (s.params.cube.shadow) {
  9493. if (isH()) {
  9494. cubeShadow = s.wrapper.find('.swiper-cube-shadow');
  9495. if (cubeShadow.length === 0) {
  9496. cubeShadow = $('<div class="swiper-cube-shadow"></div>');
  9497. s.wrapper.append(cubeShadow);
  9498. }
  9499. cubeShadow.css({height: s.width + 'px'});
  9500. }
  9501. else {
  9502. cubeShadow = s.container.find('.swiper-cube-shadow');
  9503. if (cubeShadow.length === 0) {
  9504. cubeShadow = $('<div class="swiper-cube-shadow"></div>');
  9505. s.container.append(cubeShadow);
  9506. }
  9507. }
  9508. }
  9509. for (var i = 0; i < s.slides.length; i++) {
  9510. var slide = s.slides.eq(i);
  9511. var slideAngle = i * 90;
  9512. var round = Math.floor(slideAngle / 360);
  9513. if (s.rtl) {
  9514. slideAngle = -slideAngle;
  9515. round = Math.floor(-slideAngle / 360);
  9516. }
  9517. var progress = Math.max(Math.min(slide[0].progress, 1), -1);
  9518. var tx = 0, ty = 0, tz = 0;
  9519. if (i % 4 === 0) {
  9520. tx = - round * 4 * s.size;
  9521. tz = 0;
  9522. }
  9523. else if ((i - 1) % 4 === 0) {
  9524. tx = 0;
  9525. tz = - round * 4 * s.size;
  9526. }
  9527. else if ((i - 2) % 4 === 0) {
  9528. tx = s.size + round * 4 * s.size;
  9529. tz = s.size;
  9530. }
  9531. else if ((i - 3) % 4 === 0) {
  9532. tx = - s.size;
  9533. tz = 3 * s.size + s.size * 4 * round;
  9534. }
  9535. if (s.rtl) {
  9536. tx = -tx;
  9537. }
  9538. if (!isH()) {
  9539. ty = tx;
  9540. tx = 0;
  9541. }
  9542. var transform = 'rotateX(' + (isH() ? 0 : -slideAngle) + 'deg) rotateY(' + (isH() ? slideAngle : 0) + 'deg) translate3d(' + tx + 'px, ' + ty + 'px, ' + tz + 'px)';
  9543. if (progress <= 1 && progress > -1) {
  9544. wrapperRotate = i * 90 + progress * 90;
  9545. if (s.rtl) wrapperRotate = -i * 90 - progress * 90;
  9546. }
  9547. slide.transform(transform);
  9548. if (s.params.cube.slideShadows) {
  9549. //Set shadows
  9550. var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top');
  9551. var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom');
  9552. if (shadowBefore.length === 0) {
  9553. shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>');
  9554. slide.append(shadowBefore);
  9555. }
  9556. if (shadowAfter.length === 0) {
  9557. shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>');
  9558. slide.append(shadowAfter);
  9559. }
  9560. var shadowOpacity = slide[0].progress;
  9561. if (shadowBefore.length) shadowBefore[0].style.opacity = -slide[0].progress;
  9562. if (shadowAfter.length) shadowAfter[0].style.opacity = slide[0].progress;
  9563. }
  9564. }
  9565. s.wrapper.css({
  9566. '-webkit-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9567. '-moz-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9568. '-ms-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9569. 'transform-origin': '50% 50% -' + (s.size / 2) + 'px'
  9570. });
  9571. if (s.params.cube.shadow) {
  9572. if (isH()) {
  9573. cubeShadow.transform('translate3d(0px, ' + (s.width / 2 + s.params.cube.shadowOffset) + 'px, ' + (-s.width / 2) + 'px) rotateX(90deg) rotateZ(0deg) scale(' + (s.params.cube.shadowScale) + ')');
  9574. }
  9575. else {
  9576. var shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90;
  9577. var multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2);
  9578. var scale1 = s.params.cube.shadowScale,
  9579. scale2 = s.params.cube.shadowScale / multiplier,
  9580. offset = s.params.cube.shadowOffset;
  9581. cubeShadow.transform('scale3d(' + scale1 + ', 1, ' + scale2 + ') translate3d(0px, ' + (s.height / 2 + offset) + 'px, ' + (-s.height / 2 / scale2) + 'px) rotateX(-90deg)');
  9582. }
  9583. }
  9584. var zFactor = (s.isSafari || s.isUiWebView) ? (-s.size / 2) : 0;
  9585. s.wrapper.transform('translate3d(0px,0,' + zFactor + 'px) rotateX(' + (isH() ? 0 : wrapperRotate) + 'deg) rotateY(' + (isH() ? -wrapperRotate : 0) + 'deg)');
  9586. },
  9587. setTransition: function (duration) {
  9588. s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);
  9589. if (s.params.cube.shadow && !isH()) {
  9590. s.container.find('.swiper-cube-shadow').transition(duration);
  9591. }
  9592. }
  9593. },
  9594. coverflow: {
  9595. setTranslate: function () {
  9596. var transform = s.translate;
  9597. var center = isH() ? -transform + s.width / 2 : -transform + s.height / 2;
  9598. var rotate = isH() ? s.params.coverflow.rotate: -s.params.coverflow.rotate;
  9599. var translate = s.params.coverflow.depth;
  9600. //Each slide offset from center
  9601. for (var i = 0, length = s.slides.length; i < length; i++) {
  9602. var slide = s.slides.eq(i);
  9603. var slideSize = s.slidesSizesGrid[i];
  9604. var slideOffset = slide[0].swiperSlideOffset;
  9605. var offsetMultiplier = (center - slideOffset - slideSize / 2) / slideSize * s.params.coverflow.modifier;
  9606. var rotateY = isH() ? rotate * offsetMultiplier : 0;
  9607. var rotateX = isH() ? 0 : rotate * offsetMultiplier;
  9608. // var rotateZ = 0
  9609. var translateZ = -translate * Math.abs(offsetMultiplier);
  9610. var translateY = isH() ? 0 : s.params.coverflow.stretch * (offsetMultiplier);
  9611. var translateX = isH() ? s.params.coverflow.stretch * (offsetMultiplier) : 0;
  9612. //Fix for ultra small values
  9613. if (Math.abs(translateX) < 0.001) translateX = 0;
  9614. if (Math.abs(translateY) < 0.001) translateY = 0;
  9615. if (Math.abs(translateZ) < 0.001) translateZ = 0;
  9616. if (Math.abs(rotateY) < 0.001) rotateY = 0;
  9617. if (Math.abs(rotateX) < 0.001) rotateX = 0;
  9618. var slideTransform = 'translate3d(' + translateX + 'px,' + translateY + 'px,' + translateZ + 'px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)';
  9619. slide.transform(slideTransform);
  9620. slide[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1;
  9621. if (s.params.coverflow.slideShadows) {
  9622. //Set shadows
  9623. var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top');
  9624. var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom');
  9625. if (shadowBefore.length === 0) {
  9626. shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>');
  9627. slide.append(shadowBefore);
  9628. }
  9629. if (shadowAfter.length === 0) {
  9630. shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>');
  9631. slide.append(shadowAfter);
  9632. }
  9633. if (shadowBefore.length) shadowBefore[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0;
  9634. if (shadowAfter.length) shadowAfter[0].style.opacity = (-offsetMultiplier) > 0 ? -offsetMultiplier : 0;
  9635. }
  9636. }
  9637. //Set correct perspective for IE10
  9638. if (s.browser.ie) {
  9639. var ws = s.wrapper[0].style;
  9640. ws.perspectiveOrigin = center + 'px 50%';
  9641. }
  9642. },
  9643. setTransition: function (duration) {
  9644. s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);
  9645. }
  9646. }
  9647. };
  9648. /*=========================
  9649. Images Lazy Loading
  9650. ===========================*/
  9651. s.lazy = {
  9652. initialImageLoaded: false,
  9653. loadImageInSlide: function (index, loadInDuplicate) {
  9654. if (typeof index === 'undefined') return;
  9655. if (typeof loadInDuplicate === 'undefined') loadInDuplicate = true;
  9656. if (s.slides.length === 0) return;
  9657. var slide = s.slides.eq(index);
  9658. var img = slide.find('.swiper-lazy:not(.swiper-lazy-loaded):not(.swiper-lazy-loading)');
  9659. if (slide.hasClass('swiper-lazy') && !slide.hasClass('swiper-lazy-loaded') && !slide.hasClass('swiper-lazy-loading')) {
  9660. img = img.add(slide[0]);
  9661. }
  9662. if (img.length === 0) return;
  9663. img.each(function () {
  9664. var _img = $(this);
  9665. _img.addClass('swiper-lazy-loading');
  9666. var background = _img.attr('data-background');
  9667. var src = _img.attr('data-src'),
  9668. srcset = _img.attr('data-srcset');
  9669. s.loadImage(_img[0], (src || background), srcset, false, function () {
  9670. if (background) {
  9671. _img.css('background-image', 'url(' + background + ')');
  9672. _img.removeAttr('data-background');
  9673. }
  9674. else {
  9675. if (srcset) {
  9676. _img.attr('srcset', srcset);
  9677. _img.removeAttr('data-srcset');
  9678. }
  9679. if (src) {
  9680. _img.attr('src', src);
  9681. _img.removeAttr('data-src');
  9682. }
  9683. }
  9684. _img.addClass('swiper-lazy-loaded').removeClass('swiper-lazy-loading');
  9685. slide.find('.swiper-lazy-preloader, .preloader').remove();
  9686. if (s.params.loop && loadInDuplicate) {
  9687. var slideOriginalIndex = slide.attr('data-swiper-slide-index');
  9688. if (slide.hasClass(s.params.slideDuplicateClass)) {
  9689. var originalSlide = s.wrapper.children('[data-swiper-slide-index="' + slideOriginalIndex + '"]:not(.' + s.params.slideDuplicateClass + ')');
  9690. s.lazy.loadImageInSlide(originalSlide.index(), false);
  9691. }
  9692. else {
  9693. var duplicatedSlide = s.wrapper.children('.' + s.params.slideDuplicateClass + '[data-swiper-slide-index="' + slideOriginalIndex + '"]');
  9694. s.lazy.loadImageInSlide(duplicatedSlide.index(), false);
  9695. }
  9696. }
  9697. s.emit('onLazyImageReady', s, slide[0], _img[0]);
  9698. });
  9699. s.emit('onLazyImageLoad', s, slide[0], _img[0]);
  9700. });
  9701. },
  9702. load: function () {
  9703. var i;
  9704. if (s.params.watchSlidesVisibility) {
  9705. s.wrapper.children('.' + s.params.slideVisibleClass).each(function () {
  9706. s.lazy.loadImageInSlide($(this).index());
  9707. });
  9708. }
  9709. else {
  9710. if (s.params.slidesPerView > 1) {
  9711. for (i = s.activeIndex; i < s.activeIndex + s.params.slidesPerView ; i++) {
  9712. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9713. }
  9714. }
  9715. else {
  9716. s.lazy.loadImageInSlide(s.activeIndex);
  9717. }
  9718. }
  9719. if (s.params.lazyLoadingInPrevNext) {
  9720. if (s.params.slidesPerView > 1) {
  9721. // Next Slides
  9722. for (i = s.activeIndex + s.params.slidesPerView; i < s.activeIndex + s.params.slidesPerView + s.params.slidesPerView; i++) {
  9723. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9724. }
  9725. // Prev Slides
  9726. for (i = s.activeIndex - s.params.slidesPerView; i < s.activeIndex ; i++) {
  9727. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9728. }
  9729. }
  9730. else {
  9731. var nextSlide = s.wrapper.children('.' + s.params.slideNextClass);
  9732. if (nextSlide.length > 0) s.lazy.loadImageInSlide(nextSlide.index());
  9733. var prevSlide = s.wrapper.children('.' + s.params.slidePrevClass);
  9734. if (prevSlide.length > 0) s.lazy.loadImageInSlide(prevSlide.index());
  9735. }
  9736. }
  9737. },
  9738. onTransitionStart: function () {
  9739. if (s.params.lazyLoading) {
  9740. if (s.params.lazyLoadingOnTransitionStart || (!s.params.lazyLoadingOnTransitionStart && !s.lazy.initialImageLoaded)) {
  9741. s.lazy.load();
  9742. }
  9743. }
  9744. },
  9745. onTransitionEnd: function () {
  9746. if (s.params.lazyLoading && !s.params.lazyLoadingOnTransitionStart) {
  9747. s.lazy.load();
  9748. }
  9749. }
  9750. };
  9751. /*=========================
  9752. Scrollbar
  9753. ===========================*/
  9754. s.scrollbar = {
  9755. isTouched: false,
  9756. setDragPosition: function (e) {
  9757. var sb = s.scrollbar;
  9758. var x = 0, y = 0;
  9759. var translate;
  9760. var pointerPosition = isH() ?
  9761. ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageX : e.pageX || e.clientX) :
  9762. ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageY : e.pageY || e.clientY) ;
  9763. var position = (pointerPosition) - sb.track.offset()[isH() ? 'left' : 'top'] - sb.dragSize / 2;
  9764. var positionMin = -s.minTranslate() * sb.moveDivider;
  9765. var positionMax = -s.maxTranslate() * sb.moveDivider;
  9766. if (position < positionMin) {
  9767. position = positionMin;
  9768. }
  9769. else if (position > positionMax) {
  9770. position = positionMax;
  9771. }
  9772. position = -position / sb.moveDivider;
  9773. s.updateProgress(position);
  9774. s.setWrapperTranslate(position, true);
  9775. },
  9776. dragStart: function (e) {
  9777. var sb = s.scrollbar;
  9778. sb.isTouched = true;
  9779. e.preventDefault();
  9780. e.stopPropagation();
  9781. sb.setDragPosition(e);
  9782. clearTimeout(sb.dragTimeout);
  9783. sb.track.transition(0);
  9784. if (s.params.scrollbarHide) {
  9785. sb.track.css('opacity', 1);
  9786. }
  9787. s.wrapper.transition(100);
  9788. sb.drag.transition(100);
  9789. s.emit('onScrollbarDragStart', s);
  9790. },
  9791. dragMove: function (e) {
  9792. var sb = s.scrollbar;
  9793. if (!sb.isTouched) return;
  9794. if (e.preventDefault) e.preventDefault();
  9795. else e.returnValue = false;
  9796. sb.setDragPosition(e);
  9797. s.wrapper.transition(0);
  9798. sb.track.transition(0);
  9799. sb.drag.transition(0);
  9800. s.emit('onScrollbarDragMove', s);
  9801. },
  9802. dragEnd: function (e) {
  9803. var sb = s.scrollbar;
  9804. if (!sb.isTouched) return;
  9805. sb.isTouched = false;
  9806. if (s.params.scrollbarHide) {
  9807. clearTimeout(sb.dragTimeout);
  9808. sb.dragTimeout = setTimeout(function () {
  9809. sb.track.css('opacity', 0);
  9810. sb.track.transition(400);
  9811. }, 1000);
  9812. }
  9813. s.emit('onScrollbarDragEnd', s);
  9814. if (s.params.scrollbarSnapOnRelease) {
  9815. s.slideReset();
  9816. }
  9817. },
  9818. enableDraggable: function () {
  9819. var sb = s.scrollbar;
  9820. var target = s.support.touch ? sb.track : document;
  9821. $(sb.track).on(s.touchEvents.start, sb.dragStart);
  9822. $(target).on(s.touchEvents.move, sb.dragMove);
  9823. $(target).on(s.touchEvents.end, sb.dragEnd);
  9824. },
  9825. disableDraggable: function () {
  9826. var sb = s.scrollbar;
  9827. var target = s.support.touch ? sb.track : document;
  9828. $(sb.track).off(s.touchEvents.start, sb.dragStart);
  9829. $(target).off(s.touchEvents.move, sb.dragMove);
  9830. $(target).off(s.touchEvents.end, sb.dragEnd);
  9831. },
  9832. set: function () {
  9833. if (!s.params.scrollbar) return;
  9834. var sb = s.scrollbar;
  9835. sb.track = $(s.params.scrollbar);
  9836. sb.drag = sb.track.find('.swiper-scrollbar-drag');
  9837. if (sb.drag.length === 0) {
  9838. sb.drag = $('<div class="swiper-scrollbar-drag"></div>');
  9839. sb.track.append(sb.drag);
  9840. }
  9841. sb.drag[0].style.width = '';
  9842. sb.drag[0].style.height = '';
  9843. sb.trackSize = isH() ? sb.track[0].offsetWidth : sb.track[0].offsetHeight;
  9844. sb.divider = s.size / s.virtualSize;
  9845. sb.moveDivider = sb.divider * (sb.trackSize / s.size);
  9846. sb.dragSize = sb.trackSize * sb.divider;
  9847. if (isH()) {
  9848. sb.drag[0].style.width = sb.dragSize + 'px';
  9849. }
  9850. else {
  9851. sb.drag[0].style.height = sb.dragSize + 'px';
  9852. }
  9853. if (sb.divider >= 1) {
  9854. sb.track[0].style.display = 'none';
  9855. }
  9856. else {
  9857. sb.track[0].style.display = '';
  9858. }
  9859. if (s.params.scrollbarHide) {
  9860. sb.track[0].style.opacity = 0;
  9861. }
  9862. },
  9863. setTranslate: function () {
  9864. if (!s.params.scrollbar) return;
  9865. var diff;
  9866. var sb = s.scrollbar;
  9867. var translate = s.translate || 0;
  9868. var newPos;
  9869. var newSize = sb.dragSize;
  9870. newPos = (sb.trackSize - sb.dragSize) * s.progress;
  9871. if (s.rtl && isH()) {
  9872. newPos = -newPos;
  9873. if (newPos > 0) {
  9874. newSize = sb.dragSize - newPos;
  9875. newPos = 0;
  9876. }
  9877. else if (-newPos + sb.dragSize > sb.trackSize) {
  9878. newSize = sb.trackSize + newPos;
  9879. }
  9880. }
  9881. else {
  9882. if (newPos < 0) {
  9883. newSize = sb.dragSize + newPos;
  9884. newPos = 0;
  9885. }
  9886. else if (newPos + sb.dragSize > sb.trackSize) {
  9887. newSize = sb.trackSize - newPos;
  9888. }
  9889. }
  9890. if (isH()) {
  9891. if (s.support.transforms3d) {
  9892. sb.drag.transform('translate3d(' + (newPos) + 'px, 0, 0)');
  9893. }
  9894. else {
  9895. sb.drag.transform('translateX(' + (newPos) + 'px)');
  9896. }
  9897. sb.drag[0].style.width = newSize + 'px';
  9898. }
  9899. else {
  9900. if (s.support.transforms3d) {
  9901. sb.drag.transform('translate3d(0px, ' + (newPos) + 'px, 0)');
  9902. }
  9903. else {
  9904. sb.drag.transform('translateY(' + (newPos) + 'px)');
  9905. }
  9906. sb.drag[0].style.height = newSize + 'px';
  9907. }
  9908. if (s.params.scrollbarHide) {
  9909. clearTimeout(sb.timeout);
  9910. sb.track[0].style.opacity = 1;
  9911. sb.timeout = setTimeout(function () {
  9912. sb.track[0].style.opacity = 0;
  9913. sb.track.transition(400);
  9914. }, 1000);
  9915. }
  9916. },
  9917. setTransition: function (duration) {
  9918. if (!s.params.scrollbar) return;
  9919. s.scrollbar.drag.transition(duration);
  9920. }
  9921. };
  9922. /*=========================
  9923. Controller
  9924. ===========================*/
  9925. s.controller = {
  9926. LinearSpline: function (x, y) {
  9927. this.x = x;
  9928. this.y = y;
  9929. this.lastIndex = x.length - 1;
  9930. // Given an x value (x2), return the expected y2 value:
  9931. // (x1,y1) is the known point before given value,
  9932. // (x3,y3) is the known point after given value.
  9933. var i1, i3;
  9934. var l = this.x.length;
  9935. this.interpolate = function (x2) {
  9936. if (!x2) return 0;
  9937. // Get the indexes of x1 and x3 (the array indexes before and after given x2):
  9938. i3 = binarySearch(this.x, x2);
  9939. i1 = i3 - 1;
  9940. // We have our indexes i1 & i3, so we can calculate already:
  9941. // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1
  9942. return ((x2 - this.x[i1]) * (this.y[i3] - this.y[i1])) / (this.x[i3] - this.x[i1]) + this.y[i1];
  9943. };
  9944. var binarySearch = (function() {
  9945. var maxIndex, minIndex, guess;
  9946. return function(array, val) {
  9947. minIndex = -1;
  9948. maxIndex = array.length;
  9949. while (maxIndex - minIndex > 1)
  9950. if (array[guess = maxIndex + minIndex >> 1] <= val) {
  9951. minIndex = guess;
  9952. } else {
  9953. maxIndex = guess;
  9954. }
  9955. return maxIndex;
  9956. };
  9957. })();
  9958. },
  9959. //xxx: for now i will just save one spline function to to
  9960. getInterpolateFunction: function(c){
  9961. if(!s.controller.spline) s.controller.spline = s.params.loop ?
  9962. new s.controller.LinearSpline(s.slidesGrid, c.slidesGrid) :
  9963. new s.controller.LinearSpline(s.snapGrid, c.snapGrid);
  9964. },
  9965. setTranslate: function (translate, byController) {
  9966. var controlled = s.params.control;
  9967. var multiplier, controlledTranslate;
  9968. function setControlledTranslate(c) {
  9969. // this will create an Interpolate function based on the snapGrids
  9970. // x is the Grid of the scrolled scroller and y will be the controlled scroller
  9971. // it makes sense to create this only once and recall it for the interpolation
  9972. // the function does a lot of value caching for performance
  9973. translate = c.rtl && c.params.direction === 'horizontal' ? -s.translate : s.translate;
  9974. if (s.params.controlBy === 'slide') {
  9975. s.controller.getInterpolateFunction(c);
  9976. // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid
  9977. // but it did not work out
  9978. controlledTranslate = -s.controller.spline.interpolate(-translate);
  9979. }
  9980. if(!controlledTranslate || s.params.controlBy === 'container'){
  9981. multiplier = (c.maxTranslate() - c.minTranslate()) / (s.maxTranslate() - s.minTranslate());
  9982. controlledTranslate = (translate - s.minTranslate()) * multiplier + c.minTranslate();
  9983. }
  9984. if (s.params.controlInverse) {
  9985. controlledTranslate = c.maxTranslate() - controlledTranslate;
  9986. }
  9987. c.updateProgress(controlledTranslate);
  9988. c.setWrapperTranslate(controlledTranslate, false, s);
  9989. c.updateActiveIndex();
  9990. }
  9991. if (s.isArray(controlled)) {
  9992. for (var i = 0; i < controlled.length; i++) {
  9993. if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
  9994. setControlledTranslate(controlled[i]);
  9995. }
  9996. }
  9997. }
  9998. else if (controlled instanceof Swiper && byController !== controlled) {
  9999. setControlledTranslate(controlled);
  10000. }
  10001. },
  10002. setTransition: function (duration, byController) {
  10003. var controlled = s.params.control;
  10004. var i;
  10005. function setControlledTransition(c) {
  10006. c.setWrapperTransition(duration, s);
  10007. if (duration !== 0) {
  10008. c.onTransitionStart();
  10009. c.wrapper.transitionEnd(function(){
  10010. if (!controlled) return;
  10011. if (c.params.loop && s.params.controlBy === 'slide') {
  10012. c.fixLoop();
  10013. }
  10014. c.onTransitionEnd();
  10015. });
  10016. }
  10017. }
  10018. if (s.isArray(controlled)) {
  10019. for (i = 0; i < controlled.length; i++) {
  10020. if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
  10021. setControlledTransition(controlled[i]);
  10022. }
  10023. }
  10024. }
  10025. else if (controlled instanceof Swiper && byController !== controlled) {
  10026. setControlledTransition(controlled);
  10027. }
  10028. }
  10029. };
  10030. /*=========================
  10031. Hash Navigation
  10032. ===========================*/
  10033. s.hashnav = {
  10034. init: function () {
  10035. if (!s.params.hashnav) return;
  10036. s.hashnav.initialized = true;
  10037. var hash = document.location.hash.replace('#', '');
  10038. if (!hash) return;
  10039. var speed = 0;
  10040. for (var i = 0, length = s.slides.length; i < length; i++) {
  10041. var slide = s.slides.eq(i);
  10042. var slideHash = slide.attr('data-hash');
  10043. if (slideHash === hash && !slide.hasClass(s.params.slideDuplicateClass)) {
  10044. var index = slide.index();
  10045. s.slideTo(index, speed, s.params.runCallbacksOnInit, true);
  10046. }
  10047. }
  10048. },
  10049. setHash: function () {
  10050. if (!s.hashnav.initialized || !s.params.hashnav) return;
  10051. document.location.hash = s.slides.eq(s.activeIndex).attr('data-hash') || '';
  10052. }
  10053. };
  10054. /*=========================
  10055. Keyboard Control
  10056. ===========================*/
  10057. function handleKeyboard(e) {
  10058. if (e.originalEvent) e = e.originalEvent; //jquery fix
  10059. var kc = e.keyCode || e.charCode;
  10060. // Directions locks
  10061. if (!s.params.allowSwipeToNext && (isH() && kc === 39 || !isH() && kc === 40)) {
  10062. return false;
  10063. }
  10064. if (!s.params.allowSwipeToPrev && (isH() && kc === 37 || !isH() && kc === 38)) {
  10065. return false;
  10066. }
  10067. if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) {
  10068. return;
  10069. }
  10070. if (document.activeElement && document.activeElement.nodeName && (document.activeElement.nodeName.toLowerCase() === 'input' || document.activeElement.nodeName.toLowerCase() === 'textarea')) {
  10071. return;
  10072. }
  10073. if (kc === 37 || kc === 39 || kc === 38 || kc === 40) {
  10074. var inView = false;
  10075. //Check that swiper should be inside of visible area of window
  10076. if (s.container.parents('.swiper-slide').length > 0 && s.container.parents('.swiper-slide-active').length === 0) {
  10077. return;
  10078. }
  10079. var windowScroll = {
  10080. left: window.pageXOffset,
  10081. top: window.pageYOffset
  10082. };
  10083. var windowWidth = window.innerWidth;
  10084. var windowHeight = window.innerHeight;
  10085. var swiperOffset = s.container.offset();
  10086. if (s.rtl) swiperOffset.left = swiperOffset.left - s.container[0].scrollLeft;
  10087. var swiperCoord = [
  10088. [swiperOffset.left, swiperOffset.top],
  10089. [swiperOffset.left + s.width, swiperOffset.top],
  10090. [swiperOffset.left, swiperOffset.top + s.height],
  10091. [swiperOffset.left + s.width, swiperOffset.top + s.height]
  10092. ];
  10093. for (var i = 0; i < swiperCoord.length; i++) {
  10094. var point = swiperCoord[i];
  10095. if (
  10096. point[0] >= windowScroll.left && point[0] <= windowScroll.left + windowWidth &&
  10097. point[1] >= windowScroll.top && point[1] <= windowScroll.top + windowHeight
  10098. ) {
  10099. inView = true;
  10100. }
  10101. }
  10102. if (!inView) return;
  10103. }
  10104. if (isH()) {
  10105. if (kc === 37 || kc === 39) {
  10106. if (e.preventDefault) e.preventDefault();
  10107. else e.returnValue = false;
  10108. }
  10109. if ((kc === 39 && !s.rtl) || (kc === 37 && s.rtl)) s.slideNext();
  10110. if ((kc === 37 && !s.rtl) || (kc === 39 && s.rtl)) s.slidePrev();
  10111. }
  10112. else {
  10113. if (kc === 38 || kc === 40) {
  10114. if (e.preventDefault) e.preventDefault();
  10115. else e.returnValue = false;
  10116. }
  10117. if (kc === 40) s.slideNext();
  10118. if (kc === 38) s.slidePrev();
  10119. }
  10120. }
  10121. s.disableKeyboardControl = function () {
  10122. s.params.keyboardControl = false;
  10123. $(document).off('keydown', handleKeyboard);
  10124. };
  10125. s.enableKeyboardControl = function () {
  10126. s.params.keyboardControl = true;
  10127. $(document).on('keydown', handleKeyboard);
  10128. };
  10129. /*=========================
  10130. Mousewheel Control
  10131. ===========================*/
  10132. s.mousewheel = {
  10133. event: false,
  10134. lastScrollTime: (new window.Date()).getTime()
  10135. };
  10136. if (s.params.mousewheelControl) {
  10137. try {
  10138. new window.WheelEvent('wheel');
  10139. s.mousewheel.event = 'wheel';
  10140. } catch (e) {}
  10141. if (!s.mousewheel.event && document.onmousewheel !== undefined) {
  10142. s.mousewheel.event = 'mousewheel';
  10143. }
  10144. if (!s.mousewheel.event) {
  10145. s.mousewheel.event = 'DOMMouseScroll';
  10146. }
  10147. }
  10148. function handleMousewheel(e) {
  10149. if (e.originalEvent) e = e.originalEvent; //jquery fix
  10150. var we = s.mousewheel.event;
  10151. var delta = 0;
  10152. var rtlFactor = s.rtl ? -1 : 1;
  10153. //Opera & IE
  10154. if (e.detail) delta = -e.detail;
  10155. //WebKits
  10156. else if (we === 'mousewheel') {
  10157. if (s.params.mousewheelForceToAxis) {
  10158. if (isH()) {
  10159. if (Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY)) delta = e.wheelDeltaX * rtlFactor;
  10160. else return;
  10161. }
  10162. else {
  10163. if (Math.abs(e.wheelDeltaY) > Math.abs(e.wheelDeltaX)) delta = e.wheelDeltaY;
  10164. else return;
  10165. }
  10166. }
  10167. else {
  10168. delta = Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY) ? - e.wheelDeltaX * rtlFactor : - e.wheelDeltaY;
  10169. }
  10170. }
  10171. //Old FireFox
  10172. else if (we === 'DOMMouseScroll') delta = -e.detail;
  10173. //New FireFox
  10174. else if (we === 'wheel') {
  10175. if (s.params.mousewheelForceToAxis) {
  10176. if (isH()) {
  10177. if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) delta = -e.deltaX * rtlFactor;
  10178. else return;
  10179. }
  10180. else {
  10181. if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) delta = -e.deltaY;
  10182. else return;
  10183. }
  10184. }
  10185. else {
  10186. delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? - e.deltaX * rtlFactor : - e.deltaY;
  10187. }
  10188. }
  10189. if (delta === 0) return;
  10190. if (s.params.mousewheelInvert) delta = -delta;
  10191. if (!s.params.freeMode) {
  10192. if ((new window.Date()).getTime() - s.mousewheel.lastScrollTime > 60) {
  10193. if (delta < 0) {
  10194. if ((!s.isEnd || s.params.loop) && !s.animating) s.slideNext();
  10195. else if (s.params.mousewheelReleaseOnEdges) return true;
  10196. }
  10197. else {
  10198. if ((!s.isBeginning || s.params.loop) && !s.animating) s.slidePrev();
  10199. else if (s.params.mousewheelReleaseOnEdges) return true;
  10200. }
  10201. }
  10202. s.mousewheel.lastScrollTime = (new window.Date()).getTime();
  10203. }
  10204. else {
  10205. //Freemode or scrollContainer:
  10206. var position = s.getWrapperTranslate() + delta * s.params.mousewheelSensitivity;
  10207. var wasBeginning = s.isBeginning,
  10208. wasEnd = s.isEnd;
  10209. if (position >= s.minTranslate()) position = s.minTranslate();
  10210. if (position <= s.maxTranslate()) position = s.maxTranslate();
  10211. s.setWrapperTransition(0);
  10212. s.setWrapperTranslate(position);
  10213. s.updateProgress();
  10214. s.updateActiveIndex();
  10215. if (!wasBeginning && s.isBeginning || !wasEnd && s.isEnd) {
  10216. s.updateClasses();
  10217. }
  10218. if (s.params.freeModeSticky) {
  10219. clearTimeout(s.mousewheel.timeout);
  10220. s.mousewheel.timeout = setTimeout(function () {
  10221. s.slideReset();
  10222. }, 300);
  10223. }
  10224. // Return page scroll on edge positions
  10225. if (position === 0 || position === s.maxTranslate()) return;
  10226. }
  10227. if (s.params.autoplay) s.stopAutoplay();
  10228. if (e.preventDefault) e.preventDefault();
  10229. else e.returnValue = false;
  10230. return false;
  10231. }
  10232. s.disableMousewheelControl = function () {
  10233. if (!s.mousewheel.event) return false;
  10234. s.container.off(s.mousewheel.event, handleMousewheel);
  10235. return true;
  10236. };
  10237. s.enableMousewheelControl = function () {
  10238. if (!s.mousewheel.event) return false;
  10239. s.container.on(s.mousewheel.event, handleMousewheel);
  10240. return true;
  10241. };
  10242. /*=========================
  10243. Parallax
  10244. ===========================*/
  10245. function setParallaxTransform(el, progress) {
  10246. el = $(el);
  10247. var p, pX, pY;
  10248. var rtlFactor = s.rtl ? -1 : 1;
  10249. p = el.attr('data-swiper-parallax') || '0';
  10250. pX = el.attr('data-swiper-parallax-x');
  10251. pY = el.attr('data-swiper-parallax-y');
  10252. if (pX || pY) {
  10253. pX = pX || '0';
  10254. pY = pY || '0';
  10255. }
  10256. else {
  10257. if (isH()) {
  10258. pX = p;
  10259. pY = '0';
  10260. }
  10261. else {
  10262. pY = p;
  10263. pX = '0';
  10264. }
  10265. }
  10266. if ((pX).indexOf('%') >= 0) {
  10267. pX = parseInt(pX, 10) * progress * rtlFactor + '%';
  10268. }
  10269. else {
  10270. pX = pX * progress * rtlFactor + 'px' ;
  10271. }
  10272. if ((pY).indexOf('%') >= 0) {
  10273. pY = parseInt(pY, 10) * progress + '%';
  10274. }
  10275. else {
  10276. pY = pY * progress + 'px' ;
  10277. }
  10278. el.transform('translate3d(' + pX + ', ' + pY + ',0px)');
  10279. }
  10280. s.parallax = {
  10281. setTranslate: function () {
  10282. s.container.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){
  10283. setParallaxTransform(this, s.progress);
  10284. });
  10285. s.slides.each(function () {
  10286. var slide = $(this);
  10287. slide.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function () {
  10288. var progress = Math.min(Math.max(slide[0].progress, -1), 1);
  10289. setParallaxTransform(this, progress);
  10290. });
  10291. });
  10292. },
  10293. setTransition: function (duration) {
  10294. if (typeof duration === 'undefined') duration = s.params.speed;
  10295. s.container.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){
  10296. var el = $(this);
  10297. var parallaxDuration = parseInt(el.attr('data-swiper-parallax-duration'), 10) || duration;
  10298. if (duration === 0) parallaxDuration = 0;
  10299. el.transition(parallaxDuration);
  10300. });
  10301. }
  10302. };
  10303. /*=========================
  10304. Plugins API. Collect all and init all plugins
  10305. ===========================*/
  10306. s._plugins = [];
  10307. for (var plugin in s.plugins) {
  10308. var p = s.plugins[plugin](s, s.params[plugin]);
  10309. if (p) s._plugins.push(p);
  10310. }
  10311. // Method to call all plugins event/method
  10312. s.callPlugins = function (eventName) {
  10313. for (var i = 0; i < s._plugins.length; i++) {
  10314. if (eventName in s._plugins[i]) {
  10315. s._plugins[i][eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10316. }
  10317. }
  10318. };
  10319. /*=========================
  10320. Events/Callbacks/Plugins Emitter
  10321. ===========================*/
  10322. function normalizeEventName (eventName) {
  10323. if (eventName.indexOf('on') !== 0) {
  10324. if (eventName[0] !== eventName[0].toUpperCase()) {
  10325. eventName = 'on' + eventName[0].toUpperCase() + eventName.substring(1);
  10326. }
  10327. else {
  10328. eventName = 'on' + eventName;
  10329. }
  10330. }
  10331. return eventName;
  10332. }
  10333. s.emitterEventListeners = {
  10334. };
  10335. s.emit = function (eventName) {
  10336. // Trigger callbacks
  10337. if (s.params[eventName]) {
  10338. s.params[eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10339. }
  10340. var i;
  10341. // Trigger events
  10342. if (s.emitterEventListeners[eventName]) {
  10343. for (i = 0; i < s.emitterEventListeners[eventName].length; i++) {
  10344. s.emitterEventListeners[eventName][i](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10345. }
  10346. }
  10347. // Trigger plugins
  10348. if (s.callPlugins) s.callPlugins(eventName, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10349. };
  10350. s.on = function (eventName, handler) {
  10351. eventName = normalizeEventName(eventName);
  10352. if (!s.emitterEventListeners[eventName]) s.emitterEventListeners[eventName] = [];
  10353. s.emitterEventListeners[eventName].push(handler);
  10354. return s;
  10355. };
  10356. s.off = function (eventName, handler) {
  10357. var i;
  10358. eventName = normalizeEventName(eventName);
  10359. if (typeof handler === 'undefined') {
  10360. // Remove all handlers for such event
  10361. s.emitterEventListeners[eventName] = [];
  10362. return s;
  10363. }
  10364. if (!s.emitterEventListeners[eventName] || s.emitterEventListeners[eventName].length === 0) return;
  10365. for (i = 0; i < s.emitterEventListeners[eventName].length; i++) {
  10366. if(s.emitterEventListeners[eventName][i] === handler) s.emitterEventListeners[eventName].splice(i, 1);
  10367. }
  10368. return s;
  10369. };
  10370. s.once = function (eventName, handler) {
  10371. eventName = normalizeEventName(eventName);
  10372. var _handler = function () {
  10373. handler(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
  10374. s.off(eventName, _handler);
  10375. };
  10376. s.on(eventName, _handler);
  10377. return s;
  10378. };
  10379. // Accessibility tools
  10380. s.a11y = {
  10381. makeFocusable: function ($el) {
  10382. $el.attr('tabIndex', '0');
  10383. return $el;
  10384. },
  10385. addRole: function ($el, role) {
  10386. $el.attr('role', role);
  10387. return $el;
  10388. },
  10389. addLabel: function ($el, label) {
  10390. $el.attr('aria-label', label);
  10391. return $el;
  10392. },
  10393. disable: function ($el) {
  10394. $el.attr('aria-disabled', true);
  10395. return $el;
  10396. },
  10397. enable: function ($el) {
  10398. $el.attr('aria-disabled', false);
  10399. return $el;
  10400. },
  10401. onEnterKey: function (event) {
  10402. if (event.keyCode !== 13) return;
  10403. if ($(event.target).is(s.params.nextButton)) {
  10404. s.onClickNext(event);
  10405. if (s.isEnd) {
  10406. s.a11y.notify(s.params.lastSlideMessage);
  10407. }
  10408. else {
  10409. s.a11y.notify(s.params.nextSlideMessage);
  10410. }
  10411. }
  10412. else if ($(event.target).is(s.params.prevButton)) {
  10413. s.onClickPrev(event);
  10414. if (s.isBeginning) {
  10415. s.a11y.notify(s.params.firstSlideMessage);
  10416. }
  10417. else {
  10418. s.a11y.notify(s.params.prevSlideMessage);
  10419. }
  10420. }
  10421. if ($(event.target).is('.' + s.params.bulletClass)) {
  10422. $(event.target)[0].click();
  10423. }
  10424. },
  10425. liveRegion: $('<span class="swiper-notification" aria-live="assertive" aria-atomic="true"></span>'),
  10426. notify: function (message) {
  10427. var notification = s.a11y.liveRegion;
  10428. if (notification.length === 0) return;
  10429. notification.html('');
  10430. notification.html(message);
  10431. },
  10432. init: function () {
  10433. // Setup accessibility
  10434. if (s.params.nextButton) {
  10435. var nextButton = $(s.params.nextButton);
  10436. s.a11y.makeFocusable(nextButton);
  10437. s.a11y.addRole(nextButton, 'button');
  10438. s.a11y.addLabel(nextButton, s.params.nextSlideMessage);
  10439. }
  10440. if (s.params.prevButton) {
  10441. var prevButton = $(s.params.prevButton);
  10442. s.a11y.makeFocusable(prevButton);
  10443. s.a11y.addRole(prevButton, 'button');
  10444. s.a11y.addLabel(prevButton, s.params.prevSlideMessage);
  10445. }
  10446. $(s.container).append(s.a11y.liveRegion);
  10447. },
  10448. initPagination: function () {
  10449. if (s.params.pagination && s.params.paginationClickable && s.bullets && s.bullets.length) {
  10450. s.bullets.each(function () {
  10451. var bullet = $(this);
  10452. s.a11y.makeFocusable(bullet);
  10453. s.a11y.addRole(bullet, 'button');
  10454. s.a11y.addLabel(bullet, s.params.paginationBulletMessage.replace(/{{index}}/, bullet.index() + 1));
  10455. });
  10456. }
  10457. },
  10458. destroy: function () {
  10459. if (s.a11y.liveRegion && s.a11y.liveRegion.length > 0) s.a11y.liveRegion.remove();
  10460. }
  10461. };
  10462. /*=========================
  10463. Init/Destroy
  10464. ===========================*/
  10465. s.init = function () {
  10466. if (s.params.loop) s.createLoop();
  10467. s.updateContainerSize();
  10468. s.updateSlidesSize();
  10469. s.updatePagination();
  10470. if (s.params.scrollbar && s.scrollbar) {
  10471. s.scrollbar.set();
  10472. if (s.params.scrollbarDraggable) {
  10473. s.scrollbar.enableDraggable();
  10474. }
  10475. }
  10476. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  10477. if (!s.params.loop) s.updateProgress();
  10478. s.effects[s.params.effect].setTranslate();
  10479. }
  10480. if (s.params.loop) {
  10481. s.slideTo(s.params.initialSlide + s.loopedSlides, 0, s.params.runCallbacksOnInit);
  10482. }
  10483. else {
  10484. s.slideTo(s.params.initialSlide, 0, s.params.runCallbacksOnInit);
  10485. if (s.params.initialSlide === 0) {
  10486. if (s.parallax && s.params.parallax) s.parallax.setTranslate();
  10487. if (s.lazy && s.params.lazyLoading) {
  10488. s.lazy.load();
  10489. s.lazy.initialImageLoaded = true;
  10490. }
  10491. }
  10492. }
  10493. s.attachEvents();
  10494. if (s.params.observer && s.support.observer) {
  10495. s.initObservers();
  10496. }
  10497. if (s.params.preloadImages && !s.params.lazyLoading) {
  10498. s.preloadImages();
  10499. }
  10500. if (s.params.autoplay) {
  10501. s.startAutoplay();
  10502. }
  10503. if (s.params.keyboardControl) {
  10504. if (s.enableKeyboardControl) s.enableKeyboardControl();
  10505. }
  10506. if (s.params.mousewheelControl) {
  10507. if (s.enableMousewheelControl) s.enableMousewheelControl();
  10508. }
  10509. if (s.params.hashnav) {
  10510. if (s.hashnav) s.hashnav.init();
  10511. }
  10512. if (s.params.a11y && s.a11y) s.a11y.init();
  10513. s.emit('onInit', s);
  10514. };
  10515. // Cleanup dynamic styles
  10516. s.cleanupStyles = function () {
  10517. // Container
  10518. s.container.removeClass(s.classNames.join(' ')).removeAttr('style');
  10519. // Wrapper
  10520. s.wrapper.removeAttr('style');
  10521. // Slides
  10522. if (s.slides && s.slides.length) {
  10523. s.slides
  10524. .removeClass([
  10525. s.params.slideVisibleClass,
  10526. s.params.slideActiveClass,
  10527. s.params.slideNextClass,
  10528. s.params.slidePrevClass
  10529. ].join(' '))
  10530. .removeAttr('style')
  10531. .removeAttr('data-swiper-column')
  10532. .removeAttr('data-swiper-row');
  10533. }
  10534. // Pagination/Bullets
  10535. if (s.paginationContainer && s.paginationContainer.length) {
  10536. s.paginationContainer.removeClass(s.params.paginationHiddenClass);
  10537. }
  10538. if (s.bullets && s.bullets.length) {
  10539. s.bullets.removeClass(s.params.bulletActiveClass);
  10540. }
  10541. // Buttons
  10542. if (s.params.prevButton) $(s.params.prevButton).removeClass(s.params.buttonDisabledClass);
  10543. if (s.params.nextButton) $(s.params.nextButton).removeClass(s.params.buttonDisabledClass);
  10544. // Scrollbar
  10545. if (s.params.scrollbar && s.scrollbar) {
  10546. if (s.scrollbar.track && s.scrollbar.track.length) s.scrollbar.track.removeAttr('style');
  10547. if (s.scrollbar.drag && s.scrollbar.drag.length) s.scrollbar.drag.removeAttr('style');
  10548. }
  10549. };
  10550. // Destroy
  10551. s.destroy = function (deleteInstance, cleanupStyles) {
  10552. // Detach evebts
  10553. s.detachEvents();
  10554. // Stop autoplay
  10555. s.stopAutoplay();
  10556. // Disable draggable
  10557. if (s.params.scrollbar && s.scrollbar) {
  10558. if (s.params.scrollbarDraggable) {
  10559. s.scrollbar.disableDraggable();
  10560. }
  10561. }
  10562. // Destroy loop
  10563. if (s.params.loop) {
  10564. s.destroyLoop();
  10565. }
  10566. // Cleanup styles
  10567. if (cleanupStyles) {
  10568. s.cleanupStyles();
  10569. }
  10570. // Disconnect observer
  10571. s.disconnectObservers();
  10572. // Disable keyboard/mousewheel
  10573. if (s.params.keyboardControl) {
  10574. if (s.disableKeyboardControl) s.disableKeyboardControl();
  10575. }
  10576. if (s.params.mousewheelControl) {
  10577. if (s.disableMousewheelControl) s.disableMousewheelControl();
  10578. }
  10579. // Disable a11y
  10580. if (s.params.a11y && s.a11y) s.a11y.destroy();
  10581. // Destroy callback
  10582. s.emit('onDestroy');
  10583. // Delete instance
  10584. if (deleteInstance !== false) s = null;
  10585. };
  10586. s.init();
  10587. // Return swiper instance
  10588. return s;
  10589. };
  10590. /*==================================================
  10591. Prototype
  10592. ====================================================*/
  10593. Swiper.prototype = {
  10594. isSafari: (function () {
  10595. var ua = navigator.userAgent.toLowerCase();
  10596. return (ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0);
  10597. })(),
  10598. isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent),
  10599. isArray: function (arr) {
  10600. return Object.prototype.toString.apply(arr) === '[object Array]';
  10601. },
  10602. /*==================================================
  10603. Browser
  10604. ====================================================*/
  10605. browser: {
  10606. ie: window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
  10607. ieTouch: (window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 1) || (window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 1)
  10608. },
  10609. /*==================================================
  10610. Devices
  10611. ====================================================*/
  10612. device: (function () {
  10613. var ua = navigator.userAgent;
  10614. var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  10615. var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  10616. var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  10617. var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  10618. return {
  10619. ios: ipad || iphone || ipod,
  10620. android: android
  10621. };
  10622. })(),
  10623. /*==================================================
  10624. Feature Detection
  10625. ====================================================*/
  10626. support: {
  10627. touch : (window.Modernizr && Modernizr.touch === true) || (function () {
  10628. return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
  10629. })(),
  10630. transforms3d : (window.Modernizr && Modernizr.csstransforms3d === true) || (function () {
  10631. var div = document.createElement('div').style;
  10632. return ('webkitPerspective' in div || 'MozPerspective' in div || 'OPerspective' in div || 'MsPerspective' in div || 'perspective' in div);
  10633. })(),
  10634. flexbox: (function () {
  10635. var div = document.createElement('div').style;
  10636. var styles = ('alignItems webkitAlignItems webkitBoxAlign msFlexAlign mozBoxAlign webkitFlexDirection msFlexDirection mozBoxDirection mozBoxOrient webkitBoxDirection webkitBoxOrient').split(' ');
  10637. for (var i = 0; i < styles.length; i++) {
  10638. if (styles[i] in div) return true;
  10639. }
  10640. })(),
  10641. observer: (function () {
  10642. return ('MutationObserver' in window || 'WebkitMutationObserver' in window);
  10643. })()
  10644. },
  10645. /*==================================================
  10646. Plugins
  10647. ====================================================*/
  10648. plugins: {}
  10649. };
  10650. /*===========================
  10651. Dom7 Library
  10652. ===========================*/
  10653. var Dom7 = (function () {
  10654. var Dom7 = function (arr) {
  10655. var _this = this, i = 0;
  10656. // Create array-like object
  10657. for (i = 0; i < arr.length; i++) {
  10658. _this[i] = arr[i];
  10659. }
  10660. _this.length = arr.length;
  10661. // Return collection with methods
  10662. return this;
  10663. };
  10664. var $ = function (selector, context) {
  10665. var arr = [], i = 0;
  10666. if (selector && !context) {
  10667. if (selector instanceof Dom7) {
  10668. return selector;
  10669. }
  10670. }
  10671. if (selector) {
  10672. // String
  10673. if (typeof selector === 'string') {
  10674. var els, tempParent, html = selector.trim();
  10675. if (html.indexOf('<') >= 0 && html.indexOf('>') >= 0) {
  10676. var toCreate = 'div';
  10677. if (html.indexOf('<li') === 0) toCreate = 'ul';
  10678. if (html.indexOf('<tr') === 0) toCreate = 'tbody';
  10679. if (html.indexOf('<td') === 0 || html.indexOf('<th') === 0) toCreate = 'tr';
  10680. if (html.indexOf('<tbody') === 0) toCreate = 'table';
  10681. if (html.indexOf('<option') === 0) toCreate = 'select';
  10682. tempParent = document.createElement(toCreate);
  10683. tempParent.innerHTML = selector;
  10684. for (i = 0; i < tempParent.childNodes.length; i++) {
  10685. arr.push(tempParent.childNodes[i]);
  10686. }
  10687. }
  10688. else {
  10689. if (!context && selector[0] === '#' && !selector.match(/[ .<>:~]/)) {
  10690. // Pure ID selector
  10691. els = [document.getElementById(selector.split('#')[1])];
  10692. }
  10693. else {
  10694. // Other selectors
  10695. els = (context || document).querySelectorAll(selector);
  10696. }
  10697. for (i = 0; i < els.length; i++) {
  10698. if (els[i]) arr.push(els[i]);
  10699. }
  10700. }
  10701. }
  10702. // Node/element
  10703. else if (selector.nodeType || selector === window || selector === document) {
  10704. arr.push(selector);
  10705. }
  10706. //Array of elements or instance of Dom
  10707. else if (selector.length > 0 && selector[0].nodeType) {
  10708. for (i = 0; i < selector.length; i++) {
  10709. arr.push(selector[i]);
  10710. }
  10711. }
  10712. }
  10713. return new Dom7(arr);
  10714. };
  10715. Dom7.prototype = {
  10716. // Classes and attriutes
  10717. addClass: function (className) {
  10718. if (typeof className === 'undefined') {
  10719. return this;
  10720. }
  10721. var classes = className.split(' ');
  10722. for (var i = 0; i < classes.length; i++) {
  10723. for (var j = 0; j < this.length; j++) {
  10724. this[j].classList.add(classes[i]);
  10725. }
  10726. }
  10727. return this;
  10728. },
  10729. removeClass: function (className) {
  10730. var classes = className.split(' ');
  10731. for (var i = 0; i < classes.length; i++) {
  10732. for (var j = 0; j < this.length; j++) {
  10733. this[j].classList.remove(classes[i]);
  10734. }
  10735. }
  10736. return this;
  10737. },
  10738. hasClass: function (className) {
  10739. if (!this[0]) return false;
  10740. else return this[0].classList.contains(className);
  10741. },
  10742. toggleClass: function (className) {
  10743. var classes = className.split(' ');
  10744. for (var i = 0; i < classes.length; i++) {
  10745. for (var j = 0; j < this.length; j++) {
  10746. this[j].classList.toggle(classes[i]);
  10747. }
  10748. }
  10749. return this;
  10750. },
  10751. attr: function (attrs, value) {
  10752. if (arguments.length === 1 && typeof attrs === 'string') {
  10753. // Get attr
  10754. if (this[0]) return this[0].getAttribute(attrs);
  10755. else return undefined;
  10756. }
  10757. else {
  10758. // Set attrs
  10759. for (var i = 0; i < this.length; i++) {
  10760. if (arguments.length === 2) {
  10761. // String
  10762. this[i].setAttribute(attrs, value);
  10763. }
  10764. else {
  10765. // Object
  10766. for (var attrName in attrs) {
  10767. this[i][attrName] = attrs[attrName];
  10768. this[i].setAttribute(attrName, attrs[attrName]);
  10769. }
  10770. }
  10771. }
  10772. return this;
  10773. }
  10774. },
  10775. removeAttr: function (attr) {
  10776. for (var i = 0; i < this.length; i++) {
  10777. this[i].removeAttribute(attr);
  10778. }
  10779. return this;
  10780. },
  10781. data: function (key, value) {
  10782. if (typeof value === 'undefined') {
  10783. // Get value
  10784. if (this[0]) {
  10785. var dataKey = this[0].getAttribute('data-' + key);
  10786. if (dataKey) return dataKey;
  10787. else if (this[0].dom7ElementDataStorage && (key in this[0].dom7ElementDataStorage)) return this[0].dom7ElementDataStorage[key];
  10788. else return undefined;
  10789. }
  10790. else return undefined;
  10791. }
  10792. else {
  10793. // Set value
  10794. for (var i = 0; i < this.length; i++) {
  10795. var el = this[i];
  10796. if (!el.dom7ElementDataStorage) el.dom7ElementDataStorage = {};
  10797. el.dom7ElementDataStorage[key] = value;
  10798. }
  10799. return this;
  10800. }
  10801. },
  10802. // Transforms
  10803. transform : function (transform) {
  10804. for (var i = 0; i < this.length; i++) {
  10805. var elStyle = this[i].style;
  10806. elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
  10807. }
  10808. return this;
  10809. },
  10810. transition: function (duration) {
  10811. if (typeof duration !== 'string') {
  10812. duration = duration + 'ms';
  10813. }
  10814. for (var i = 0; i < this.length; i++) {
  10815. var elStyle = this[i].style;
  10816. elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
  10817. }
  10818. return this;
  10819. },
  10820. //Events
  10821. on: function (eventName, targetSelector, listener, capture) {
  10822. function handleLiveEvent(e) {
  10823. var target = e.target;
  10824. if ($(target).is(targetSelector)) listener.call(target, e);
  10825. else {
  10826. var parents = $(target).parents();
  10827. for (var k = 0; k < parents.length; k++) {
  10828. if ($(parents[k]).is(targetSelector)) listener.call(parents[k], e);
  10829. }
  10830. }
  10831. }
  10832. var events = eventName.split(' ');
  10833. var i, j;
  10834. for (i = 0; i < this.length; i++) {
  10835. if (typeof targetSelector === 'function' || targetSelector === false) {
  10836. // Usual events
  10837. if (typeof targetSelector === 'function') {
  10838. listener = arguments[1];
  10839. capture = arguments[2] || false;
  10840. }
  10841. for (j = 0; j < events.length; j++) {
  10842. this[i].addEventListener(events[j], listener, capture);
  10843. }
  10844. }
  10845. else {
  10846. //Live events
  10847. for (j = 0; j < events.length; j++) {
  10848. if (!this[i].dom7LiveListeners) this[i].dom7LiveListeners = [];
  10849. this[i].dom7LiveListeners.push({listener: listener, liveListener: handleLiveEvent});
  10850. this[i].addEventListener(events[j], handleLiveEvent, capture);
  10851. }
  10852. }
  10853. }
  10854. return this;
  10855. },
  10856. off: function (eventName, targetSelector, listener, capture) {
  10857. var events = eventName.split(' ');
  10858. for (var i = 0; i < events.length; i++) {
  10859. for (var j = 0; j < this.length; j++) {
  10860. if (typeof targetSelector === 'function' || targetSelector === false) {
  10861. // Usual events
  10862. if (typeof targetSelector === 'function') {
  10863. listener = arguments[1];
  10864. capture = arguments[2] || false;
  10865. }
  10866. this[j].removeEventListener(events[i], listener, capture);
  10867. }
  10868. else {
  10869. // Live event
  10870. if (this[j].dom7LiveListeners) {
  10871. for (var k = 0; k < this[j].dom7LiveListeners.length; k++) {
  10872. if (this[j].dom7LiveListeners[k].listener === listener) {
  10873. this[j].removeEventListener(events[i], this[j].dom7LiveListeners[k].liveListener, capture);
  10874. }
  10875. }
  10876. }
  10877. }
  10878. }
  10879. }
  10880. return this;
  10881. },
  10882. once: function (eventName, targetSelector, listener, capture) {
  10883. var dom = this;
  10884. if (typeof targetSelector === 'function') {
  10885. targetSelector = false;
  10886. listener = arguments[1];
  10887. capture = arguments[2];
  10888. }
  10889. function proxy(e) {
  10890. listener(e);
  10891. dom.off(eventName, targetSelector, proxy, capture);
  10892. }
  10893. dom.on(eventName, targetSelector, proxy, capture);
  10894. },
  10895. trigger: function (eventName, eventData) {
  10896. for (var i = 0; i < this.length; i++) {
  10897. var evt;
  10898. try {
  10899. evt = new window.CustomEvent(eventName, {detail: eventData, bubbles: true, cancelable: true});
  10900. }
  10901. catch (e) {
  10902. evt = document.createEvent('Event');
  10903. evt.initEvent(eventName, true, true);
  10904. evt.detail = eventData;
  10905. }
  10906. this[i].dispatchEvent(evt);
  10907. }
  10908. return this;
  10909. },
  10910. transitionEnd: function (callback) {
  10911. var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
  10912. i, j, dom = this;
  10913. function fireCallBack(e) {
  10914. /*jshint validthis:true */
  10915. if (e.target !== this) return;
  10916. callback.call(this, e);
  10917. for (i = 0; i < events.length; i++) {
  10918. dom.off(events[i], fireCallBack);
  10919. }
  10920. }
  10921. if (callback) {
  10922. for (i = 0; i < events.length; i++) {
  10923. dom.on(events[i], fireCallBack);
  10924. }
  10925. }
  10926. return this;
  10927. },
  10928. // Sizing/Styles
  10929. width: function () {
  10930. if (this[0] === window) {
  10931. return window.innerWidth;
  10932. }
  10933. else {
  10934. if (this.length > 0) {
  10935. return parseFloat(this.css('width'));
  10936. }
  10937. else {
  10938. return null;
  10939. }
  10940. }
  10941. },
  10942. outerWidth: function (includeMargins) {
  10943. if (this.length > 0) {
  10944. if (includeMargins)
  10945. return this[0].offsetWidth + parseFloat(this.css('margin-right')) + parseFloat(this.css('margin-left'));
  10946. else
  10947. return this[0].offsetWidth;
  10948. }
  10949. else return null;
  10950. },
  10951. height: function () {
  10952. if (this[0] === window) {
  10953. return window.innerHeight;
  10954. }
  10955. else {
  10956. if (this.length > 0) {
  10957. return parseFloat(this.css('height'));
  10958. }
  10959. else {
  10960. return null;
  10961. }
  10962. }
  10963. },
  10964. outerHeight: function (includeMargins) {
  10965. if (this.length > 0) {
  10966. if (includeMargins)
  10967. return this[0].offsetHeight + parseFloat(this.css('margin-top')) + parseFloat(this.css('margin-bottom'));
  10968. else
  10969. return this[0].offsetHeight;
  10970. }
  10971. else return null;
  10972. },
  10973. offset: function () {
  10974. if (this.length > 0) {
  10975. var el = this[0];
  10976. var box = el.getBoundingClientRect();
  10977. var body = document.body;
  10978. var clientTop = el.clientTop || body.clientTop || 0;
  10979. var clientLeft = el.clientLeft || body.clientLeft || 0;
  10980. var scrollTop = window.pageYOffset || el.scrollTop;
  10981. var scrollLeft = window.pageXOffset || el.scrollLeft;
  10982. return {
  10983. top: box.top + scrollTop - clientTop,
  10984. left: box.left + scrollLeft - clientLeft
  10985. };
  10986. }
  10987. else {
  10988. return null;
  10989. }
  10990. },
  10991. css: function (props, value) {
  10992. var i;
  10993. if (arguments.length === 1) {
  10994. if (typeof props === 'string') {
  10995. if (this[0]) return window.getComputedStyle(this[0], null).getPropertyValue(props);
  10996. }
  10997. else {
  10998. for (i = 0; i < this.length; i++) {
  10999. for (var prop in props) {
  11000. this[i].style[prop] = props[prop];
  11001. }
  11002. }
  11003. return this;
  11004. }
  11005. }
  11006. if (arguments.length === 2 && typeof props === 'string') {
  11007. for (i = 0; i < this.length; i++) {
  11008. this[i].style[props] = value;
  11009. }
  11010. return this;
  11011. }
  11012. return this;
  11013. },
  11014. //Dom manipulation
  11015. each: function (callback) {
  11016. for (var i = 0; i < this.length; i++) {
  11017. callback.call(this[i], i, this[i]);
  11018. }
  11019. return this;
  11020. },
  11021. html: function (html) {
  11022. if (typeof html === 'undefined') {
  11023. return this[0] ? this[0].innerHTML : undefined;
  11024. }
  11025. else {
  11026. for (var i = 0; i < this.length; i++) {
  11027. this[i].innerHTML = html;
  11028. }
  11029. return this;
  11030. }
  11031. },
  11032. is: function (selector) {
  11033. if (!this[0]) return false;
  11034. var compareWith, i;
  11035. if (typeof selector === 'string') {
  11036. var el = this[0];
  11037. if (el === document) return selector === document;
  11038. if (el === window) return selector === window;
  11039. if (el.matches) return el.matches(selector);
  11040. else if (el.webkitMatchesSelector) return el.webkitMatchesSelector(selector);
  11041. else if (el.mozMatchesSelector) return el.mozMatchesSelector(selector);
  11042. else if (el.msMatchesSelector) return el.msMatchesSelector(selector);
  11043. else {
  11044. compareWith = $(selector);
  11045. for (i = 0; i < compareWith.length; i++) {
  11046. if (compareWith[i] === this[0]) return true;
  11047. }
  11048. return false;
  11049. }
  11050. }
  11051. else if (selector === document) return this[0] === document;
  11052. else if (selector === window) return this[0] === window;
  11053. else {
  11054. if (selector.nodeType || selector instanceof Dom7) {
  11055. compareWith = selector.nodeType ? [selector] : selector;
  11056. for (i = 0; i < compareWith.length; i++) {
  11057. if (compareWith[i] === this[0]) return true;
  11058. }
  11059. return false;
  11060. }
  11061. return false;
  11062. }
  11063. },
  11064. index: function () {
  11065. if (this[0]) {
  11066. var child = this[0];
  11067. var i = 0;
  11068. while ((child = child.previousSibling) !== null) {
  11069. if (child.nodeType === 1) i++;
  11070. }
  11071. return i;
  11072. }
  11073. else return undefined;
  11074. },
  11075. eq: function (index) {
  11076. if (typeof index === 'undefined') return this;
  11077. var length = this.length;
  11078. var returnIndex;
  11079. if (index > length - 1) {
  11080. return new Dom7([]);
  11081. }
  11082. if (index < 0) {
  11083. returnIndex = length + index;
  11084. if (returnIndex < 0) return new Dom7([]);
  11085. else return new Dom7([this[returnIndex]]);
  11086. }
  11087. return new Dom7([this[index]]);
  11088. },
  11089. append: function (newChild) {
  11090. var i, j;
  11091. for (i = 0; i < this.length; i++) {
  11092. if (typeof newChild === 'string') {
  11093. var tempDiv = document.createElement('div');
  11094. tempDiv.innerHTML = newChild;
  11095. while (tempDiv.firstChild) {
  11096. this[i].appendChild(tempDiv.firstChild);
  11097. }
  11098. }
  11099. else if (newChild instanceof Dom7) {
  11100. for (j = 0; j < newChild.length; j++) {
  11101. this[i].appendChild(newChild[j]);
  11102. }
  11103. }
  11104. else {
  11105. this[i].appendChild(newChild);
  11106. }
  11107. }
  11108. return this;
  11109. },
  11110. prepend: function (newChild) {
  11111. var i, j;
  11112. for (i = 0; i < this.length; i++) {
  11113. if (typeof newChild === 'string') {
  11114. var tempDiv = document.createElement('div');
  11115. tempDiv.innerHTML = newChild;
  11116. for (j = tempDiv.childNodes.length - 1; j >= 0; j--) {
  11117. this[i].insertBefore(tempDiv.childNodes[j], this[i].childNodes[0]);
  11118. }
  11119. // this[i].insertAdjacentHTML('afterbegin', newChild);
  11120. }
  11121. else if (newChild instanceof Dom7) {
  11122. for (j = 0; j < newChild.length; j++) {
  11123. this[i].insertBefore(newChild[j], this[i].childNodes[0]);
  11124. }
  11125. }
  11126. else {
  11127. this[i].insertBefore(newChild, this[i].childNodes[0]);
  11128. }
  11129. }
  11130. return this;
  11131. },
  11132. insertBefore: function (selector) {
  11133. var before = $(selector);
  11134. for (var i = 0; i < this.length; i++) {
  11135. if (before.length === 1) {
  11136. before[0].parentNode.insertBefore(this[i], before[0]);
  11137. }
  11138. else if (before.length > 1) {
  11139. for (var j = 0; j < before.length; j++) {
  11140. before[j].parentNode.insertBefore(this[i].cloneNode(true), before[j]);
  11141. }
  11142. }
  11143. }
  11144. },
  11145. insertAfter: function (selector) {
  11146. var after = $(selector);
  11147. for (var i = 0; i < this.length; i++) {
  11148. if (after.length === 1) {
  11149. after[0].parentNode.insertBefore(this[i], after[0].nextSibling);
  11150. }
  11151. else if (after.length > 1) {
  11152. for (var j = 0; j < after.length; j++) {
  11153. after[j].parentNode.insertBefore(this[i].cloneNode(true), after[j].nextSibling);
  11154. }
  11155. }
  11156. }
  11157. },
  11158. next: function (selector) {
  11159. if (this.length > 0) {
  11160. if (selector) {
  11161. if (this[0].nextElementSibling && $(this[0].nextElementSibling).is(selector)) return new Dom7([this[0].nextElementSibling]);
  11162. else return new Dom7([]);
  11163. }
  11164. else {
  11165. if (this[0].nextElementSibling) return new Dom7([this[0].nextElementSibling]);
  11166. else return new Dom7([]);
  11167. }
  11168. }
  11169. else return new Dom7([]);
  11170. },
  11171. nextAll: function (selector) {
  11172. var nextEls = [];
  11173. var el = this[0];
  11174. if (!el) return new Dom7([]);
  11175. while (el.nextElementSibling) {
  11176. var next = el.nextElementSibling;
  11177. if (selector) {
  11178. if($(next).is(selector)) nextEls.push(next);
  11179. }
  11180. else nextEls.push(next);
  11181. el = next;
  11182. }
  11183. return new Dom7(nextEls);
  11184. },
  11185. prev: function (selector) {
  11186. if (this.length > 0) {
  11187. if (selector) {
  11188. if (this[0].previousElementSibling && $(this[0].previousElementSibling).is(selector)) return new Dom7([this[0].previousElementSibling]);
  11189. else return new Dom7([]);
  11190. }
  11191. else {
  11192. if (this[0].previousElementSibling) return new Dom7([this[0].previousElementSibling]);
  11193. else return new Dom7([]);
  11194. }
  11195. }
  11196. else return new Dom7([]);
  11197. },
  11198. prevAll: function (selector) {
  11199. var prevEls = [];
  11200. var el = this[0];
  11201. if (!el) return new Dom7([]);
  11202. while (el.previousElementSibling) {
  11203. var prev = el.previousElementSibling;
  11204. if (selector) {
  11205. if($(prev).is(selector)) prevEls.push(prev);
  11206. }
  11207. else prevEls.push(prev);
  11208. el = prev;
  11209. }
  11210. return new Dom7(prevEls);
  11211. },
  11212. parent: function (selector) {
  11213. var parents = [];
  11214. for (var i = 0; i < this.length; i++) {
  11215. if (selector) {
  11216. if ($(this[i].parentNode).is(selector)) parents.push(this[i].parentNode);
  11217. }
  11218. else {
  11219. parents.push(this[i].parentNode);
  11220. }
  11221. }
  11222. return $($.unique(parents));
  11223. },
  11224. parents: function (selector) {
  11225. var parents = [];
  11226. for (var i = 0; i < this.length; i++) {
  11227. var parent = this[i].parentNode;
  11228. while (parent) {
  11229. if (selector) {
  11230. if ($(parent).is(selector)) parents.push(parent);
  11231. }
  11232. else {
  11233. parents.push(parent);
  11234. }
  11235. parent = parent.parentNode;
  11236. }
  11237. }
  11238. return $($.unique(parents));
  11239. },
  11240. find : function (selector) {
  11241. var foundElements = [];
  11242. for (var i = 0; i < this.length; i++) {
  11243. var found = this[i].querySelectorAll(selector);
  11244. for (var j = 0; j < found.length; j++) {
  11245. foundElements.push(found[j]);
  11246. }
  11247. }
  11248. return new Dom7(foundElements);
  11249. },
  11250. children: function (selector) {
  11251. var children = [];
  11252. for (var i = 0; i < this.length; i++) {
  11253. var childNodes = this[i].childNodes;
  11254. for (var j = 0; j < childNodes.length; j++) {
  11255. if (!selector) {
  11256. if (childNodes[j].nodeType === 1) children.push(childNodes[j]);
  11257. }
  11258. else {
  11259. if (childNodes[j].nodeType === 1 && $(childNodes[j]).is(selector)) children.push(childNodes[j]);
  11260. }
  11261. }
  11262. }
  11263. return new Dom7($.unique(children));
  11264. },
  11265. remove: function () {
  11266. for (var i = 0; i < this.length; i++) {
  11267. if (this[i].parentNode) this[i].parentNode.removeChild(this[i]);
  11268. }
  11269. return this;
  11270. },
  11271. add: function () {
  11272. var dom = this;
  11273. var i, j;
  11274. for (i = 0; i < arguments.length; i++) {
  11275. var toAdd = $(arguments[i]);
  11276. for (j = 0; j < toAdd.length; j++) {
  11277. dom[dom.length] = toAdd[j];
  11278. dom.length++;
  11279. }
  11280. }
  11281. return dom;
  11282. }
  11283. };
  11284. $.fn = Dom7.prototype;
  11285. $.unique = function (arr) {
  11286. var unique = [];
  11287. for (var i = 0; i < arr.length; i++) {
  11288. if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
  11289. }
  11290. return unique;
  11291. };
  11292. return $;
  11293. })();
  11294. /*===========================
  11295. Get Dom libraries
  11296. ===========================*/
  11297. var swiperDomPlugins = ['jQuery', 'Zepto', 'Dom7'];
  11298. for (var i = 0; i < swiperDomPlugins.length; i++) {
  11299. if (window[swiperDomPlugins[i]]) {
  11300. addLibraryPlugin(window[swiperDomPlugins[i]]);
  11301. }
  11302. }
  11303. // Required DOM Plugins
  11304. var domLib;
  11305. if (typeof Dom7 === 'undefined') {
  11306. domLib = window.Dom7 || window.Zepto || window.jQuery;
  11307. }
  11308. else {
  11309. domLib = Dom7;
  11310. }
  11311. /*===========================
  11312. Add .swiper plugin from Dom libraries
  11313. ===========================*/
  11314. function addLibraryPlugin(lib) {
  11315. lib.fn.swiper = function (params) {
  11316. var firstInstance;
  11317. lib(this).each(function () {
  11318. var s = new Swiper(this, params);
  11319. if (!firstInstance) firstInstance = s;
  11320. });
  11321. return firstInstance;
  11322. };
  11323. }
  11324. if (domLib) {
  11325. if (!('transitionEnd' in domLib.fn)) {
  11326. domLib.fn.transitionEnd = function (callback) {
  11327. var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
  11328. i, j, dom = this;
  11329. function fireCallBack(e) {
  11330. /*jshint validthis:true */
  11331. if (e.target !== this) return;
  11332. callback.call(this, e);
  11333. for (i = 0; i < events.length; i++) {
  11334. dom.off(events[i], fireCallBack);
  11335. }
  11336. }
  11337. if (callback) {
  11338. for (i = 0; i < events.length; i++) {
  11339. dom.on(events[i], fireCallBack);
  11340. }
  11341. }
  11342. return this;
  11343. };
  11344. }
  11345. if (!('transform' in domLib.fn)) {
  11346. domLib.fn.transform = function (transform) {
  11347. for (var i = 0; i < this.length; i++) {
  11348. var elStyle = this[i].style;
  11349. elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
  11350. }
  11351. return this;
  11352. };
  11353. }
  11354. if (!('transition' in domLib.fn)) {
  11355. domLib.fn.transition = function (duration) {
  11356. if (typeof duration !== 'string') {
  11357. duration = duration + 'ms';
  11358. }
  11359. for (var i = 0; i < this.length; i++) {
  11360. var elStyle = this[i].style;
  11361. elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
  11362. }
  11363. return this;
  11364. };
  11365. }
  11366. }
  11367. ionic.views.Swiper = Swiper;
  11368. })();
  11369. (function(ionic) {
  11370. 'use strict';
  11371. ionic.views.Toggle = ionic.views.View.inherit({
  11372. initialize: function(opts) {
  11373. var self = this;
  11374. this.el = opts.el;
  11375. this.checkbox = opts.checkbox;
  11376. this.track = opts.track;
  11377. this.handle = opts.handle;
  11378. this.openPercent = -1;
  11379. this.onChange = opts.onChange || function() {};
  11380. this.triggerThreshold = opts.triggerThreshold || 20;
  11381. this.dragStartHandler = function(e) {
  11382. self.dragStart(e);
  11383. };
  11384. this.dragHandler = function(e) {
  11385. self.drag(e);
  11386. };
  11387. this.holdHandler = function(e) {
  11388. self.hold(e);
  11389. };
  11390. this.releaseHandler = function(e) {
  11391. self.release(e);
  11392. };
  11393. this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el);
  11394. this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el);
  11395. this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el);
  11396. this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el);
  11397. },
  11398. destroy: function() {
  11399. ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture);
  11400. ionic.offGesture(this.dragGesture, 'drag', this.dragGesture);
  11401. ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler);
  11402. ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler);
  11403. },
  11404. tap: function() {
  11405. if(this.el.getAttribute('disabled') !== 'disabled') {
  11406. this.val( !this.checkbox.checked );
  11407. }
  11408. },
  11409. dragStart: function(e) {
  11410. if(this.checkbox.disabled) return;
  11411. this._dragInfo = {
  11412. width: this.el.offsetWidth,
  11413. left: this.el.offsetLeft,
  11414. right: this.el.offsetLeft + this.el.offsetWidth,
  11415. triggerX: this.el.offsetWidth / 2,
  11416. initialState: this.checkbox.checked
  11417. };
  11418. // Stop any parent dragging
  11419. e.gesture.srcEvent.preventDefault();
  11420. // Trigger hold styles
  11421. this.hold(e);
  11422. },
  11423. drag: function(e) {
  11424. var self = this;
  11425. if(!this._dragInfo) { return; }
  11426. // Stop any parent dragging
  11427. e.gesture.srcEvent.preventDefault();
  11428. ionic.requestAnimationFrame(function () {
  11429. if (!self._dragInfo) { return; }
  11430. var px = e.gesture.touches[0].pageX - self._dragInfo.left;
  11431. var mx = self._dragInfo.width - self.triggerThreshold;
  11432. // The initial state was on, so "tend towards" on
  11433. if(self._dragInfo.initialState) {
  11434. if(px < self.triggerThreshold) {
  11435. self.setOpenPercent(0);
  11436. } else if(px > self._dragInfo.triggerX) {
  11437. self.setOpenPercent(100);
  11438. }
  11439. } else {
  11440. // The initial state was off, so "tend towards" off
  11441. if(px < self._dragInfo.triggerX) {
  11442. self.setOpenPercent(0);
  11443. } else if(px > mx) {
  11444. self.setOpenPercent(100);
  11445. }
  11446. }
  11447. });
  11448. },
  11449. endDrag: function() {
  11450. this._dragInfo = null;
  11451. },
  11452. hold: function() {
  11453. this.el.classList.add('dragging');
  11454. },
  11455. release: function(e) {
  11456. this.el.classList.remove('dragging');
  11457. this.endDrag(e);
  11458. },
  11459. setOpenPercent: function(openPercent) {
  11460. // only make a change if the new open percent has changed
  11461. if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) {
  11462. this.openPercent = openPercent;
  11463. if(openPercent === 0) {
  11464. this.val(false);
  11465. } else if(openPercent === 100) {
  11466. this.val(true);
  11467. } else {
  11468. var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) );
  11469. openPixel = (openPixel < 1 ? 0 : openPixel);
  11470. this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)';
  11471. }
  11472. }
  11473. },
  11474. val: function(value) {
  11475. if(value === true || value === false) {
  11476. if(this.handle.style[ionic.CSS.TRANSFORM] !== "") {
  11477. this.handle.style[ionic.CSS.TRANSFORM] = "";
  11478. }
  11479. this.checkbox.checked = value;
  11480. this.openPercent = (value ? 100 : 0);
  11481. this.onChange && this.onChange();
  11482. }
  11483. return this.checkbox.checked;
  11484. }
  11485. });
  11486. })(ionic);
  11487. })();
  11488. /*!
  11489. * ionic.bundle.js is a concatenation of:
  11490. * ionic.js, angular.js, angular-animate.js,
  11491. * angular-sanitize.js, angular-ui-router.js,
  11492. * and ionic-angular.js
  11493. */
  11494. /**
  11495. * @license AngularJS v1.5.3
  11496. * (c) 2010-2016 Google, Inc. http://angularjs.org
  11497. * License: MIT
  11498. */
  11499. (function(window, document, undefined) {'use strict';
  11500. /**
  11501. * @description
  11502. *
  11503. * This object provides a utility for producing rich Error messages within
  11504. * Angular. It can be called as follows:
  11505. *
  11506. * var exampleMinErr = minErr('example');
  11507. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  11508. *
  11509. * The above creates an instance of minErr in the example namespace. The
  11510. * resulting error will have a namespaced error code of example.one. The
  11511. * resulting error will replace {0} with the value of foo, and {1} with the
  11512. * value of bar. The object is not restricted in the number of arguments it can
  11513. * take.
  11514. *
  11515. * If fewer arguments are specified than necessary for interpolation, the extra
  11516. * interpolation markers will be preserved in the final string.
  11517. *
  11518. * Since data will be parsed statically during a build step, some restrictions
  11519. * are applied with respect to how minErr instances are created and called.
  11520. * Instances should have names of the form namespaceMinErr for a minErr created
  11521. * using minErr('namespace') . Error codes, namespaces and template strings
  11522. * should all be static strings, not variables or general expressions.
  11523. *
  11524. * @param {string} module The namespace to use for the new minErr instance.
  11525. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  11526. * error from returned function, for cases when a particular type of error is useful.
  11527. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  11528. */
  11529. function minErr(module, ErrorConstructor) {
  11530. ErrorConstructor = ErrorConstructor || Error;
  11531. return function() {
  11532. var SKIP_INDEXES = 2;
  11533. var templateArgs = arguments,
  11534. code = templateArgs[0],
  11535. message = '[' + (module ? module + ':' : '') + code + '] ',
  11536. template = templateArgs[1],
  11537. paramPrefix, i;
  11538. message += template.replace(/\{\d+\}/g, function(match) {
  11539. var index = +match.slice(1, -1),
  11540. shiftedIndex = index + SKIP_INDEXES;
  11541. if (shiftedIndex < templateArgs.length) {
  11542. return toDebugString(templateArgs[shiftedIndex]);
  11543. }
  11544. return match;
  11545. });
  11546. message += '\nhttp://errors.angularjs.org/1.5.3/' +
  11547. (module ? module + '/' : '') + code;
  11548. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  11549. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  11550. encodeURIComponent(toDebugString(templateArgs[i]));
  11551. }
  11552. return new ErrorConstructor(message);
  11553. };
  11554. }
  11555. /* We need to tell jshint what variables are being exported */
  11556. /* global angular: true,
  11557. msie: true,
  11558. jqLite: true,
  11559. jQuery: true,
  11560. slice: true,
  11561. splice: true,
  11562. push: true,
  11563. toString: true,
  11564. ngMinErr: true,
  11565. angularModule: true,
  11566. uid: true,
  11567. REGEX_STRING_REGEXP: true,
  11568. VALIDITY_STATE_PROPERTY: true,
  11569. lowercase: true,
  11570. uppercase: true,
  11571. manualLowercase: true,
  11572. manualUppercase: true,
  11573. nodeName_: true,
  11574. isArrayLike: true,
  11575. forEach: true,
  11576. forEachSorted: true,
  11577. reverseParams: true,
  11578. nextUid: true,
  11579. setHashKey: true,
  11580. extend: true,
  11581. toInt: true,
  11582. inherit: true,
  11583. merge: true,
  11584. noop: true,
  11585. identity: true,
  11586. valueFn: true,
  11587. isUndefined: true,
  11588. isDefined: true,
  11589. isObject: true,
  11590. isBlankObject: true,
  11591. isString: true,
  11592. isNumber: true,
  11593. isDate: true,
  11594. isArray: true,
  11595. isFunction: true,
  11596. isRegExp: true,
  11597. isWindow: true,
  11598. isScope: true,
  11599. isFile: true,
  11600. isFormData: true,
  11601. isBlob: true,
  11602. isBoolean: true,
  11603. isPromiseLike: true,
  11604. trim: true,
  11605. escapeForRegexp: true,
  11606. isElement: true,
  11607. makeMap: true,
  11608. includes: true,
  11609. arrayRemove: true,
  11610. copy: true,
  11611. shallowCopy: true,
  11612. equals: true,
  11613. csp: true,
  11614. jq: true,
  11615. concat: true,
  11616. sliceArgs: true,
  11617. bind: true,
  11618. toJsonReplacer: true,
  11619. toJson: true,
  11620. fromJson: true,
  11621. convertTimezoneToLocal: true,
  11622. timezoneToOffset: true,
  11623. startingTag: true,
  11624. tryDecodeURIComponent: true,
  11625. parseKeyValue: true,
  11626. toKeyValue: true,
  11627. encodeUriSegment: true,
  11628. encodeUriQuery: true,
  11629. angularInit: true,
  11630. bootstrap: true,
  11631. getTestability: true,
  11632. snake_case: true,
  11633. bindJQuery: true,
  11634. assertArg: true,
  11635. assertArgFn: true,
  11636. assertNotHasOwnProperty: true,
  11637. getter: true,
  11638. getBlockNodes: true,
  11639. hasOwnProperty: true,
  11640. createMap: true,
  11641. NODE_TYPE_ELEMENT: true,
  11642. NODE_TYPE_ATTRIBUTE: true,
  11643. NODE_TYPE_TEXT: true,
  11644. NODE_TYPE_COMMENT: true,
  11645. NODE_TYPE_DOCUMENT: true,
  11646. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  11647. */
  11648. ////////////////////////////////////
  11649. /**
  11650. * @ngdoc module
  11651. * @name ng
  11652. * @module ng
  11653. * @description
  11654. *
  11655. * # ng (core module)
  11656. * The ng module is loaded by default when an AngularJS application is started. The module itself
  11657. * contains the essential components for an AngularJS application to function. The table below
  11658. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  11659. * components available within this core module.
  11660. *
  11661. * <div doc-module-components="ng"></div>
  11662. */
  11663. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  11664. // The name of a form control's ValidityState property.
  11665. // This is used so that it's possible for internal tests to create mock ValidityStates.
  11666. var VALIDITY_STATE_PROPERTY = 'validity';
  11667. var hasOwnProperty = Object.prototype.hasOwnProperty;
  11668. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  11669. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  11670. var manualLowercase = function(s) {
  11671. /* jshint bitwise: false */
  11672. return isString(s)
  11673. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  11674. : s;
  11675. };
  11676. var manualUppercase = function(s) {
  11677. /* jshint bitwise: false */
  11678. return isString(s)
  11679. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  11680. : s;
  11681. };
  11682. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  11683. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  11684. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  11685. if ('i' !== 'I'.toLowerCase()) {
  11686. lowercase = manualLowercase;
  11687. uppercase = manualUppercase;
  11688. }
  11689. var
  11690. msie, // holds major version number for IE, or NaN if UA is not IE.
  11691. jqLite, // delay binding since jQuery could be loaded after us.
  11692. jQuery, // delay binding
  11693. slice = [].slice,
  11694. splice = [].splice,
  11695. push = [].push,
  11696. toString = Object.prototype.toString,
  11697. getPrototypeOf = Object.getPrototypeOf,
  11698. ngMinErr = minErr('ng'),
  11699. /** @name angular */
  11700. angular = window.angular || (window.angular = {}),
  11701. angularModule,
  11702. uid = 0;
  11703. /**
  11704. * documentMode is an IE-only property
  11705. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  11706. */
  11707. msie = document.documentMode;
  11708. /**
  11709. * @private
  11710. * @param {*} obj
  11711. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  11712. * String ...)
  11713. */
  11714. function isArrayLike(obj) {
  11715. // `null`, `undefined` and `window` are not array-like
  11716. if (obj == null || isWindow(obj)) return false;
  11717. // arrays, strings and jQuery/jqLite objects are array like
  11718. // * jqLite is either the jQuery or jqLite constructor function
  11719. // * we have to check the existence of jqLite first as this method is called
  11720. // via the forEach method when constructing the jqLite object in the first place
  11721. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  11722. // Support: iOS 8.2 (not reproducible in simulator)
  11723. // "length" in obj used to prevent JIT error (gh-11508)
  11724. var length = "length" in Object(obj) && obj.length;
  11725. // NodeList objects (with `item` method) and
  11726. // other objects with suitable length characteristics are array-like
  11727. return isNumber(length) &&
  11728. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
  11729. }
  11730. /**
  11731. * @ngdoc function
  11732. * @name angular.forEach
  11733. * @module ng
  11734. * @kind function
  11735. *
  11736. * @description
  11737. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  11738. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  11739. * is the value of an object property or an array element, `key` is the object property key or
  11740. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  11741. *
  11742. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  11743. * using the `hasOwnProperty` method.
  11744. *
  11745. * Unlike ES262's
  11746. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  11747. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  11748. * return the value provided.
  11749. *
  11750. ```js
  11751. var values = {name: 'misko', gender: 'male'};
  11752. var log = [];
  11753. angular.forEach(values, function(value, key) {
  11754. this.push(key + ': ' + value);
  11755. }, log);
  11756. expect(log).toEqual(['name: misko', 'gender: male']);
  11757. ```
  11758. *
  11759. * @param {Object|Array} obj Object to iterate over.
  11760. * @param {Function} iterator Iterator function.
  11761. * @param {Object=} context Object to become context (`this`) for the iterator function.
  11762. * @returns {Object|Array} Reference to `obj`.
  11763. */
  11764. function forEach(obj, iterator, context) {
  11765. var key, length;
  11766. if (obj) {
  11767. if (isFunction(obj)) {
  11768. for (key in obj) {
  11769. // Need to check if hasOwnProperty exists,
  11770. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  11771. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  11772. iterator.call(context, obj[key], key, obj);
  11773. }
  11774. }
  11775. } else if (isArray(obj) || isArrayLike(obj)) {
  11776. var isPrimitive = typeof obj !== 'object';
  11777. for (key = 0, length = obj.length; key < length; key++) {
  11778. if (isPrimitive || key in obj) {
  11779. iterator.call(context, obj[key], key, obj);
  11780. }
  11781. }
  11782. } else if (obj.forEach && obj.forEach !== forEach) {
  11783. obj.forEach(iterator, context, obj);
  11784. } else if (isBlankObject(obj)) {
  11785. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  11786. for (key in obj) {
  11787. iterator.call(context, obj[key], key, obj);
  11788. }
  11789. } else if (typeof obj.hasOwnProperty === 'function') {
  11790. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  11791. for (key in obj) {
  11792. if (obj.hasOwnProperty(key)) {
  11793. iterator.call(context, obj[key], key, obj);
  11794. }
  11795. }
  11796. } else {
  11797. // Slow path for objects which do not have a method `hasOwnProperty`
  11798. for (key in obj) {
  11799. if (hasOwnProperty.call(obj, key)) {
  11800. iterator.call(context, obj[key], key, obj);
  11801. }
  11802. }
  11803. }
  11804. }
  11805. return obj;
  11806. }
  11807. function forEachSorted(obj, iterator, context) {
  11808. var keys = Object.keys(obj).sort();
  11809. for (var i = 0; i < keys.length; i++) {
  11810. iterator.call(context, obj[keys[i]], keys[i]);
  11811. }
  11812. return keys;
  11813. }
  11814. /**
  11815. * when using forEach the params are value, key, but it is often useful to have key, value.
  11816. * @param {function(string, *)} iteratorFn
  11817. * @returns {function(*, string)}
  11818. */
  11819. function reverseParams(iteratorFn) {
  11820. return function(value, key) {iteratorFn(key, value);};
  11821. }
  11822. /**
  11823. * A consistent way of creating unique IDs in angular.
  11824. *
  11825. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  11826. * we hit number precision issues in JavaScript.
  11827. *
  11828. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  11829. *
  11830. * @returns {number} an unique alpha-numeric string
  11831. */
  11832. function nextUid() {
  11833. return ++uid;
  11834. }
  11835. /**
  11836. * Set or clear the hashkey for an object.
  11837. * @param obj object
  11838. * @param h the hashkey (!truthy to delete the hashkey)
  11839. */
  11840. function setHashKey(obj, h) {
  11841. if (h) {
  11842. obj.$$hashKey = h;
  11843. } else {
  11844. delete obj.$$hashKey;
  11845. }
  11846. }
  11847. function baseExtend(dst, objs, deep) {
  11848. var h = dst.$$hashKey;
  11849. for (var i = 0, ii = objs.length; i < ii; ++i) {
  11850. var obj = objs[i];
  11851. if (!isObject(obj) && !isFunction(obj)) continue;
  11852. var keys = Object.keys(obj);
  11853. for (var j = 0, jj = keys.length; j < jj; j++) {
  11854. var key = keys[j];
  11855. var src = obj[key];
  11856. if (deep && isObject(src)) {
  11857. if (isDate(src)) {
  11858. dst[key] = new Date(src.valueOf());
  11859. } else if (isRegExp(src)) {
  11860. dst[key] = new RegExp(src);
  11861. } else if (src.nodeName) {
  11862. dst[key] = src.cloneNode(true);
  11863. } else if (isElement(src)) {
  11864. dst[key] = src.clone();
  11865. } else {
  11866. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  11867. baseExtend(dst[key], [src], true);
  11868. }
  11869. } else {
  11870. dst[key] = src;
  11871. }
  11872. }
  11873. }
  11874. setHashKey(dst, h);
  11875. return dst;
  11876. }
  11877. /**
  11878. * @ngdoc function
  11879. * @name angular.extend
  11880. * @module ng
  11881. * @kind function
  11882. *
  11883. * @description
  11884. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  11885. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  11886. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  11887. *
  11888. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  11889. * {@link angular.merge} for this.
  11890. *
  11891. * @param {Object} dst Destination object.
  11892. * @param {...Object} src Source object(s).
  11893. * @returns {Object} Reference to `dst`.
  11894. */
  11895. function extend(dst) {
  11896. return baseExtend(dst, slice.call(arguments, 1), false);
  11897. }
  11898. /**
  11899. * @ngdoc function
  11900. * @name angular.merge
  11901. * @module ng
  11902. * @kind function
  11903. *
  11904. * @description
  11905. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  11906. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  11907. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  11908. *
  11909. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  11910. * objects, performing a deep copy.
  11911. *
  11912. * @param {Object} dst Destination object.
  11913. * @param {...Object} src Source object(s).
  11914. * @returns {Object} Reference to `dst`.
  11915. */
  11916. function merge(dst) {
  11917. return baseExtend(dst, slice.call(arguments, 1), true);
  11918. }
  11919. function toInt(str) {
  11920. return parseInt(str, 10);
  11921. }
  11922. function inherit(parent, extra) {
  11923. return extend(Object.create(parent), extra);
  11924. }
  11925. /**
  11926. * @ngdoc function
  11927. * @name angular.noop
  11928. * @module ng
  11929. * @kind function
  11930. *
  11931. * @description
  11932. * A function that performs no operations. This function can be useful when writing code in the
  11933. * functional style.
  11934. ```js
  11935. function foo(callback) {
  11936. var result = calculateResult();
  11937. (callback || angular.noop)(result);
  11938. }
  11939. ```
  11940. */
  11941. function noop() {}
  11942. noop.$inject = [];
  11943. /**
  11944. * @ngdoc function
  11945. * @name angular.identity
  11946. * @module ng
  11947. * @kind function
  11948. *
  11949. * @description
  11950. * A function that returns its first argument. This function is useful when writing code in the
  11951. * functional style.
  11952. *
  11953. ```js
  11954. function transformer(transformationFn, value) {
  11955. return (transformationFn || angular.identity)(value);
  11956. };
  11957. ```
  11958. * @param {*} value to be returned.
  11959. * @returns {*} the value passed in.
  11960. */
  11961. function identity($) {return $;}
  11962. identity.$inject = [];
  11963. function valueFn(value) {return function valueRef() {return value;};}
  11964. function hasCustomToString(obj) {
  11965. return isFunction(obj.toString) && obj.toString !== toString;
  11966. }
  11967. /**
  11968. * @ngdoc function
  11969. * @name angular.isUndefined
  11970. * @module ng
  11971. * @kind function
  11972. *
  11973. * @description
  11974. * Determines if a reference is undefined.
  11975. *
  11976. * @param {*} value Reference to check.
  11977. * @returns {boolean} True if `value` is undefined.
  11978. */
  11979. function isUndefined(value) {return typeof value === 'undefined';}
  11980. /**
  11981. * @ngdoc function
  11982. * @name angular.isDefined
  11983. * @module ng
  11984. * @kind function
  11985. *
  11986. * @description
  11987. * Determines if a reference is defined.
  11988. *
  11989. * @param {*} value Reference to check.
  11990. * @returns {boolean} True if `value` is defined.
  11991. */
  11992. function isDefined(value) {return typeof value !== 'undefined';}
  11993. /**
  11994. * @ngdoc function
  11995. * @name angular.isObject
  11996. * @module ng
  11997. * @kind function
  11998. *
  11999. * @description
  12000. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  12001. * considered to be objects. Note that JavaScript arrays are objects.
  12002. *
  12003. * @param {*} value Reference to check.
  12004. * @returns {boolean} True if `value` is an `Object` but not `null`.
  12005. */
  12006. function isObject(value) {
  12007. // http://jsperf.com/isobject4
  12008. return value !== null && typeof value === 'object';
  12009. }
  12010. /**
  12011. * Determine if a value is an object with a null prototype
  12012. *
  12013. * @returns {boolean} True if `value` is an `Object` with a null prototype
  12014. */
  12015. function isBlankObject(value) {
  12016. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  12017. }
  12018. /**
  12019. * @ngdoc function
  12020. * @name angular.isString
  12021. * @module ng
  12022. * @kind function
  12023. *
  12024. * @description
  12025. * Determines if a reference is a `String`.
  12026. *
  12027. * @param {*} value Reference to check.
  12028. * @returns {boolean} True if `value` is a `String`.
  12029. */
  12030. function isString(value) {return typeof value === 'string';}
  12031. /**
  12032. * @ngdoc function
  12033. * @name angular.isNumber
  12034. * @module ng
  12035. * @kind function
  12036. *
  12037. * @description
  12038. * Determines if a reference is a `Number`.
  12039. *
  12040. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  12041. *
  12042. * If you wish to exclude these then you can use the native
  12043. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  12044. * method.
  12045. *
  12046. * @param {*} value Reference to check.
  12047. * @returns {boolean} True if `value` is a `Number`.
  12048. */
  12049. function isNumber(value) {return typeof value === 'number';}
  12050. /**
  12051. * @ngdoc function
  12052. * @name angular.isDate
  12053. * @module ng
  12054. * @kind function
  12055. *
  12056. * @description
  12057. * Determines if a value is a date.
  12058. *
  12059. * @param {*} value Reference to check.
  12060. * @returns {boolean} True if `value` is a `Date`.
  12061. */
  12062. function isDate(value) {
  12063. return toString.call(value) === '[object Date]';
  12064. }
  12065. /**
  12066. * @ngdoc function
  12067. * @name angular.isArray
  12068. * @module ng
  12069. * @kind function
  12070. *
  12071. * @description
  12072. * Determines if a reference is an `Array`.
  12073. *
  12074. * @param {*} value Reference to check.
  12075. * @returns {boolean} True if `value` is an `Array`.
  12076. */
  12077. var isArray = Array.isArray;
  12078. /**
  12079. * @ngdoc function
  12080. * @name angular.isFunction
  12081. * @module ng
  12082. * @kind function
  12083. *
  12084. * @description
  12085. * Determines if a reference is a `Function`.
  12086. *
  12087. * @param {*} value Reference to check.
  12088. * @returns {boolean} True if `value` is a `Function`.
  12089. */
  12090. function isFunction(value) {return typeof value === 'function';}
  12091. /**
  12092. * Determines if a value is a regular expression object.
  12093. *
  12094. * @private
  12095. * @param {*} value Reference to check.
  12096. * @returns {boolean} True if `value` is a `RegExp`.
  12097. */
  12098. function isRegExp(value) {
  12099. return toString.call(value) === '[object RegExp]';
  12100. }
  12101. /**
  12102. * Checks if `obj` is a window object.
  12103. *
  12104. * @private
  12105. * @param {*} obj Object to check
  12106. * @returns {boolean} True if `obj` is a window obj.
  12107. */
  12108. function isWindow(obj) {
  12109. return obj && obj.window === obj;
  12110. }
  12111. function isScope(obj) {
  12112. return obj && obj.$evalAsync && obj.$watch;
  12113. }
  12114. function isFile(obj) {
  12115. return toString.call(obj) === '[object File]';
  12116. }
  12117. function isFormData(obj) {
  12118. return toString.call(obj) === '[object FormData]';
  12119. }
  12120. function isBlob(obj) {
  12121. return toString.call(obj) === '[object Blob]';
  12122. }
  12123. function isBoolean(value) {
  12124. return typeof value === 'boolean';
  12125. }
  12126. function isPromiseLike(obj) {
  12127. return obj && isFunction(obj.then);
  12128. }
  12129. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  12130. function isTypedArray(value) {
  12131. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  12132. }
  12133. function isArrayBuffer(obj) {
  12134. return toString.call(obj) === '[object ArrayBuffer]';
  12135. }
  12136. var trim = function(value) {
  12137. return isString(value) ? value.trim() : value;
  12138. };
  12139. // Copied from:
  12140. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  12141. // Prereq: s is a string.
  12142. var escapeForRegexp = function(s) {
  12143. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  12144. replace(/\x08/g, '\\x08');
  12145. };
  12146. /**
  12147. * @ngdoc function
  12148. * @name angular.isElement
  12149. * @module ng
  12150. * @kind function
  12151. *
  12152. * @description
  12153. * Determines if a reference is a DOM element (or wrapped jQuery element).
  12154. *
  12155. * @param {*} value Reference to check.
  12156. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  12157. */
  12158. function isElement(node) {
  12159. return !!(node &&
  12160. (node.nodeName // we are a direct element
  12161. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  12162. }
  12163. /**
  12164. * @param str 'key1,key2,...'
  12165. * @returns {object} in the form of {key1:true, key2:true, ...}
  12166. */
  12167. function makeMap(str) {
  12168. var obj = {}, items = str.split(','), i;
  12169. for (i = 0; i < items.length; i++) {
  12170. obj[items[i]] = true;
  12171. }
  12172. return obj;
  12173. }
  12174. function nodeName_(element) {
  12175. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  12176. }
  12177. function includes(array, obj) {
  12178. return Array.prototype.indexOf.call(array, obj) != -1;
  12179. }
  12180. function arrayRemove(array, value) {
  12181. var index = array.indexOf(value);
  12182. if (index >= 0) {
  12183. array.splice(index, 1);
  12184. }
  12185. return index;
  12186. }
  12187. /**
  12188. * @ngdoc function
  12189. * @name angular.copy
  12190. * @module ng
  12191. * @kind function
  12192. *
  12193. * @description
  12194. * Creates a deep copy of `source`, which should be an object or an array.
  12195. *
  12196. * * If no destination is supplied, a copy of the object or array is created.
  12197. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  12198. * are deleted and then all elements/properties from the source are copied to it.
  12199. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  12200. * * If `source` is identical to 'destination' an exception will be thrown.
  12201. *
  12202. * @param {*} source The source that will be used to make a copy.
  12203. * Can be any type, including primitives, `null`, and `undefined`.
  12204. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  12205. * provided, must be of the same type as `source`.
  12206. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  12207. *
  12208. * @example
  12209. <example module="copyExample">
  12210. <file name="index.html">
  12211. <div ng-controller="ExampleController">
  12212. <form novalidate class="simple-form">
  12213. Name: <input type="text" ng-model="user.name" /><br />
  12214. E-mail: <input type="email" ng-model="user.email" /><br />
  12215. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  12216. <input type="radio" ng-model="user.gender" value="female" />female<br />
  12217. <button ng-click="reset()">RESET</button>
  12218. <button ng-click="update(user)">SAVE</button>
  12219. </form>
  12220. <pre>form = {{user | json}}</pre>
  12221. <pre>master = {{master | json}}</pre>
  12222. </div>
  12223. <script>
  12224. angular.module('copyExample', [])
  12225. .controller('ExampleController', ['$scope', function($scope) {
  12226. $scope.master= {};
  12227. $scope.update = function(user) {
  12228. // Example with 1 argument
  12229. $scope.master= angular.copy(user);
  12230. };
  12231. $scope.reset = function() {
  12232. // Example with 2 arguments
  12233. angular.copy($scope.master, $scope.user);
  12234. };
  12235. $scope.reset();
  12236. }]);
  12237. </script>
  12238. </file>
  12239. </example>
  12240. */
  12241. function copy(source, destination) {
  12242. var stackSource = [];
  12243. var stackDest = [];
  12244. if (destination) {
  12245. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  12246. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  12247. }
  12248. if (source === destination) {
  12249. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  12250. }
  12251. // Empty the destination object
  12252. if (isArray(destination)) {
  12253. destination.length = 0;
  12254. } else {
  12255. forEach(destination, function(value, key) {
  12256. if (key !== '$$hashKey') {
  12257. delete destination[key];
  12258. }
  12259. });
  12260. }
  12261. stackSource.push(source);
  12262. stackDest.push(destination);
  12263. return copyRecurse(source, destination);
  12264. }
  12265. return copyElement(source);
  12266. function copyRecurse(source, destination) {
  12267. var h = destination.$$hashKey;
  12268. var key;
  12269. if (isArray(source)) {
  12270. for (var i = 0, ii = source.length; i < ii; i++) {
  12271. destination.push(copyElement(source[i]));
  12272. }
  12273. } else if (isBlankObject(source)) {
  12274. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  12275. for (key in source) {
  12276. destination[key] = copyElement(source[key]);
  12277. }
  12278. } else if (source && typeof source.hasOwnProperty === 'function') {
  12279. // Slow path, which must rely on hasOwnProperty
  12280. for (key in source) {
  12281. if (source.hasOwnProperty(key)) {
  12282. destination[key] = copyElement(source[key]);
  12283. }
  12284. }
  12285. } else {
  12286. // Slowest path --- hasOwnProperty can't be called as a method
  12287. for (key in source) {
  12288. if (hasOwnProperty.call(source, key)) {
  12289. destination[key] = copyElement(source[key]);
  12290. }
  12291. }
  12292. }
  12293. setHashKey(destination, h);
  12294. return destination;
  12295. }
  12296. function copyElement(source) {
  12297. // Simple values
  12298. if (!isObject(source)) {
  12299. return source;
  12300. }
  12301. // Already copied values
  12302. var index = stackSource.indexOf(source);
  12303. if (index !== -1) {
  12304. return stackDest[index];
  12305. }
  12306. if (isWindow(source) || isScope(source)) {
  12307. throw ngMinErr('cpws',
  12308. "Can't copy! Making copies of Window or Scope instances is not supported.");
  12309. }
  12310. var needsRecurse = false;
  12311. var destination = copyType(source);
  12312. if (destination === undefined) {
  12313. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  12314. needsRecurse = true;
  12315. }
  12316. stackSource.push(source);
  12317. stackDest.push(destination);
  12318. return needsRecurse
  12319. ? copyRecurse(source, destination)
  12320. : destination;
  12321. }
  12322. function copyType(source) {
  12323. switch (toString.call(source)) {
  12324. case '[object Int8Array]':
  12325. case '[object Int16Array]':
  12326. case '[object Int32Array]':
  12327. case '[object Float32Array]':
  12328. case '[object Float64Array]':
  12329. case '[object Uint8Array]':
  12330. case '[object Uint8ClampedArray]':
  12331. case '[object Uint16Array]':
  12332. case '[object Uint32Array]':
  12333. return new source.constructor(copyElement(source.buffer));
  12334. case '[object ArrayBuffer]':
  12335. //Support: IE10
  12336. if (!source.slice) {
  12337. var copied = new ArrayBuffer(source.byteLength);
  12338. new Uint8Array(copied).set(new Uint8Array(source));
  12339. return copied;
  12340. }
  12341. return source.slice(0);
  12342. case '[object Boolean]':
  12343. case '[object Number]':
  12344. case '[object String]':
  12345. case '[object Date]':
  12346. return new source.constructor(source.valueOf());
  12347. case '[object RegExp]':
  12348. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  12349. re.lastIndex = source.lastIndex;
  12350. return re;
  12351. case '[object Blob]':
  12352. return new source.constructor([source], {type: source.type});
  12353. }
  12354. if (isFunction(source.cloneNode)) {
  12355. return source.cloneNode(true);
  12356. }
  12357. }
  12358. }
  12359. /**
  12360. * Creates a shallow copy of an object, an array or a primitive.
  12361. *
  12362. * Assumes that there are no proto properties for objects.
  12363. */
  12364. function shallowCopy(src, dst) {
  12365. if (isArray(src)) {
  12366. dst = dst || [];
  12367. for (var i = 0, ii = src.length; i < ii; i++) {
  12368. dst[i] = src[i];
  12369. }
  12370. } else if (isObject(src)) {
  12371. dst = dst || {};
  12372. for (var key in src) {
  12373. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  12374. dst[key] = src[key];
  12375. }
  12376. }
  12377. }
  12378. return dst || src;
  12379. }
  12380. /**
  12381. * @ngdoc function
  12382. * @name angular.equals
  12383. * @module ng
  12384. * @kind function
  12385. *
  12386. * @description
  12387. * Determines if two objects or two values are equivalent. Supports value types, regular
  12388. * expressions, arrays and objects.
  12389. *
  12390. * Two objects or values are considered equivalent if at least one of the following is true:
  12391. *
  12392. * * Both objects or values pass `===` comparison.
  12393. * * Both objects or values are of the same type and all of their properties are equal by
  12394. * comparing them with `angular.equals`.
  12395. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  12396. * * Both values represent the same regular expression (In JavaScript,
  12397. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  12398. * representation matches).
  12399. *
  12400. * During a property comparison, properties of `function` type and properties with names
  12401. * that begin with `$` are ignored.
  12402. *
  12403. * Scope and DOMWindow objects are being compared only by identify (`===`).
  12404. *
  12405. * @param {*} o1 Object or value to compare.
  12406. * @param {*} o2 Object or value to compare.
  12407. * @returns {boolean} True if arguments are equal.
  12408. */
  12409. function equals(o1, o2) {
  12410. if (o1 === o2) return true;
  12411. if (o1 === null || o2 === null) return false;
  12412. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  12413. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  12414. if (t1 == t2 && t1 == 'object') {
  12415. if (isArray(o1)) {
  12416. if (!isArray(o2)) return false;
  12417. if ((length = o1.length) == o2.length) {
  12418. for (key = 0; key < length; key++) {
  12419. if (!equals(o1[key], o2[key])) return false;
  12420. }
  12421. return true;
  12422. }
  12423. } else if (isDate(o1)) {
  12424. if (!isDate(o2)) return false;
  12425. return equals(o1.getTime(), o2.getTime());
  12426. } else if (isRegExp(o1)) {
  12427. if (!isRegExp(o2)) return false;
  12428. return o1.toString() == o2.toString();
  12429. } else {
  12430. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  12431. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  12432. keySet = createMap();
  12433. for (key in o1) {
  12434. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  12435. if (!equals(o1[key], o2[key])) return false;
  12436. keySet[key] = true;
  12437. }
  12438. for (key in o2) {
  12439. if (!(key in keySet) &&
  12440. key.charAt(0) !== '$' &&
  12441. isDefined(o2[key]) &&
  12442. !isFunction(o2[key])) return false;
  12443. }
  12444. return true;
  12445. }
  12446. }
  12447. return false;
  12448. }
  12449. var csp = function() {
  12450. if (!isDefined(csp.rules)) {
  12451. var ngCspElement = (document.querySelector('[ng-csp]') ||
  12452. document.querySelector('[data-ng-csp]'));
  12453. if (ngCspElement) {
  12454. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  12455. ngCspElement.getAttribute('data-ng-csp');
  12456. csp.rules = {
  12457. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  12458. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  12459. };
  12460. } else {
  12461. csp.rules = {
  12462. noUnsafeEval: noUnsafeEval(),
  12463. noInlineStyle: false
  12464. };
  12465. }
  12466. }
  12467. return csp.rules;
  12468. function noUnsafeEval() {
  12469. try {
  12470. /* jshint -W031, -W054 */
  12471. new Function('');
  12472. /* jshint +W031, +W054 */
  12473. return false;
  12474. } catch (e) {
  12475. return true;
  12476. }
  12477. }
  12478. };
  12479. /**
  12480. * @ngdoc directive
  12481. * @module ng
  12482. * @name ngJq
  12483. *
  12484. * @element ANY
  12485. * @param {string=} ngJq the name of the library available under `window`
  12486. * to be used for angular.element
  12487. * @description
  12488. * Use this directive to force the angular.element library. This should be
  12489. * used to force either jqLite by leaving ng-jq blank or setting the name of
  12490. * the jquery variable under window (eg. jQuery).
  12491. *
  12492. * Since angular looks for this directive when it is loaded (doesn't wait for the
  12493. * DOMContentLoaded event), it must be placed on an element that comes before the script
  12494. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  12495. * others ignored.
  12496. *
  12497. * @example
  12498. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  12499. ```html
  12500. <!doctype html>
  12501. <html ng-app ng-jq>
  12502. ...
  12503. ...
  12504. </html>
  12505. ```
  12506. * @example
  12507. * This example shows how to use a jQuery based library of a different name.
  12508. * The library name must be available at the top most 'window'.
  12509. ```html
  12510. <!doctype html>
  12511. <html ng-app ng-jq="jQueryLib">
  12512. ...
  12513. ...
  12514. </html>
  12515. ```
  12516. */
  12517. var jq = function() {
  12518. if (isDefined(jq.name_)) return jq.name_;
  12519. var el;
  12520. var i, ii = ngAttrPrefixes.length, prefix, name;
  12521. for (i = 0; i < ii; ++i) {
  12522. prefix = ngAttrPrefixes[i];
  12523. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  12524. name = el.getAttribute(prefix + 'jq');
  12525. break;
  12526. }
  12527. }
  12528. return (jq.name_ = name);
  12529. };
  12530. function concat(array1, array2, index) {
  12531. return array1.concat(slice.call(array2, index));
  12532. }
  12533. function sliceArgs(args, startIndex) {
  12534. return slice.call(args, startIndex || 0);
  12535. }
  12536. /* jshint -W101 */
  12537. /**
  12538. * @ngdoc function
  12539. * @name angular.bind
  12540. * @module ng
  12541. * @kind function
  12542. *
  12543. * @description
  12544. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  12545. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  12546. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  12547. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  12548. *
  12549. * @param {Object} self Context which `fn` should be evaluated in.
  12550. * @param {function()} fn Function to be bound.
  12551. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  12552. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  12553. */
  12554. /* jshint +W101 */
  12555. function bind(self, fn) {
  12556. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  12557. if (isFunction(fn) && !(fn instanceof RegExp)) {
  12558. return curryArgs.length
  12559. ? function() {
  12560. return arguments.length
  12561. ? fn.apply(self, concat(curryArgs, arguments, 0))
  12562. : fn.apply(self, curryArgs);
  12563. }
  12564. : function() {
  12565. return arguments.length
  12566. ? fn.apply(self, arguments)
  12567. : fn.call(self);
  12568. };
  12569. } else {
  12570. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  12571. return fn;
  12572. }
  12573. }
  12574. function toJsonReplacer(key, value) {
  12575. var val = value;
  12576. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  12577. val = undefined;
  12578. } else if (isWindow(value)) {
  12579. val = '$WINDOW';
  12580. } else if (value && document === value) {
  12581. val = '$DOCUMENT';
  12582. } else if (isScope(value)) {
  12583. val = '$SCOPE';
  12584. }
  12585. return val;
  12586. }
  12587. /**
  12588. * @ngdoc function
  12589. * @name angular.toJson
  12590. * @module ng
  12591. * @kind function
  12592. *
  12593. * @description
  12594. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  12595. * stripped since angular uses this notation internally.
  12596. *
  12597. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  12598. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  12599. * If set to an integer, the JSON output will contain that many spaces per indentation.
  12600. * @returns {string|undefined} JSON-ified string representing `obj`.
  12601. */
  12602. function toJson(obj, pretty) {
  12603. if (isUndefined(obj)) return undefined;
  12604. if (!isNumber(pretty)) {
  12605. pretty = pretty ? 2 : null;
  12606. }
  12607. return JSON.stringify(obj, toJsonReplacer, pretty);
  12608. }
  12609. /**
  12610. * @ngdoc function
  12611. * @name angular.fromJson
  12612. * @module ng
  12613. * @kind function
  12614. *
  12615. * @description
  12616. * Deserializes a JSON string.
  12617. *
  12618. * @param {string} json JSON string to deserialize.
  12619. * @returns {Object|Array|string|number} Deserialized JSON string.
  12620. */
  12621. function fromJson(json) {
  12622. return isString(json)
  12623. ? JSON.parse(json)
  12624. : json;
  12625. }
  12626. var ALL_COLONS = /:/g;
  12627. function timezoneToOffset(timezone, fallback) {
  12628. // IE/Edge do not "understand" colon (`:`) in timezone
  12629. timezone = timezone.replace(ALL_COLONS, '');
  12630. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  12631. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  12632. }
  12633. function addDateMinutes(date, minutes) {
  12634. date = new Date(date.getTime());
  12635. date.setMinutes(date.getMinutes() + minutes);
  12636. return date;
  12637. }
  12638. function convertTimezoneToLocal(date, timezone, reverse) {
  12639. reverse = reverse ? -1 : 1;
  12640. var dateTimezoneOffset = date.getTimezoneOffset();
  12641. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  12642. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  12643. }
  12644. /**
  12645. * @returns {string} Returns the string representation of the element.
  12646. */
  12647. function startingTag(element) {
  12648. element = jqLite(element).clone();
  12649. try {
  12650. // turns out IE does not let you set .html() on elements which
  12651. // are not allowed to have children. So we just ignore it.
  12652. element.empty();
  12653. } catch (e) {}
  12654. var elemHtml = jqLite('<div>').append(element).html();
  12655. try {
  12656. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  12657. elemHtml.
  12658. match(/^(<[^>]+>)/)[1].
  12659. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  12660. } catch (e) {
  12661. return lowercase(elemHtml);
  12662. }
  12663. }
  12664. /////////////////////////////////////////////////
  12665. /**
  12666. * Tries to decode the URI component without throwing an exception.
  12667. *
  12668. * @private
  12669. * @param str value potential URI component to check.
  12670. * @returns {boolean} True if `value` can be decoded
  12671. * with the decodeURIComponent function.
  12672. */
  12673. function tryDecodeURIComponent(value) {
  12674. try {
  12675. return decodeURIComponent(value);
  12676. } catch (e) {
  12677. // Ignore any invalid uri component
  12678. }
  12679. }
  12680. /**
  12681. * Parses an escaped url query string into key-value pairs.
  12682. * @returns {Object.<string,boolean|Array>}
  12683. */
  12684. function parseKeyValue(/**string*/keyValue) {
  12685. var obj = {};
  12686. forEach((keyValue || "").split('&'), function(keyValue) {
  12687. var splitPoint, key, val;
  12688. if (keyValue) {
  12689. key = keyValue = keyValue.replace(/\+/g,'%20');
  12690. splitPoint = keyValue.indexOf('=');
  12691. if (splitPoint !== -1) {
  12692. key = keyValue.substring(0, splitPoint);
  12693. val = keyValue.substring(splitPoint + 1);
  12694. }
  12695. key = tryDecodeURIComponent(key);
  12696. if (isDefined(key)) {
  12697. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  12698. if (!hasOwnProperty.call(obj, key)) {
  12699. obj[key] = val;
  12700. } else if (isArray(obj[key])) {
  12701. obj[key].push(val);
  12702. } else {
  12703. obj[key] = [obj[key],val];
  12704. }
  12705. }
  12706. }
  12707. });
  12708. return obj;
  12709. }
  12710. function toKeyValue(obj) {
  12711. var parts = [];
  12712. forEach(obj, function(value, key) {
  12713. if (isArray(value)) {
  12714. forEach(value, function(arrayValue) {
  12715. parts.push(encodeUriQuery(key, true) +
  12716. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  12717. });
  12718. } else {
  12719. parts.push(encodeUriQuery(key, true) +
  12720. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  12721. }
  12722. });
  12723. return parts.length ? parts.join('&') : '';
  12724. }
  12725. /**
  12726. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  12727. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  12728. * segments:
  12729. * segment = *pchar
  12730. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  12731. * pct-encoded = "%" HEXDIG HEXDIG
  12732. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  12733. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  12734. * / "*" / "+" / "," / ";" / "="
  12735. */
  12736. function encodeUriSegment(val) {
  12737. return encodeUriQuery(val, true).
  12738. replace(/%26/gi, '&').
  12739. replace(/%3D/gi, '=').
  12740. replace(/%2B/gi, '+');
  12741. }
  12742. /**
  12743. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  12744. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  12745. * encoded per http://tools.ietf.org/html/rfc3986:
  12746. * query = *( pchar / "/" / "?" )
  12747. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  12748. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  12749. * pct-encoded = "%" HEXDIG HEXDIG
  12750. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  12751. * / "*" / "+" / "," / ";" / "="
  12752. */
  12753. function encodeUriQuery(val, pctEncodeSpaces) {
  12754. return encodeURIComponent(val).
  12755. replace(/%40/gi, '@').
  12756. replace(/%3A/gi, ':').
  12757. replace(/%24/g, '$').
  12758. replace(/%2C/gi, ',').
  12759. replace(/%3B/gi, ';').
  12760. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  12761. }
  12762. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  12763. function getNgAttribute(element, ngAttr) {
  12764. var attr, i, ii = ngAttrPrefixes.length;
  12765. for (i = 0; i < ii; ++i) {
  12766. attr = ngAttrPrefixes[i] + ngAttr;
  12767. if (isString(attr = element.getAttribute(attr))) {
  12768. return attr;
  12769. }
  12770. }
  12771. return null;
  12772. }
  12773. /**
  12774. * @ngdoc directive
  12775. * @name ngApp
  12776. * @module ng
  12777. *
  12778. * @element ANY
  12779. * @param {angular.Module} ngApp an optional application
  12780. * {@link angular.module module} name to load.
  12781. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  12782. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  12783. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  12784. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  12785. * tracking down the root of these bugs.
  12786. *
  12787. * @description
  12788. *
  12789. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  12790. * designates the **root element** of the application and is typically placed near the root element
  12791. * of the page - e.g. on the `<body>` or `<html>` tags.
  12792. *
  12793. * There are a few things to keep in mind when using `ngApp`:
  12794. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  12795. * found in the document will be used to define the root element to auto-bootstrap as an
  12796. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  12797. * {@link angular.bootstrap} instead.
  12798. * - AngularJS applications cannot be nested within each other.
  12799. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  12800. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  12801. * {@link ngRoute.ngView `ngView`}.
  12802. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  12803. * causing animations to stop working and making the injector inaccessible from outside the app.
  12804. *
  12805. * You can specify an **AngularJS module** to be used as the root module for the application. This
  12806. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  12807. * should contain the application code needed or have dependencies on other modules that will
  12808. * contain the code. See {@link angular.module} for more information.
  12809. *
  12810. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  12811. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  12812. * would not be resolved to `3`.
  12813. *
  12814. * `ngApp` is the easiest, and most common way to bootstrap an application.
  12815. *
  12816. <example module="ngAppDemo">
  12817. <file name="index.html">
  12818. <div ng-controller="ngAppDemoController">
  12819. I can add: {{a}} + {{b}} = {{ a+b }}
  12820. </div>
  12821. </file>
  12822. <file name="script.js">
  12823. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  12824. $scope.a = 1;
  12825. $scope.b = 2;
  12826. });
  12827. </file>
  12828. </example>
  12829. *
  12830. * Using `ngStrictDi`, you would see something like this:
  12831. *
  12832. <example ng-app-included="true">
  12833. <file name="index.html">
  12834. <div ng-app="ngAppStrictDemo" ng-strict-di>
  12835. <div ng-controller="GoodController1">
  12836. I can add: {{a}} + {{b}} = {{ a+b }}
  12837. <p>This renders because the controller does not fail to
  12838. instantiate, by using explicit annotation style (see
  12839. script.js for details)
  12840. </p>
  12841. </div>
  12842. <div ng-controller="GoodController2">
  12843. Name: <input ng-model="name"><br />
  12844. Hello, {{name}}!
  12845. <p>This renders because the controller does not fail to
  12846. instantiate, by using explicit annotation style
  12847. (see script.js for details)
  12848. </p>
  12849. </div>
  12850. <div ng-controller="BadController">
  12851. I can add: {{a}} + {{b}} = {{ a+b }}
  12852. <p>The controller could not be instantiated, due to relying
  12853. on automatic function annotations (which are disabled in
  12854. strict mode). As such, the content of this section is not
  12855. interpolated, and there should be an error in your web console.
  12856. </p>
  12857. </div>
  12858. </div>
  12859. </file>
  12860. <file name="script.js">
  12861. angular.module('ngAppStrictDemo', [])
  12862. // BadController will fail to instantiate, due to relying on automatic function annotation,
  12863. // rather than an explicit annotation
  12864. .controller('BadController', function($scope) {
  12865. $scope.a = 1;
  12866. $scope.b = 2;
  12867. })
  12868. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  12869. // due to using explicit annotations using the array style and $inject property, respectively.
  12870. .controller('GoodController1', ['$scope', function($scope) {
  12871. $scope.a = 1;
  12872. $scope.b = 2;
  12873. }])
  12874. .controller('GoodController2', GoodController2);
  12875. function GoodController2($scope) {
  12876. $scope.name = "World";
  12877. }
  12878. GoodController2.$inject = ['$scope'];
  12879. </file>
  12880. <file name="style.css">
  12881. div[ng-controller] {
  12882. margin-bottom: 1em;
  12883. -webkit-border-radius: 4px;
  12884. border-radius: 4px;
  12885. border: 1px solid;
  12886. padding: .5em;
  12887. }
  12888. div[ng-controller^=Good] {
  12889. border-color: #d6e9c6;
  12890. background-color: #dff0d8;
  12891. color: #3c763d;
  12892. }
  12893. div[ng-controller^=Bad] {
  12894. border-color: #ebccd1;
  12895. background-color: #f2dede;
  12896. color: #a94442;
  12897. margin-bottom: 0;
  12898. }
  12899. </file>
  12900. </example>
  12901. */
  12902. function angularInit(element, bootstrap) {
  12903. var appElement,
  12904. module,
  12905. config = {};
  12906. // The element `element` has priority over any other element
  12907. forEach(ngAttrPrefixes, function(prefix) {
  12908. var name = prefix + 'app';
  12909. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  12910. appElement = element;
  12911. module = element.getAttribute(name);
  12912. }
  12913. });
  12914. forEach(ngAttrPrefixes, function(prefix) {
  12915. var name = prefix + 'app';
  12916. var candidate;
  12917. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  12918. appElement = candidate;
  12919. module = candidate.getAttribute(name);
  12920. }
  12921. });
  12922. if (appElement) {
  12923. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  12924. bootstrap(appElement, module ? [module] : [], config);
  12925. }
  12926. }
  12927. /**
  12928. * @ngdoc function
  12929. * @name angular.bootstrap
  12930. * @module ng
  12931. * @description
  12932. * Use this function to manually start up angular application.
  12933. *
  12934. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  12935. *
  12936. * Angular will detect if it has been loaded into the browser more than once and only allow the
  12937. * first loaded script to be bootstrapped and will report a warning to the browser console for
  12938. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  12939. * multiple instances of Angular try to work on the DOM.
  12940. *
  12941. * <div class="alert alert-warning">
  12942. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  12943. * They must use {@link ng.directive:ngApp ngApp}.
  12944. * </div>
  12945. *
  12946. * <div class="alert alert-warning">
  12947. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  12948. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  12949. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  12950. * causing animations to stop working and making the injector inaccessible from outside the app.
  12951. * </div>
  12952. *
  12953. * ```html
  12954. * <!doctype html>
  12955. * <html>
  12956. * <body>
  12957. * <div ng-controller="WelcomeController">
  12958. * {{greeting}}
  12959. * </div>
  12960. *
  12961. * <script src="angular.js"></script>
  12962. * <script>
  12963. * var app = angular.module('demo', [])
  12964. * .controller('WelcomeController', function($scope) {
  12965. * $scope.greeting = 'Welcome!';
  12966. * });
  12967. * angular.bootstrap(document, ['demo']);
  12968. * </script>
  12969. * </body>
  12970. * </html>
  12971. * ```
  12972. *
  12973. * @param {DOMElement} element DOM element which is the root of angular application.
  12974. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  12975. * Each item in the array should be the name of a predefined module or a (DI annotated)
  12976. * function that will be invoked by the injector as a `config` block.
  12977. * See: {@link angular.module modules}
  12978. * @param {Object=} config an object for defining configuration options for the application. The
  12979. * following keys are supported:
  12980. *
  12981. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  12982. * assist in finding bugs which break minified code. Defaults to `false`.
  12983. *
  12984. * @returns {auto.$injector} Returns the newly created injector for this app.
  12985. */
  12986. function bootstrap(element, modules, config) {
  12987. if (!isObject(config)) config = {};
  12988. var defaultConfig = {
  12989. strictDi: false
  12990. };
  12991. config = extend(defaultConfig, config);
  12992. var doBootstrap = function() {
  12993. element = jqLite(element);
  12994. if (element.injector()) {
  12995. var tag = (element[0] === document) ? 'document' : startingTag(element);
  12996. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  12997. throw ngMinErr(
  12998. 'btstrpd',
  12999. "App Already Bootstrapped with this Element '{0}'",
  13000. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  13001. }
  13002. modules = modules || [];
  13003. modules.unshift(['$provide', function($provide) {
  13004. $provide.value('$rootElement', element);
  13005. }]);
  13006. if (config.debugInfoEnabled) {
  13007. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  13008. modules.push(['$compileProvider', function($compileProvider) {
  13009. $compileProvider.debugInfoEnabled(true);
  13010. }]);
  13011. }
  13012. modules.unshift('ng');
  13013. var injector = createInjector(modules, config.strictDi);
  13014. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  13015. function bootstrapApply(scope, element, compile, injector) {
  13016. scope.$apply(function() {
  13017. element.data('$injector', injector);
  13018. compile(element)(scope);
  13019. });
  13020. }]
  13021. );
  13022. return injector;
  13023. };
  13024. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  13025. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  13026. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  13027. config.debugInfoEnabled = true;
  13028. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  13029. }
  13030. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  13031. return doBootstrap();
  13032. }
  13033. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  13034. angular.resumeBootstrap = function(extraModules) {
  13035. forEach(extraModules, function(module) {
  13036. modules.push(module);
  13037. });
  13038. return doBootstrap();
  13039. };
  13040. if (isFunction(angular.resumeDeferredBootstrap)) {
  13041. angular.resumeDeferredBootstrap();
  13042. }
  13043. }
  13044. /**
  13045. * @ngdoc function
  13046. * @name angular.reloadWithDebugInfo
  13047. * @module ng
  13048. * @description
  13049. * Use this function to reload the current application with debug information turned on.
  13050. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  13051. *
  13052. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  13053. */
  13054. function reloadWithDebugInfo() {
  13055. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  13056. window.location.reload();
  13057. }
  13058. /**
  13059. * @name angular.getTestability
  13060. * @module ng
  13061. * @description
  13062. * Get the testability service for the instance of Angular on the given
  13063. * element.
  13064. * @param {DOMElement} element DOM element which is the root of angular application.
  13065. */
  13066. function getTestability(rootElement) {
  13067. var injector = angular.element(rootElement).injector();
  13068. if (!injector) {
  13069. throw ngMinErr('test',
  13070. 'no injector found for element argument to getTestability');
  13071. }
  13072. return injector.get('$$testability');
  13073. }
  13074. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  13075. function snake_case(name, separator) {
  13076. separator = separator || '_';
  13077. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  13078. return (pos ? separator : '') + letter.toLowerCase();
  13079. });
  13080. }
  13081. var bindJQueryFired = false;
  13082. function bindJQuery() {
  13083. var originalCleanData;
  13084. if (bindJQueryFired) {
  13085. return;
  13086. }
  13087. // bind to jQuery if present;
  13088. var jqName = jq();
  13089. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  13090. !jqName ? undefined : // use jqLite
  13091. window[jqName]; // use jQuery specified by `ngJq`
  13092. // Use jQuery if it exists with proper functionality, otherwise default to us.
  13093. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  13094. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  13095. // versions. It will not work for sure with jQuery <1.7, though.
  13096. if (jQuery && jQuery.fn.on) {
  13097. jqLite = jQuery;
  13098. extend(jQuery.fn, {
  13099. scope: JQLitePrototype.scope,
  13100. isolateScope: JQLitePrototype.isolateScope,
  13101. controller: JQLitePrototype.controller,
  13102. injector: JQLitePrototype.injector,
  13103. inheritedData: JQLitePrototype.inheritedData
  13104. });
  13105. // All nodes removed from the DOM via various jQuery APIs like .remove()
  13106. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  13107. // the $destroy event on all removed nodes.
  13108. originalCleanData = jQuery.cleanData;
  13109. jQuery.cleanData = function(elems) {
  13110. var events;
  13111. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  13112. events = jQuery._data(elem, "events");
  13113. if (events && events.$destroy) {
  13114. jQuery(elem).triggerHandler('$destroy');
  13115. }
  13116. }
  13117. originalCleanData(elems);
  13118. };
  13119. } else {
  13120. jqLite = JQLite;
  13121. }
  13122. angular.element = jqLite;
  13123. // Prevent double-proxying.
  13124. bindJQueryFired = true;
  13125. }
  13126. /**
  13127. * throw error if the argument is falsy.
  13128. */
  13129. function assertArg(arg, name, reason) {
  13130. if (!arg) {
  13131. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  13132. }
  13133. return arg;
  13134. }
  13135. function assertArgFn(arg, name, acceptArrayAnnotation) {
  13136. if (acceptArrayAnnotation && isArray(arg)) {
  13137. arg = arg[arg.length - 1];
  13138. }
  13139. assertArg(isFunction(arg), name, 'not a function, got ' +
  13140. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  13141. return arg;
  13142. }
  13143. /**
  13144. * throw error if the name given is hasOwnProperty
  13145. * @param {String} name the name to test
  13146. * @param {String} context the context in which the name is used, such as module or directive
  13147. */
  13148. function assertNotHasOwnProperty(name, context) {
  13149. if (name === 'hasOwnProperty') {
  13150. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  13151. }
  13152. }
  13153. /**
  13154. * Return the value accessible from the object by path. Any undefined traversals are ignored
  13155. * @param {Object} obj starting object
  13156. * @param {String} path path to traverse
  13157. * @param {boolean} [bindFnToScope=true]
  13158. * @returns {Object} value as accessible by path
  13159. */
  13160. //TODO(misko): this function needs to be removed
  13161. function getter(obj, path, bindFnToScope) {
  13162. if (!path) return obj;
  13163. var keys = path.split('.');
  13164. var key;
  13165. var lastInstance = obj;
  13166. var len = keys.length;
  13167. for (var i = 0; i < len; i++) {
  13168. key = keys[i];
  13169. if (obj) {
  13170. obj = (lastInstance = obj)[key];
  13171. }
  13172. }
  13173. if (!bindFnToScope && isFunction(obj)) {
  13174. return bind(lastInstance, obj);
  13175. }
  13176. return obj;
  13177. }
  13178. /**
  13179. * Return the DOM siblings between the first and last node in the given array.
  13180. * @param {Array} array like object
  13181. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  13182. */
  13183. function getBlockNodes(nodes) {
  13184. // TODO(perf): update `nodes` instead of creating a new object?
  13185. var node = nodes[0];
  13186. var endNode = nodes[nodes.length - 1];
  13187. var blockNodes;
  13188. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  13189. if (blockNodes || nodes[i] !== node) {
  13190. if (!blockNodes) {
  13191. blockNodes = jqLite(slice.call(nodes, 0, i));
  13192. }
  13193. blockNodes.push(node);
  13194. }
  13195. }
  13196. return blockNodes || nodes;
  13197. }
  13198. /**
  13199. * Creates a new object without a prototype. This object is useful for lookup without having to
  13200. * guard against prototypically inherited properties via hasOwnProperty.
  13201. *
  13202. * Related micro-benchmarks:
  13203. * - http://jsperf.com/object-create2
  13204. * - http://jsperf.com/proto-map-lookup/2
  13205. * - http://jsperf.com/for-in-vs-object-keys2
  13206. *
  13207. * @returns {Object}
  13208. */
  13209. function createMap() {
  13210. return Object.create(null);
  13211. }
  13212. var NODE_TYPE_ELEMENT = 1;
  13213. var NODE_TYPE_ATTRIBUTE = 2;
  13214. var NODE_TYPE_TEXT = 3;
  13215. var NODE_TYPE_COMMENT = 8;
  13216. var NODE_TYPE_DOCUMENT = 9;
  13217. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  13218. /**
  13219. * @ngdoc type
  13220. * @name angular.Module
  13221. * @module ng
  13222. * @description
  13223. *
  13224. * Interface for configuring angular {@link angular.module modules}.
  13225. */
  13226. function setupModuleLoader(window) {
  13227. var $injectorMinErr = minErr('$injector');
  13228. var ngMinErr = minErr('ng');
  13229. function ensure(obj, name, factory) {
  13230. return obj[name] || (obj[name] = factory());
  13231. }
  13232. var angular = ensure(window, 'angular', Object);
  13233. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  13234. angular.$$minErr = angular.$$minErr || minErr;
  13235. return ensure(angular, 'module', function() {
  13236. /** @type {Object.<string, angular.Module>} */
  13237. var modules = {};
  13238. /**
  13239. * @ngdoc function
  13240. * @name angular.module
  13241. * @module ng
  13242. * @description
  13243. *
  13244. * The `angular.module` is a global place for creating, registering and retrieving Angular
  13245. * modules.
  13246. * All modules (angular core or 3rd party) that should be available to an application must be
  13247. * registered using this mechanism.
  13248. *
  13249. * Passing one argument retrieves an existing {@link angular.Module},
  13250. * whereas passing more than one argument creates a new {@link angular.Module}
  13251. *
  13252. *
  13253. * # Module
  13254. *
  13255. * A module is a collection of services, directives, controllers, filters, and configuration information.
  13256. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  13257. *
  13258. * ```js
  13259. * // Create a new module
  13260. * var myModule = angular.module('myModule', []);
  13261. *
  13262. * // register a new service
  13263. * myModule.value('appName', 'MyCoolApp');
  13264. *
  13265. * // configure existing services inside initialization blocks.
  13266. * myModule.config(['$locationProvider', function($locationProvider) {
  13267. * // Configure existing providers
  13268. * $locationProvider.hashPrefix('!');
  13269. * }]);
  13270. * ```
  13271. *
  13272. * Then you can create an injector and load your modules like this:
  13273. *
  13274. * ```js
  13275. * var injector = angular.injector(['ng', 'myModule'])
  13276. * ```
  13277. *
  13278. * However it's more likely that you'll just use
  13279. * {@link ng.directive:ngApp ngApp} or
  13280. * {@link angular.bootstrap} to simplify this process for you.
  13281. *
  13282. * @param {!string} name The name of the module to create or retrieve.
  13283. * @param {!Array.<string>=} requires If specified then new module is being created. If
  13284. * unspecified then the module is being retrieved for further configuration.
  13285. * @param {Function=} configFn Optional configuration function for the module. Same as
  13286. * {@link angular.Module#config Module#config()}.
  13287. * @returns {angular.Module} new module with the {@link angular.Module} api.
  13288. */
  13289. return function module(name, requires, configFn) {
  13290. var assertNotHasOwnProperty = function(name, context) {
  13291. if (name === 'hasOwnProperty') {
  13292. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  13293. }
  13294. };
  13295. assertNotHasOwnProperty(name, 'module');
  13296. if (requires && modules.hasOwnProperty(name)) {
  13297. modules[name] = null;
  13298. }
  13299. return ensure(modules, name, function() {
  13300. if (!requires) {
  13301. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  13302. "the module name or forgot to load it. If registering a module ensure that you " +
  13303. "specify the dependencies as the second argument.", name);
  13304. }
  13305. /** @type {!Array.<Array.<*>>} */
  13306. var invokeQueue = [];
  13307. /** @type {!Array.<Function>} */
  13308. var configBlocks = [];
  13309. /** @type {!Array.<Function>} */
  13310. var runBlocks = [];
  13311. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  13312. /** @type {angular.Module} */
  13313. var moduleInstance = {
  13314. // Private state
  13315. _invokeQueue: invokeQueue,
  13316. _configBlocks: configBlocks,
  13317. _runBlocks: runBlocks,
  13318. /**
  13319. * @ngdoc property
  13320. * @name angular.Module#requires
  13321. * @module ng
  13322. *
  13323. * @description
  13324. * Holds the list of modules which the injector will load before the current module is
  13325. * loaded.
  13326. */
  13327. requires: requires,
  13328. /**
  13329. * @ngdoc property
  13330. * @name angular.Module#name
  13331. * @module ng
  13332. *
  13333. * @description
  13334. * Name of the module.
  13335. */
  13336. name: name,
  13337. /**
  13338. * @ngdoc method
  13339. * @name angular.Module#provider
  13340. * @module ng
  13341. * @param {string} name service name
  13342. * @param {Function} providerType Construction function for creating new instance of the
  13343. * service.
  13344. * @description
  13345. * See {@link auto.$provide#provider $provide.provider()}.
  13346. */
  13347. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  13348. /**
  13349. * @ngdoc method
  13350. * @name angular.Module#factory
  13351. * @module ng
  13352. * @param {string} name service name
  13353. * @param {Function} providerFunction Function for creating new instance of the service.
  13354. * @description
  13355. * See {@link auto.$provide#factory $provide.factory()}.
  13356. */
  13357. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  13358. /**
  13359. * @ngdoc method
  13360. * @name angular.Module#service
  13361. * @module ng
  13362. * @param {string} name service name
  13363. * @param {Function} constructor A constructor function that will be instantiated.
  13364. * @description
  13365. * See {@link auto.$provide#service $provide.service()}.
  13366. */
  13367. service: invokeLaterAndSetModuleName('$provide', 'service'),
  13368. /**
  13369. * @ngdoc method
  13370. * @name angular.Module#value
  13371. * @module ng
  13372. * @param {string} name service name
  13373. * @param {*} object Service instance object.
  13374. * @description
  13375. * See {@link auto.$provide#value $provide.value()}.
  13376. */
  13377. value: invokeLater('$provide', 'value'),
  13378. /**
  13379. * @ngdoc method
  13380. * @name angular.Module#constant
  13381. * @module ng
  13382. * @param {string} name constant name
  13383. * @param {*} object Constant value.
  13384. * @description
  13385. * Because the constants are fixed, they get applied before other provide methods.
  13386. * See {@link auto.$provide#constant $provide.constant()}.
  13387. */
  13388. constant: invokeLater('$provide', 'constant', 'unshift'),
  13389. /**
  13390. * @ngdoc method
  13391. * @name angular.Module#decorator
  13392. * @module ng
  13393. * @param {string} The name of the service to decorate.
  13394. * @param {Function} This function will be invoked when the service needs to be
  13395. * instantiated and should return the decorated service instance.
  13396. * @description
  13397. * See {@link auto.$provide#decorator $provide.decorator()}.
  13398. */
  13399. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  13400. /**
  13401. * @ngdoc method
  13402. * @name angular.Module#animation
  13403. * @module ng
  13404. * @param {string} name animation name
  13405. * @param {Function} animationFactory Factory function for creating new instance of an
  13406. * animation.
  13407. * @description
  13408. *
  13409. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  13410. *
  13411. *
  13412. * Defines an animation hook that can be later used with
  13413. * {@link $animate $animate} service and directives that use this service.
  13414. *
  13415. * ```js
  13416. * module.animation('.animation-name', function($inject1, $inject2) {
  13417. * return {
  13418. * eventName : function(element, done) {
  13419. * //code to run the animation
  13420. * //once complete, then run done()
  13421. * return function cancellationFunction(element) {
  13422. * //code to cancel the animation
  13423. * }
  13424. * }
  13425. * }
  13426. * })
  13427. * ```
  13428. *
  13429. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  13430. * {@link ngAnimate ngAnimate module} for more information.
  13431. */
  13432. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  13433. /**
  13434. * @ngdoc method
  13435. * @name angular.Module#filter
  13436. * @module ng
  13437. * @param {string} name Filter name - this must be a valid angular expression identifier
  13438. * @param {Function} filterFactory Factory function for creating new instance of filter.
  13439. * @description
  13440. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  13441. *
  13442. * <div class="alert alert-warning">
  13443. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  13444. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  13445. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  13446. * (`myapp_subsection_filterx`).
  13447. * </div>
  13448. */
  13449. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  13450. /**
  13451. * @ngdoc method
  13452. * @name angular.Module#controller
  13453. * @module ng
  13454. * @param {string|Object} name Controller name, or an object map of controllers where the
  13455. * keys are the names and the values are the constructors.
  13456. * @param {Function} constructor Controller constructor function.
  13457. * @description
  13458. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  13459. */
  13460. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  13461. /**
  13462. * @ngdoc method
  13463. * @name angular.Module#directive
  13464. * @module ng
  13465. * @param {string|Object} name Directive name, or an object map of directives where the
  13466. * keys are the names and the values are the factories.
  13467. * @param {Function} directiveFactory Factory function for creating new instance of
  13468. * directives.
  13469. * @description
  13470. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  13471. */
  13472. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  13473. /**
  13474. * @ngdoc method
  13475. * @name angular.Module#component
  13476. * @module ng
  13477. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  13478. * @param {Object} options Component definition object (a simplified
  13479. * {@link ng.$compile#directive-definition-object directive definition object})
  13480. *
  13481. * @description
  13482. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  13483. */
  13484. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  13485. /**
  13486. * @ngdoc method
  13487. * @name angular.Module#config
  13488. * @module ng
  13489. * @param {Function} configFn Execute this function on module load. Useful for service
  13490. * configuration.
  13491. * @description
  13492. * Use this method to register work which needs to be performed on module loading.
  13493. * For more about how to configure services, see
  13494. * {@link providers#provider-recipe Provider Recipe}.
  13495. */
  13496. config: config,
  13497. /**
  13498. * @ngdoc method
  13499. * @name angular.Module#run
  13500. * @module ng
  13501. * @param {Function} initializationFn Execute this function after injector creation.
  13502. * Useful for application initialization.
  13503. * @description
  13504. * Use this method to register work which should be performed when the injector is done
  13505. * loading all modules.
  13506. */
  13507. run: function(block) {
  13508. runBlocks.push(block);
  13509. return this;
  13510. }
  13511. };
  13512. if (configFn) {
  13513. config(configFn);
  13514. }
  13515. return moduleInstance;
  13516. /**
  13517. * @param {string} provider
  13518. * @param {string} method
  13519. * @param {String=} insertMethod
  13520. * @returns {angular.Module}
  13521. */
  13522. function invokeLater(provider, method, insertMethod, queue) {
  13523. if (!queue) queue = invokeQueue;
  13524. return function() {
  13525. queue[insertMethod || 'push']([provider, method, arguments]);
  13526. return moduleInstance;
  13527. };
  13528. }
  13529. /**
  13530. * @param {string} provider
  13531. * @param {string} method
  13532. * @returns {angular.Module}
  13533. */
  13534. function invokeLaterAndSetModuleName(provider, method) {
  13535. return function(recipeName, factoryFunction) {
  13536. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  13537. invokeQueue.push([provider, method, arguments]);
  13538. return moduleInstance;
  13539. };
  13540. }
  13541. });
  13542. };
  13543. });
  13544. }
  13545. /* global: toDebugString: true */
  13546. function serializeObject(obj) {
  13547. var seen = [];
  13548. return JSON.stringify(obj, function(key, val) {
  13549. val = toJsonReplacer(key, val);
  13550. if (isObject(val)) {
  13551. if (seen.indexOf(val) >= 0) return '...';
  13552. seen.push(val);
  13553. }
  13554. return val;
  13555. });
  13556. }
  13557. function toDebugString(obj) {
  13558. if (typeof obj === 'function') {
  13559. return obj.toString().replace(/ \{[\s\S]*$/, '');
  13560. } else if (isUndefined(obj)) {
  13561. return 'undefined';
  13562. } else if (typeof obj !== 'string') {
  13563. return serializeObject(obj);
  13564. }
  13565. return obj;
  13566. }
  13567. /* global angularModule: true,
  13568. version: true,
  13569. $CompileProvider,
  13570. htmlAnchorDirective,
  13571. inputDirective,
  13572. inputDirective,
  13573. formDirective,
  13574. scriptDirective,
  13575. selectDirective,
  13576. styleDirective,
  13577. optionDirective,
  13578. ngBindDirective,
  13579. ngBindHtmlDirective,
  13580. ngBindTemplateDirective,
  13581. ngClassDirective,
  13582. ngClassEvenDirective,
  13583. ngClassOddDirective,
  13584. ngCloakDirective,
  13585. ngControllerDirective,
  13586. ngFormDirective,
  13587. ngHideDirective,
  13588. ngIfDirective,
  13589. ngIncludeDirective,
  13590. ngIncludeFillContentDirective,
  13591. ngInitDirective,
  13592. ngNonBindableDirective,
  13593. ngPluralizeDirective,
  13594. ngRepeatDirective,
  13595. ngShowDirective,
  13596. ngStyleDirective,
  13597. ngSwitchDirective,
  13598. ngSwitchWhenDirective,
  13599. ngSwitchDefaultDirective,
  13600. ngOptionsDirective,
  13601. ngTranscludeDirective,
  13602. ngModelDirective,
  13603. ngListDirective,
  13604. ngChangeDirective,
  13605. patternDirective,
  13606. patternDirective,
  13607. requiredDirective,
  13608. requiredDirective,
  13609. minlengthDirective,
  13610. minlengthDirective,
  13611. maxlengthDirective,
  13612. maxlengthDirective,
  13613. ngValueDirective,
  13614. ngModelOptionsDirective,
  13615. ngAttributeAliasDirectives,
  13616. ngEventDirectives,
  13617. $AnchorScrollProvider,
  13618. $AnimateProvider,
  13619. $CoreAnimateCssProvider,
  13620. $$CoreAnimateJsProvider,
  13621. $$CoreAnimateQueueProvider,
  13622. $$AnimateRunnerFactoryProvider,
  13623. $$AnimateAsyncRunFactoryProvider,
  13624. $BrowserProvider,
  13625. $CacheFactoryProvider,
  13626. $ControllerProvider,
  13627. $DateProvider,
  13628. $DocumentProvider,
  13629. $ExceptionHandlerProvider,
  13630. $FilterProvider,
  13631. $$ForceReflowProvider,
  13632. $InterpolateProvider,
  13633. $IntervalProvider,
  13634. $$HashMapProvider,
  13635. $HttpProvider,
  13636. $HttpParamSerializerProvider,
  13637. $HttpParamSerializerJQLikeProvider,
  13638. $HttpBackendProvider,
  13639. $xhrFactoryProvider,
  13640. $LocationProvider,
  13641. $LogProvider,
  13642. $ParseProvider,
  13643. $RootScopeProvider,
  13644. $QProvider,
  13645. $$QProvider,
  13646. $$SanitizeUriProvider,
  13647. $SceProvider,
  13648. $SceDelegateProvider,
  13649. $SnifferProvider,
  13650. $TemplateCacheProvider,
  13651. $TemplateRequestProvider,
  13652. $$TestabilityProvider,
  13653. $TimeoutProvider,
  13654. $$RAFProvider,
  13655. $WindowProvider,
  13656. $$jqLiteProvider,
  13657. $$CookieReaderProvider
  13658. */
  13659. /**
  13660. * @ngdoc object
  13661. * @name angular.version
  13662. * @module ng
  13663. * @description
  13664. * An object that contains information about the current AngularJS version.
  13665. *
  13666. * This object has the following properties:
  13667. *
  13668. * - `full` – `{string}` – Full version string, such as "0.9.18".
  13669. * - `major` – `{number}` – Major version number, such as "0".
  13670. * - `minor` – `{number}` – Minor version number, such as "9".
  13671. * - `dot` – `{number}` – Dot version number, such as "18".
  13672. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  13673. */
  13674. var version = {
  13675. full: '1.5.3', // all of these placeholder strings will be replaced by grunt's
  13676. major: 1, // package task
  13677. minor: 5,
  13678. dot: 3,
  13679. codeName: 'diplohaplontic-meiosis'
  13680. };
  13681. function publishExternalAPI(angular) {
  13682. extend(angular, {
  13683. 'bootstrap': bootstrap,
  13684. 'copy': copy,
  13685. 'extend': extend,
  13686. 'merge': merge,
  13687. 'equals': equals,
  13688. 'element': jqLite,
  13689. 'forEach': forEach,
  13690. 'injector': createInjector,
  13691. 'noop': noop,
  13692. 'bind': bind,
  13693. 'toJson': toJson,
  13694. 'fromJson': fromJson,
  13695. 'identity': identity,
  13696. 'isUndefined': isUndefined,
  13697. 'isDefined': isDefined,
  13698. 'isString': isString,
  13699. 'isFunction': isFunction,
  13700. 'isObject': isObject,
  13701. 'isNumber': isNumber,
  13702. 'isElement': isElement,
  13703. 'isArray': isArray,
  13704. 'version': version,
  13705. 'isDate': isDate,
  13706. 'lowercase': lowercase,
  13707. 'uppercase': uppercase,
  13708. 'callbacks': {counter: 0},
  13709. 'getTestability': getTestability,
  13710. '$$minErr': minErr,
  13711. '$$csp': csp,
  13712. 'reloadWithDebugInfo': reloadWithDebugInfo
  13713. });
  13714. angularModule = setupModuleLoader(window);
  13715. angularModule('ng', ['ngLocale'], ['$provide',
  13716. function ngModule($provide) {
  13717. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  13718. $provide.provider({
  13719. $$sanitizeUri: $$SanitizeUriProvider
  13720. });
  13721. $provide.provider('$compile', $CompileProvider).
  13722. directive({
  13723. a: htmlAnchorDirective,
  13724. input: inputDirective,
  13725. textarea: inputDirective,
  13726. form: formDirective,
  13727. script: scriptDirective,
  13728. select: selectDirective,
  13729. style: styleDirective,
  13730. option: optionDirective,
  13731. ngBind: ngBindDirective,
  13732. ngBindHtml: ngBindHtmlDirective,
  13733. ngBindTemplate: ngBindTemplateDirective,
  13734. ngClass: ngClassDirective,
  13735. ngClassEven: ngClassEvenDirective,
  13736. ngClassOdd: ngClassOddDirective,
  13737. ngCloak: ngCloakDirective,
  13738. ngController: ngControllerDirective,
  13739. ngForm: ngFormDirective,
  13740. ngHide: ngHideDirective,
  13741. ngIf: ngIfDirective,
  13742. ngInclude: ngIncludeDirective,
  13743. ngInit: ngInitDirective,
  13744. ngNonBindable: ngNonBindableDirective,
  13745. ngPluralize: ngPluralizeDirective,
  13746. ngRepeat: ngRepeatDirective,
  13747. ngShow: ngShowDirective,
  13748. ngStyle: ngStyleDirective,
  13749. ngSwitch: ngSwitchDirective,
  13750. ngSwitchWhen: ngSwitchWhenDirective,
  13751. ngSwitchDefault: ngSwitchDefaultDirective,
  13752. ngOptions: ngOptionsDirective,
  13753. ngTransclude: ngTranscludeDirective,
  13754. ngModel: ngModelDirective,
  13755. ngList: ngListDirective,
  13756. ngChange: ngChangeDirective,
  13757. pattern: patternDirective,
  13758. ngPattern: patternDirective,
  13759. required: requiredDirective,
  13760. ngRequired: requiredDirective,
  13761. minlength: minlengthDirective,
  13762. ngMinlength: minlengthDirective,
  13763. maxlength: maxlengthDirective,
  13764. ngMaxlength: maxlengthDirective,
  13765. ngValue: ngValueDirective,
  13766. ngModelOptions: ngModelOptionsDirective
  13767. }).
  13768. directive({
  13769. ngInclude: ngIncludeFillContentDirective
  13770. }).
  13771. directive(ngAttributeAliasDirectives).
  13772. directive(ngEventDirectives);
  13773. $provide.provider({
  13774. $anchorScroll: $AnchorScrollProvider,
  13775. $animate: $AnimateProvider,
  13776. $animateCss: $CoreAnimateCssProvider,
  13777. $$animateJs: $$CoreAnimateJsProvider,
  13778. $$animateQueue: $$CoreAnimateQueueProvider,
  13779. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  13780. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  13781. $browser: $BrowserProvider,
  13782. $cacheFactory: $CacheFactoryProvider,
  13783. $controller: $ControllerProvider,
  13784. $document: $DocumentProvider,
  13785. $exceptionHandler: $ExceptionHandlerProvider,
  13786. $filter: $FilterProvider,
  13787. $$forceReflow: $$ForceReflowProvider,
  13788. $interpolate: $InterpolateProvider,
  13789. $interval: $IntervalProvider,
  13790. $http: $HttpProvider,
  13791. $httpParamSerializer: $HttpParamSerializerProvider,
  13792. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  13793. $httpBackend: $HttpBackendProvider,
  13794. $xhrFactory: $xhrFactoryProvider,
  13795. $location: $LocationProvider,
  13796. $log: $LogProvider,
  13797. $parse: $ParseProvider,
  13798. $rootScope: $RootScopeProvider,
  13799. $q: $QProvider,
  13800. $$q: $$QProvider,
  13801. $sce: $SceProvider,
  13802. $sceDelegate: $SceDelegateProvider,
  13803. $sniffer: $SnifferProvider,
  13804. $templateCache: $TemplateCacheProvider,
  13805. $templateRequest: $TemplateRequestProvider,
  13806. $$testability: $$TestabilityProvider,
  13807. $timeout: $TimeoutProvider,
  13808. $window: $WindowProvider,
  13809. $$rAF: $$RAFProvider,
  13810. $$jqLite: $$jqLiteProvider,
  13811. $$HashMap: $$HashMapProvider,
  13812. $$cookieReader: $$CookieReaderProvider
  13813. });
  13814. }
  13815. ]);
  13816. }
  13817. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13818. * Any commits to this file should be reviewed with security in mind. *
  13819. * Changes to this file can potentially create security vulnerabilities. *
  13820. * An approval from 2 Core members with history of modifying *
  13821. * this file is required. *
  13822. * *
  13823. * Does the change somehow allow for arbitrary javascript to be executed? *
  13824. * Or allows for someone to change the prototype of built-in objects? *
  13825. * Or gives undesired access to variables likes document or window? *
  13826. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13827. /* global JQLitePrototype: true,
  13828. addEventListenerFn: true,
  13829. removeEventListenerFn: true,
  13830. BOOLEAN_ATTR: true,
  13831. ALIASED_ATTR: true,
  13832. */
  13833. //////////////////////////////////
  13834. //JQLite
  13835. //////////////////////////////////
  13836. /**
  13837. * @ngdoc function
  13838. * @name angular.element
  13839. * @module ng
  13840. * @kind function
  13841. *
  13842. * @description
  13843. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  13844. *
  13845. * If jQuery is available, `angular.element` is an alias for the
  13846. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  13847. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  13848. *
  13849. * jqLite is a tiny, API-compatible subset of jQuery that allows
  13850. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  13851. * commonly needed functionality with the goal of having a very small footprint.
  13852. *
  13853. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  13854. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  13855. * specific version of jQuery if multiple versions exist on the page.
  13856. *
  13857. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  13858. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  13859. *
  13860. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  13861. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  13862. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  13863. *
  13864. * ## Angular's jqLite
  13865. * jqLite provides only the following jQuery methods:
  13866. *
  13867. * - [`addClass()`](http://api.jquery.com/addClass/)
  13868. * - [`after()`](http://api.jquery.com/after/)
  13869. * - [`append()`](http://api.jquery.com/append/)
  13870. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  13871. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  13872. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  13873. * - [`clone()`](http://api.jquery.com/clone/)
  13874. * - [`contents()`](http://api.jquery.com/contents/)
  13875. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  13876. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  13877. * - [`data()`](http://api.jquery.com/data/)
  13878. * - [`detach()`](http://api.jquery.com/detach/)
  13879. * - [`empty()`](http://api.jquery.com/empty/)
  13880. * - [`eq()`](http://api.jquery.com/eq/)
  13881. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  13882. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  13883. * - [`html()`](http://api.jquery.com/html/)
  13884. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  13885. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  13886. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  13887. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  13888. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  13889. * - [`prepend()`](http://api.jquery.com/prepend/)
  13890. * - [`prop()`](http://api.jquery.com/prop/)
  13891. * - [`ready()`](http://api.jquery.com/ready/)
  13892. * - [`remove()`](http://api.jquery.com/remove/)
  13893. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  13894. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  13895. * - [`removeData()`](http://api.jquery.com/removeData/)
  13896. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  13897. * - [`text()`](http://api.jquery.com/text/)
  13898. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  13899. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  13900. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  13901. * - [`val()`](http://api.jquery.com/val/)
  13902. * - [`wrap()`](http://api.jquery.com/wrap/)
  13903. *
  13904. * ## jQuery/jqLite Extras
  13905. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  13906. *
  13907. * ### Events
  13908. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  13909. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  13910. * element before it is removed.
  13911. *
  13912. * ### Methods
  13913. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  13914. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  13915. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  13916. * `'ngModel'`).
  13917. * - `injector()` - retrieves the injector of the current element or its parent.
  13918. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  13919. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  13920. * be enabled.
  13921. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  13922. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  13923. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  13924. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  13925. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  13926. * parent element is reached.
  13927. *
  13928. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  13929. * @returns {Object} jQuery object.
  13930. */
  13931. JQLite.expando = 'ng339';
  13932. var jqCache = JQLite.cache = {},
  13933. jqId = 1,
  13934. addEventListenerFn = function(element, type, fn) {
  13935. element.addEventListener(type, fn, false);
  13936. },
  13937. removeEventListenerFn = function(element, type, fn) {
  13938. element.removeEventListener(type, fn, false);
  13939. };
  13940. /*
  13941. * !!! This is an undocumented "private" function !!!
  13942. */
  13943. JQLite._data = function(node) {
  13944. //jQuery always returns an object on cache miss
  13945. return this.cache[node[this.expando]] || {};
  13946. };
  13947. function jqNextId() { return ++jqId; }
  13948. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  13949. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  13950. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  13951. var jqLiteMinErr = minErr('jqLite');
  13952. /**
  13953. * Converts snake_case to camelCase.
  13954. * Also there is special case for Moz prefix starting with upper case letter.
  13955. * @param name Name to normalize
  13956. */
  13957. function camelCase(name) {
  13958. return name.
  13959. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  13960. return offset ? letter.toUpperCase() : letter;
  13961. }).
  13962. replace(MOZ_HACK_REGEXP, 'Moz$1');
  13963. }
  13964. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  13965. var HTML_REGEXP = /<|&#?\w+;/;
  13966. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  13967. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  13968. var wrapMap = {
  13969. 'option': [1, '<select multiple="multiple">', '</select>'],
  13970. 'thead': [1, '<table>', '</table>'],
  13971. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  13972. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  13973. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  13974. '_default': [0, "", ""]
  13975. };
  13976. wrapMap.optgroup = wrapMap.option;
  13977. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  13978. wrapMap.th = wrapMap.td;
  13979. function jqLiteIsTextNode(html) {
  13980. return !HTML_REGEXP.test(html);
  13981. }
  13982. function jqLiteAcceptsData(node) {
  13983. // The window object can accept data but has no nodeType
  13984. // Otherwise we are only interested in elements (1) and documents (9)
  13985. var nodeType = node.nodeType;
  13986. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  13987. }
  13988. function jqLiteHasData(node) {
  13989. for (var key in jqCache[node.ng339]) {
  13990. return true;
  13991. }
  13992. return false;
  13993. }
  13994. function jqLiteCleanData(nodes) {
  13995. for (var i = 0, ii = nodes.length; i < ii; i++) {
  13996. jqLiteRemoveData(nodes[i]);
  13997. }
  13998. }
  13999. function jqLiteBuildFragment(html, context) {
  14000. var tmp, tag, wrap,
  14001. fragment = context.createDocumentFragment(),
  14002. nodes = [], i;
  14003. if (jqLiteIsTextNode(html)) {
  14004. // Convert non-html into a text node
  14005. nodes.push(context.createTextNode(html));
  14006. } else {
  14007. // Convert html into DOM nodes
  14008. tmp = tmp || fragment.appendChild(context.createElement("div"));
  14009. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  14010. wrap = wrapMap[tag] || wrapMap._default;
  14011. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  14012. // Descend through wrappers to the right content
  14013. i = wrap[0];
  14014. while (i--) {
  14015. tmp = tmp.lastChild;
  14016. }
  14017. nodes = concat(nodes, tmp.childNodes);
  14018. tmp = fragment.firstChild;
  14019. tmp.textContent = "";
  14020. }
  14021. // Remove wrapper from fragment
  14022. fragment.textContent = "";
  14023. fragment.innerHTML = ""; // Clear inner HTML
  14024. forEach(nodes, function(node) {
  14025. fragment.appendChild(node);
  14026. });
  14027. return fragment;
  14028. }
  14029. function jqLiteParseHTML(html, context) {
  14030. context = context || document;
  14031. var parsed;
  14032. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  14033. return [context.createElement(parsed[1])];
  14034. }
  14035. if ((parsed = jqLiteBuildFragment(html, context))) {
  14036. return parsed.childNodes;
  14037. }
  14038. return [];
  14039. }
  14040. function jqLiteWrapNode(node, wrapper) {
  14041. var parent = node.parentNode;
  14042. if (parent) {
  14043. parent.replaceChild(wrapper, node);
  14044. }
  14045. wrapper.appendChild(node);
  14046. }
  14047. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  14048. var jqLiteContains = Node.prototype.contains || function(arg) {
  14049. // jshint bitwise: false
  14050. return !!(this.compareDocumentPosition(arg) & 16);
  14051. // jshint bitwise: true
  14052. };
  14053. /////////////////////////////////////////////
  14054. function JQLite(element) {
  14055. if (element instanceof JQLite) {
  14056. return element;
  14057. }
  14058. var argIsString;
  14059. if (isString(element)) {
  14060. element = trim(element);
  14061. argIsString = true;
  14062. }
  14063. if (!(this instanceof JQLite)) {
  14064. if (argIsString && element.charAt(0) != '<') {
  14065. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  14066. }
  14067. return new JQLite(element);
  14068. }
  14069. if (argIsString) {
  14070. jqLiteAddNodes(this, jqLiteParseHTML(element));
  14071. } else {
  14072. jqLiteAddNodes(this, element);
  14073. }
  14074. }
  14075. function jqLiteClone(element) {
  14076. return element.cloneNode(true);
  14077. }
  14078. function jqLiteDealoc(element, onlyDescendants) {
  14079. if (!onlyDescendants) jqLiteRemoveData(element);
  14080. if (element.querySelectorAll) {
  14081. var descendants = element.querySelectorAll('*');
  14082. for (var i = 0, l = descendants.length; i < l; i++) {
  14083. jqLiteRemoveData(descendants[i]);
  14084. }
  14085. }
  14086. }
  14087. function jqLiteOff(element, type, fn, unsupported) {
  14088. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  14089. var expandoStore = jqLiteExpandoStore(element);
  14090. var events = expandoStore && expandoStore.events;
  14091. var handle = expandoStore && expandoStore.handle;
  14092. if (!handle) return; //no listeners registered
  14093. if (!type) {
  14094. for (type in events) {
  14095. if (type !== '$destroy') {
  14096. removeEventListenerFn(element, type, handle);
  14097. }
  14098. delete events[type];
  14099. }
  14100. } else {
  14101. var removeHandler = function(type) {
  14102. var listenerFns = events[type];
  14103. if (isDefined(fn)) {
  14104. arrayRemove(listenerFns || [], fn);
  14105. }
  14106. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  14107. removeEventListenerFn(element, type, handle);
  14108. delete events[type];
  14109. }
  14110. };
  14111. forEach(type.split(' '), function(type) {
  14112. removeHandler(type);
  14113. if (MOUSE_EVENT_MAP[type]) {
  14114. removeHandler(MOUSE_EVENT_MAP[type]);
  14115. }
  14116. });
  14117. }
  14118. }
  14119. function jqLiteRemoveData(element, name) {
  14120. var expandoId = element.ng339;
  14121. var expandoStore = expandoId && jqCache[expandoId];
  14122. if (expandoStore) {
  14123. if (name) {
  14124. delete expandoStore.data[name];
  14125. return;
  14126. }
  14127. if (expandoStore.handle) {
  14128. if (expandoStore.events.$destroy) {
  14129. expandoStore.handle({}, '$destroy');
  14130. }
  14131. jqLiteOff(element);
  14132. }
  14133. delete jqCache[expandoId];
  14134. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  14135. }
  14136. }
  14137. function jqLiteExpandoStore(element, createIfNecessary) {
  14138. var expandoId = element.ng339,
  14139. expandoStore = expandoId && jqCache[expandoId];
  14140. if (createIfNecessary && !expandoStore) {
  14141. element.ng339 = expandoId = jqNextId();
  14142. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  14143. }
  14144. return expandoStore;
  14145. }
  14146. function jqLiteData(element, key, value) {
  14147. if (jqLiteAcceptsData(element)) {
  14148. var isSimpleSetter = isDefined(value);
  14149. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  14150. var massGetter = !key;
  14151. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  14152. var data = expandoStore && expandoStore.data;
  14153. if (isSimpleSetter) { // data('key', value)
  14154. data[key] = value;
  14155. } else {
  14156. if (massGetter) { // data()
  14157. return data;
  14158. } else {
  14159. if (isSimpleGetter) { // data('key')
  14160. // don't force creation of expandoStore if it doesn't exist yet
  14161. return data && data[key];
  14162. } else { // mass-setter: data({key1: val1, key2: val2})
  14163. extend(data, key);
  14164. }
  14165. }
  14166. }
  14167. }
  14168. }
  14169. function jqLiteHasClass(element, selector) {
  14170. if (!element.getAttribute) return false;
  14171. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  14172. indexOf(" " + selector + " ") > -1);
  14173. }
  14174. function jqLiteRemoveClass(element, cssClasses) {
  14175. if (cssClasses && element.setAttribute) {
  14176. forEach(cssClasses.split(' '), function(cssClass) {
  14177. element.setAttribute('class', trim(
  14178. (" " + (element.getAttribute('class') || '') + " ")
  14179. .replace(/[\n\t]/g, " ")
  14180. .replace(" " + trim(cssClass) + " ", " "))
  14181. );
  14182. });
  14183. }
  14184. }
  14185. function jqLiteAddClass(element, cssClasses) {
  14186. if (cssClasses && element.setAttribute) {
  14187. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  14188. .replace(/[\n\t]/g, " ");
  14189. forEach(cssClasses.split(' '), function(cssClass) {
  14190. cssClass = trim(cssClass);
  14191. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  14192. existingClasses += cssClass + ' ';
  14193. }
  14194. });
  14195. element.setAttribute('class', trim(existingClasses));
  14196. }
  14197. }
  14198. function jqLiteAddNodes(root, elements) {
  14199. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  14200. if (elements) {
  14201. // if a Node (the most common case)
  14202. if (elements.nodeType) {
  14203. root[root.length++] = elements;
  14204. } else {
  14205. var length = elements.length;
  14206. // if an Array or NodeList and not a Window
  14207. if (typeof length === 'number' && elements.window !== elements) {
  14208. if (length) {
  14209. for (var i = 0; i < length; i++) {
  14210. root[root.length++] = elements[i];
  14211. }
  14212. }
  14213. } else {
  14214. root[root.length++] = elements;
  14215. }
  14216. }
  14217. }
  14218. }
  14219. function jqLiteController(element, name) {
  14220. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  14221. }
  14222. function jqLiteInheritedData(element, name, value) {
  14223. // if element is the document object work with the html element instead
  14224. // this makes $(document).scope() possible
  14225. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  14226. element = element.documentElement;
  14227. }
  14228. var names = isArray(name) ? name : [name];
  14229. while (element) {
  14230. for (var i = 0, ii = names.length; i < ii; i++) {
  14231. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  14232. }
  14233. // If dealing with a document fragment node with a host element, and no parent, use the host
  14234. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  14235. // to lookup parent controllers.
  14236. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  14237. }
  14238. }
  14239. function jqLiteEmpty(element) {
  14240. jqLiteDealoc(element, true);
  14241. while (element.firstChild) {
  14242. element.removeChild(element.firstChild);
  14243. }
  14244. }
  14245. function jqLiteRemove(element, keepData) {
  14246. if (!keepData) jqLiteDealoc(element);
  14247. var parent = element.parentNode;
  14248. if (parent) parent.removeChild(element);
  14249. }
  14250. function jqLiteDocumentLoaded(action, win) {
  14251. win = win || window;
  14252. if (win.document.readyState === 'complete') {
  14253. // Force the action to be run async for consistent behavior
  14254. // from the action's point of view
  14255. // i.e. it will definitely not be in a $apply
  14256. win.setTimeout(action);
  14257. } else {
  14258. // No need to unbind this handler as load is only ever called once
  14259. jqLite(win).on('load', action);
  14260. }
  14261. }
  14262. //////////////////////////////////////////
  14263. // Functions which are declared directly.
  14264. //////////////////////////////////////////
  14265. var JQLitePrototype = JQLite.prototype = {
  14266. ready: function(fn) {
  14267. var fired = false;
  14268. function trigger() {
  14269. if (fired) return;
  14270. fired = true;
  14271. fn();
  14272. }
  14273. // check if document is already loaded
  14274. if (document.readyState === 'complete') {
  14275. setTimeout(trigger);
  14276. } else {
  14277. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  14278. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  14279. // jshint -W064
  14280. JQLite(window).on('load', trigger); // fallback to window.onload for others
  14281. // jshint +W064
  14282. }
  14283. },
  14284. toString: function() {
  14285. var value = [];
  14286. forEach(this, function(e) { value.push('' + e);});
  14287. return '[' + value.join(', ') + ']';
  14288. },
  14289. eq: function(index) {
  14290. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  14291. },
  14292. length: 0,
  14293. push: push,
  14294. sort: [].sort,
  14295. splice: [].splice
  14296. };
  14297. //////////////////////////////////////////
  14298. // Functions iterating getter/setters.
  14299. // these functions return self on setter and
  14300. // value on get.
  14301. //////////////////////////////////////////
  14302. var BOOLEAN_ATTR = {};
  14303. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  14304. BOOLEAN_ATTR[lowercase(value)] = value;
  14305. });
  14306. var BOOLEAN_ELEMENTS = {};
  14307. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  14308. BOOLEAN_ELEMENTS[value] = true;
  14309. });
  14310. var ALIASED_ATTR = {
  14311. 'ngMinlength': 'minlength',
  14312. 'ngMaxlength': 'maxlength',
  14313. 'ngMin': 'min',
  14314. 'ngMax': 'max',
  14315. 'ngPattern': 'pattern'
  14316. };
  14317. function getBooleanAttrName(element, name) {
  14318. // check dom last since we will most likely fail on name
  14319. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  14320. // booleanAttr is here twice to minimize DOM access
  14321. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  14322. }
  14323. function getAliasedAttrName(name) {
  14324. return ALIASED_ATTR[name];
  14325. }
  14326. forEach({
  14327. data: jqLiteData,
  14328. removeData: jqLiteRemoveData,
  14329. hasData: jqLiteHasData,
  14330. cleanData: jqLiteCleanData
  14331. }, function(fn, name) {
  14332. JQLite[name] = fn;
  14333. });
  14334. forEach({
  14335. data: jqLiteData,
  14336. inheritedData: jqLiteInheritedData,
  14337. scope: function(element) {
  14338. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  14339. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  14340. },
  14341. isolateScope: function(element) {
  14342. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  14343. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  14344. },
  14345. controller: jqLiteController,
  14346. injector: function(element) {
  14347. return jqLiteInheritedData(element, '$injector');
  14348. },
  14349. removeAttr: function(element, name) {
  14350. element.removeAttribute(name);
  14351. },
  14352. hasClass: jqLiteHasClass,
  14353. css: function(element, name, value) {
  14354. name = camelCase(name);
  14355. if (isDefined(value)) {
  14356. element.style[name] = value;
  14357. } else {
  14358. return element.style[name];
  14359. }
  14360. },
  14361. attr: function(element, name, value) {
  14362. var nodeType = element.nodeType;
  14363. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  14364. return;
  14365. }
  14366. var lowercasedName = lowercase(name);
  14367. if (BOOLEAN_ATTR[lowercasedName]) {
  14368. if (isDefined(value)) {
  14369. if (!!value) {
  14370. element[name] = true;
  14371. element.setAttribute(name, lowercasedName);
  14372. } else {
  14373. element[name] = false;
  14374. element.removeAttribute(lowercasedName);
  14375. }
  14376. } else {
  14377. return (element[name] ||
  14378. (element.attributes.getNamedItem(name) || noop).specified)
  14379. ? lowercasedName
  14380. : undefined;
  14381. }
  14382. } else if (isDefined(value)) {
  14383. element.setAttribute(name, value);
  14384. } else if (element.getAttribute) {
  14385. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  14386. // some elements (e.g. Document) don't have get attribute, so return undefined
  14387. var ret = element.getAttribute(name, 2);
  14388. // normalize non-existing attributes to undefined (as jQuery)
  14389. return ret === null ? undefined : ret;
  14390. }
  14391. },
  14392. prop: function(element, name, value) {
  14393. if (isDefined(value)) {
  14394. element[name] = value;
  14395. } else {
  14396. return element[name];
  14397. }
  14398. },
  14399. text: (function() {
  14400. getText.$dv = '';
  14401. return getText;
  14402. function getText(element, value) {
  14403. if (isUndefined(value)) {
  14404. var nodeType = element.nodeType;
  14405. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  14406. }
  14407. element.textContent = value;
  14408. }
  14409. })(),
  14410. val: function(element, value) {
  14411. if (isUndefined(value)) {
  14412. if (element.multiple && nodeName_(element) === 'select') {
  14413. var result = [];
  14414. forEach(element.options, function(option) {
  14415. if (option.selected) {
  14416. result.push(option.value || option.text);
  14417. }
  14418. });
  14419. return result.length === 0 ? null : result;
  14420. }
  14421. return element.value;
  14422. }
  14423. element.value = value;
  14424. },
  14425. html: function(element, value) {
  14426. if (isUndefined(value)) {
  14427. return element.innerHTML;
  14428. }
  14429. jqLiteDealoc(element, true);
  14430. element.innerHTML = value;
  14431. },
  14432. empty: jqLiteEmpty
  14433. }, function(fn, name) {
  14434. /**
  14435. * Properties: writes return selection, reads return first value
  14436. */
  14437. JQLite.prototype[name] = function(arg1, arg2) {
  14438. var i, key;
  14439. var nodeCount = this.length;
  14440. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  14441. // in a way that survives minification.
  14442. // jqLiteEmpty takes no arguments but is a setter.
  14443. if (fn !== jqLiteEmpty &&
  14444. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  14445. if (isObject(arg1)) {
  14446. // we are a write, but the object properties are the key/values
  14447. for (i = 0; i < nodeCount; i++) {
  14448. if (fn === jqLiteData) {
  14449. // data() takes the whole object in jQuery
  14450. fn(this[i], arg1);
  14451. } else {
  14452. for (key in arg1) {
  14453. fn(this[i], key, arg1[key]);
  14454. }
  14455. }
  14456. }
  14457. // return self for chaining
  14458. return this;
  14459. } else {
  14460. // we are a read, so read the first child.
  14461. // TODO: do we still need this?
  14462. var value = fn.$dv;
  14463. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  14464. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  14465. for (var j = 0; j < jj; j++) {
  14466. var nodeValue = fn(this[j], arg1, arg2);
  14467. value = value ? value + nodeValue : nodeValue;
  14468. }
  14469. return value;
  14470. }
  14471. } else {
  14472. // we are a write, so apply to all children
  14473. for (i = 0; i < nodeCount; i++) {
  14474. fn(this[i], arg1, arg2);
  14475. }
  14476. // return self for chaining
  14477. return this;
  14478. }
  14479. };
  14480. });
  14481. function createEventHandler(element, events) {
  14482. var eventHandler = function(event, type) {
  14483. // jQuery specific api
  14484. event.isDefaultPrevented = function() {
  14485. return event.defaultPrevented;
  14486. };
  14487. var eventFns = events[type || event.type];
  14488. var eventFnsLength = eventFns ? eventFns.length : 0;
  14489. if (!eventFnsLength) return;
  14490. if (isUndefined(event.immediatePropagationStopped)) {
  14491. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  14492. event.stopImmediatePropagation = function() {
  14493. event.immediatePropagationStopped = true;
  14494. if (event.stopPropagation) {
  14495. event.stopPropagation();
  14496. }
  14497. if (originalStopImmediatePropagation) {
  14498. originalStopImmediatePropagation.call(event);
  14499. }
  14500. };
  14501. }
  14502. event.isImmediatePropagationStopped = function() {
  14503. return event.immediatePropagationStopped === true;
  14504. };
  14505. // Some events have special handlers that wrap the real handler
  14506. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  14507. // Copy event handlers in case event handlers array is modified during execution.
  14508. if ((eventFnsLength > 1)) {
  14509. eventFns = shallowCopy(eventFns);
  14510. }
  14511. for (var i = 0; i < eventFnsLength; i++) {
  14512. if (!event.isImmediatePropagationStopped()) {
  14513. handlerWrapper(element, event, eventFns[i]);
  14514. }
  14515. }
  14516. };
  14517. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  14518. // events on `element`
  14519. eventHandler.elem = element;
  14520. return eventHandler;
  14521. }
  14522. function defaultHandlerWrapper(element, event, handler) {
  14523. handler.call(element, event);
  14524. }
  14525. function specialMouseHandlerWrapper(target, event, handler) {
  14526. // Refer to jQuery's implementation of mouseenter & mouseleave
  14527. // Read about mouseenter and mouseleave:
  14528. // http://www.quirksmode.org/js/events_mouse.html#link8
  14529. var related = event.relatedTarget;
  14530. // For mousenter/leave call the handler if related is outside the target.
  14531. // NB: No relatedTarget if the mouse left/entered the browser window
  14532. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  14533. handler.call(target, event);
  14534. }
  14535. }
  14536. //////////////////////////////////////////
  14537. // Functions iterating traversal.
  14538. // These functions chain results into a single
  14539. // selector.
  14540. //////////////////////////////////////////
  14541. forEach({
  14542. removeData: jqLiteRemoveData,
  14543. on: function jqLiteOn(element, type, fn, unsupported) {
  14544. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  14545. // Do not add event handlers to non-elements because they will not be cleaned up.
  14546. if (!jqLiteAcceptsData(element)) {
  14547. return;
  14548. }
  14549. var expandoStore = jqLiteExpandoStore(element, true);
  14550. var events = expandoStore.events;
  14551. var handle = expandoStore.handle;
  14552. if (!handle) {
  14553. handle = expandoStore.handle = createEventHandler(element, events);
  14554. }
  14555. // http://jsperf.com/string-indexof-vs-split
  14556. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  14557. var i = types.length;
  14558. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  14559. var eventFns = events[type];
  14560. if (!eventFns) {
  14561. eventFns = events[type] = [];
  14562. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  14563. if (type !== '$destroy' && !noEventListener) {
  14564. addEventListenerFn(element, type, handle);
  14565. }
  14566. }
  14567. eventFns.push(fn);
  14568. };
  14569. while (i--) {
  14570. type = types[i];
  14571. if (MOUSE_EVENT_MAP[type]) {
  14572. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  14573. addHandler(type, undefined, true);
  14574. } else {
  14575. addHandler(type);
  14576. }
  14577. }
  14578. },
  14579. off: jqLiteOff,
  14580. one: function(element, type, fn) {
  14581. element = jqLite(element);
  14582. //add the listener twice so that when it is called
  14583. //you can remove the original function and still be
  14584. //able to call element.off(ev, fn) normally
  14585. element.on(type, function onFn() {
  14586. element.off(type, fn);
  14587. element.off(type, onFn);
  14588. });
  14589. element.on(type, fn);
  14590. },
  14591. replaceWith: function(element, replaceNode) {
  14592. var index, parent = element.parentNode;
  14593. jqLiteDealoc(element);
  14594. forEach(new JQLite(replaceNode), function(node) {
  14595. if (index) {
  14596. parent.insertBefore(node, index.nextSibling);
  14597. } else {
  14598. parent.replaceChild(node, element);
  14599. }
  14600. index = node;
  14601. });
  14602. },
  14603. children: function(element) {
  14604. var children = [];
  14605. forEach(element.childNodes, function(element) {
  14606. if (element.nodeType === NODE_TYPE_ELEMENT) {
  14607. children.push(element);
  14608. }
  14609. });
  14610. return children;
  14611. },
  14612. contents: function(element) {
  14613. return element.contentDocument || element.childNodes || [];
  14614. },
  14615. append: function(element, node) {
  14616. var nodeType = element.nodeType;
  14617. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  14618. node = new JQLite(node);
  14619. for (var i = 0, ii = node.length; i < ii; i++) {
  14620. var child = node[i];
  14621. element.appendChild(child);
  14622. }
  14623. },
  14624. prepend: function(element, node) {
  14625. if (element.nodeType === NODE_TYPE_ELEMENT) {
  14626. var index = element.firstChild;
  14627. forEach(new JQLite(node), function(child) {
  14628. element.insertBefore(child, index);
  14629. });
  14630. }
  14631. },
  14632. wrap: function(element, wrapNode) {
  14633. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  14634. },
  14635. remove: jqLiteRemove,
  14636. detach: function(element) {
  14637. jqLiteRemove(element, true);
  14638. },
  14639. after: function(element, newElement) {
  14640. var index = element, parent = element.parentNode;
  14641. newElement = new JQLite(newElement);
  14642. for (var i = 0, ii = newElement.length; i < ii; i++) {
  14643. var node = newElement[i];
  14644. parent.insertBefore(node, index.nextSibling);
  14645. index = node;
  14646. }
  14647. },
  14648. addClass: jqLiteAddClass,
  14649. removeClass: jqLiteRemoveClass,
  14650. toggleClass: function(element, selector, condition) {
  14651. if (selector) {
  14652. forEach(selector.split(' '), function(className) {
  14653. var classCondition = condition;
  14654. if (isUndefined(classCondition)) {
  14655. classCondition = !jqLiteHasClass(element, className);
  14656. }
  14657. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  14658. });
  14659. }
  14660. },
  14661. parent: function(element) {
  14662. var parent = element.parentNode;
  14663. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  14664. },
  14665. next: function(element) {
  14666. return element.nextElementSibling;
  14667. },
  14668. find: function(element, selector) {
  14669. if (element.getElementsByTagName) {
  14670. return element.getElementsByTagName(selector);
  14671. } else {
  14672. return [];
  14673. }
  14674. },
  14675. clone: jqLiteClone,
  14676. triggerHandler: function(element, event, extraParameters) {
  14677. var dummyEvent, eventFnsCopy, handlerArgs;
  14678. var eventName = event.type || event;
  14679. var expandoStore = jqLiteExpandoStore(element);
  14680. var events = expandoStore && expandoStore.events;
  14681. var eventFns = events && events[eventName];
  14682. if (eventFns) {
  14683. // Create a dummy event to pass to the handlers
  14684. dummyEvent = {
  14685. preventDefault: function() { this.defaultPrevented = true; },
  14686. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  14687. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  14688. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  14689. stopPropagation: noop,
  14690. type: eventName,
  14691. target: element
  14692. };
  14693. // If a custom event was provided then extend our dummy event with it
  14694. if (event.type) {
  14695. dummyEvent = extend(dummyEvent, event);
  14696. }
  14697. // Copy event handlers in case event handlers array is modified during execution.
  14698. eventFnsCopy = shallowCopy(eventFns);
  14699. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  14700. forEach(eventFnsCopy, function(fn) {
  14701. if (!dummyEvent.isImmediatePropagationStopped()) {
  14702. fn.apply(element, handlerArgs);
  14703. }
  14704. });
  14705. }
  14706. }
  14707. }, function(fn, name) {
  14708. /**
  14709. * chaining functions
  14710. */
  14711. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  14712. var value;
  14713. for (var i = 0, ii = this.length; i < ii; i++) {
  14714. if (isUndefined(value)) {
  14715. value = fn(this[i], arg1, arg2, arg3);
  14716. if (isDefined(value)) {
  14717. // any function which returns a value needs to be wrapped
  14718. value = jqLite(value);
  14719. }
  14720. } else {
  14721. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  14722. }
  14723. }
  14724. return isDefined(value) ? value : this;
  14725. };
  14726. // bind legacy bind/unbind to on/off
  14727. JQLite.prototype.bind = JQLite.prototype.on;
  14728. JQLite.prototype.unbind = JQLite.prototype.off;
  14729. });
  14730. // Provider for private $$jqLite service
  14731. function $$jqLiteProvider() {
  14732. this.$get = function $$jqLite() {
  14733. return extend(JQLite, {
  14734. hasClass: function(node, classes) {
  14735. if (node.attr) node = node[0];
  14736. return jqLiteHasClass(node, classes);
  14737. },
  14738. addClass: function(node, classes) {
  14739. if (node.attr) node = node[0];
  14740. return jqLiteAddClass(node, classes);
  14741. },
  14742. removeClass: function(node, classes) {
  14743. if (node.attr) node = node[0];
  14744. return jqLiteRemoveClass(node, classes);
  14745. }
  14746. });
  14747. };
  14748. }
  14749. /**
  14750. * Computes a hash of an 'obj'.
  14751. * Hash of a:
  14752. * string is string
  14753. * number is number as string
  14754. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  14755. * that is also assigned to the $$hashKey property of the object.
  14756. *
  14757. * @param obj
  14758. * @returns {string} hash string such that the same input will have the same hash string.
  14759. * The resulting string key is in 'type:hashKey' format.
  14760. */
  14761. function hashKey(obj, nextUidFn) {
  14762. var key = obj && obj.$$hashKey;
  14763. if (key) {
  14764. if (typeof key === 'function') {
  14765. key = obj.$$hashKey();
  14766. }
  14767. return key;
  14768. }
  14769. var objType = typeof obj;
  14770. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  14771. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  14772. } else {
  14773. key = objType + ':' + obj;
  14774. }
  14775. return key;
  14776. }
  14777. /**
  14778. * HashMap which can use objects as keys
  14779. */
  14780. function HashMap(array, isolatedUid) {
  14781. if (isolatedUid) {
  14782. var uid = 0;
  14783. this.nextUid = function() {
  14784. return ++uid;
  14785. };
  14786. }
  14787. forEach(array, this.put, this);
  14788. }
  14789. HashMap.prototype = {
  14790. /**
  14791. * Store key value pair
  14792. * @param key key to store can be any type
  14793. * @param value value to store can be any type
  14794. */
  14795. put: function(key, value) {
  14796. this[hashKey(key, this.nextUid)] = value;
  14797. },
  14798. /**
  14799. * @param key
  14800. * @returns {Object} the value for the key
  14801. */
  14802. get: function(key) {
  14803. return this[hashKey(key, this.nextUid)];
  14804. },
  14805. /**
  14806. * Remove the key/value pair
  14807. * @param key
  14808. */
  14809. remove: function(key) {
  14810. var value = this[key = hashKey(key, this.nextUid)];
  14811. delete this[key];
  14812. return value;
  14813. }
  14814. };
  14815. var $$HashMapProvider = [function() {
  14816. this.$get = [function() {
  14817. return HashMap;
  14818. }];
  14819. }];
  14820. /**
  14821. * @ngdoc function
  14822. * @module ng
  14823. * @name angular.injector
  14824. * @kind function
  14825. *
  14826. * @description
  14827. * Creates an injector object that can be used for retrieving services as well as for
  14828. * dependency injection (see {@link guide/di dependency injection}).
  14829. *
  14830. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  14831. * {@link angular.module}. The `ng` module must be explicitly added.
  14832. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  14833. * disallows argument name annotation inference.
  14834. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  14835. *
  14836. * @example
  14837. * Typical usage
  14838. * ```js
  14839. * // create an injector
  14840. * var $injector = angular.injector(['ng']);
  14841. *
  14842. * // use the injector to kick off your application
  14843. * // use the type inference to auto inject arguments, or use implicit injection
  14844. * $injector.invoke(function($rootScope, $compile, $document) {
  14845. * $compile($document)($rootScope);
  14846. * $rootScope.$digest();
  14847. * });
  14848. * ```
  14849. *
  14850. * Sometimes you want to get access to the injector of a currently running Angular app
  14851. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  14852. * application has been bootstrapped. You can do this using the extra `injector()` added
  14853. * to JQuery/jqLite elements. See {@link angular.element}.
  14854. *
  14855. * *This is fairly rare but could be the case if a third party library is injecting the
  14856. * markup.*
  14857. *
  14858. * In the following example a new block of HTML containing a `ng-controller`
  14859. * directive is added to the end of the document body by JQuery. We then compile and link
  14860. * it into the current AngularJS scope.
  14861. *
  14862. * ```js
  14863. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  14864. * $(document.body).append($div);
  14865. *
  14866. * angular.element(document).injector().invoke(function($compile) {
  14867. * var scope = angular.element($div).scope();
  14868. * $compile($div)(scope);
  14869. * });
  14870. * ```
  14871. */
  14872. /**
  14873. * @ngdoc module
  14874. * @name auto
  14875. * @description
  14876. *
  14877. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  14878. */
  14879. var ARROW_ARG = /^([^\(]+?)=>/;
  14880. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  14881. var FN_ARG_SPLIT = /,/;
  14882. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  14883. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  14884. var $injectorMinErr = minErr('$injector');
  14885. function extractArgs(fn) {
  14886. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  14887. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  14888. return args;
  14889. }
  14890. function anonFn(fn) {
  14891. // For anonymous functions, showing at the very least the function signature can help in
  14892. // debugging.
  14893. var args = extractArgs(fn);
  14894. if (args) {
  14895. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  14896. }
  14897. return 'fn';
  14898. }
  14899. function annotate(fn, strictDi, name) {
  14900. var $inject,
  14901. argDecl,
  14902. last;
  14903. if (typeof fn === 'function') {
  14904. if (!($inject = fn.$inject)) {
  14905. $inject = [];
  14906. if (fn.length) {
  14907. if (strictDi) {
  14908. if (!isString(name) || !name) {
  14909. name = fn.name || anonFn(fn);
  14910. }
  14911. throw $injectorMinErr('strictdi',
  14912. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  14913. }
  14914. argDecl = extractArgs(fn);
  14915. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  14916. arg.replace(FN_ARG, function(all, underscore, name) {
  14917. $inject.push(name);
  14918. });
  14919. });
  14920. }
  14921. fn.$inject = $inject;
  14922. }
  14923. } else if (isArray(fn)) {
  14924. last = fn.length - 1;
  14925. assertArgFn(fn[last], 'fn');
  14926. $inject = fn.slice(0, last);
  14927. } else {
  14928. assertArgFn(fn, 'fn', true);
  14929. }
  14930. return $inject;
  14931. }
  14932. ///////////////////////////////////////
  14933. /**
  14934. * @ngdoc service
  14935. * @name $injector
  14936. *
  14937. * @description
  14938. *
  14939. * `$injector` is used to retrieve object instances as defined by
  14940. * {@link auto.$provide provider}, instantiate types, invoke methods,
  14941. * and load modules.
  14942. *
  14943. * The following always holds true:
  14944. *
  14945. * ```js
  14946. * var $injector = angular.injector();
  14947. * expect($injector.get('$injector')).toBe($injector);
  14948. * expect($injector.invoke(function($injector) {
  14949. * return $injector;
  14950. * })).toBe($injector);
  14951. * ```
  14952. *
  14953. * # Injection Function Annotation
  14954. *
  14955. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  14956. * following are all valid ways of annotating function with injection arguments and are equivalent.
  14957. *
  14958. * ```js
  14959. * // inferred (only works if code not minified/obfuscated)
  14960. * $injector.invoke(function(serviceA){});
  14961. *
  14962. * // annotated
  14963. * function explicit(serviceA) {};
  14964. * explicit.$inject = ['serviceA'];
  14965. * $injector.invoke(explicit);
  14966. *
  14967. * // inline
  14968. * $injector.invoke(['serviceA', function(serviceA){}]);
  14969. * ```
  14970. *
  14971. * ## Inference
  14972. *
  14973. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  14974. * can then be parsed and the function arguments can be extracted. This method of discovering
  14975. * annotations is disallowed when the injector is in strict mode.
  14976. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  14977. * argument names.
  14978. *
  14979. * ## `$inject` Annotation
  14980. * By adding an `$inject` property onto a function the injection parameters can be specified.
  14981. *
  14982. * ## Inline
  14983. * As an array of injection names, where the last item in the array is the function to call.
  14984. */
  14985. /**
  14986. * @ngdoc method
  14987. * @name $injector#get
  14988. *
  14989. * @description
  14990. * Return an instance of the service.
  14991. *
  14992. * @param {string} name The name of the instance to retrieve.
  14993. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  14994. * @return {*} The instance.
  14995. */
  14996. /**
  14997. * @ngdoc method
  14998. * @name $injector#invoke
  14999. *
  15000. * @description
  15001. * Invoke the method and supply the method arguments from the `$injector`.
  15002. *
  15003. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  15004. * injected according to the {@link guide/di $inject Annotation} rules.
  15005. * @param {Object=} self The `this` for the invoked method.
  15006. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  15007. * object first, before the `$injector` is consulted.
  15008. * @returns {*} the value returned by the invoked `fn` function.
  15009. */
  15010. /**
  15011. * @ngdoc method
  15012. * @name $injector#has
  15013. *
  15014. * @description
  15015. * Allows the user to query if the particular service exists.
  15016. *
  15017. * @param {string} name Name of the service to query.
  15018. * @returns {boolean} `true` if injector has given service.
  15019. */
  15020. /**
  15021. * @ngdoc method
  15022. * @name $injector#instantiate
  15023. * @description
  15024. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  15025. * operator, and supplies all of the arguments to the constructor function as specified by the
  15026. * constructor annotation.
  15027. *
  15028. * @param {Function} Type Annotated constructor function.
  15029. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  15030. * object first, before the `$injector` is consulted.
  15031. * @returns {Object} new instance of `Type`.
  15032. */
  15033. /**
  15034. * @ngdoc method
  15035. * @name $injector#annotate
  15036. *
  15037. * @description
  15038. * Returns an array of service names which the function is requesting for injection. This API is
  15039. * used by the injector to determine which services need to be injected into the function when the
  15040. * function is invoked. There are three ways in which the function can be annotated with the needed
  15041. * dependencies.
  15042. *
  15043. * # Argument names
  15044. *
  15045. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  15046. * by converting the function into a string using `toString()` method and extracting the argument
  15047. * names.
  15048. * ```js
  15049. * // Given
  15050. * function MyController($scope, $route) {
  15051. * // ...
  15052. * }
  15053. *
  15054. * // Then
  15055. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  15056. * ```
  15057. *
  15058. * You can disallow this method by using strict injection mode.
  15059. *
  15060. * This method does not work with code minification / obfuscation. For this reason the following
  15061. * annotation strategies are supported.
  15062. *
  15063. * # The `$inject` property
  15064. *
  15065. * If a function has an `$inject` property and its value is an array of strings, then the strings
  15066. * represent names of services to be injected into the function.
  15067. * ```js
  15068. * // Given
  15069. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  15070. * // ...
  15071. * }
  15072. * // Define function dependencies
  15073. * MyController['$inject'] = ['$scope', '$route'];
  15074. *
  15075. * // Then
  15076. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  15077. * ```
  15078. *
  15079. * # The array notation
  15080. *
  15081. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  15082. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  15083. * a way that survives minification is a better choice:
  15084. *
  15085. * ```js
  15086. * // We wish to write this (not minification / obfuscation safe)
  15087. * injector.invoke(function($compile, $rootScope) {
  15088. * // ...
  15089. * });
  15090. *
  15091. * // We are forced to write break inlining
  15092. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  15093. * // ...
  15094. * };
  15095. * tmpFn.$inject = ['$compile', '$rootScope'];
  15096. * injector.invoke(tmpFn);
  15097. *
  15098. * // To better support inline function the inline annotation is supported
  15099. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  15100. * // ...
  15101. * }]);
  15102. *
  15103. * // Therefore
  15104. * expect(injector.annotate(
  15105. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  15106. * ).toEqual(['$compile', '$rootScope']);
  15107. * ```
  15108. *
  15109. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  15110. * be retrieved as described above.
  15111. *
  15112. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  15113. *
  15114. * @returns {Array.<string>} The names of the services which the function requires.
  15115. */
  15116. /**
  15117. * @ngdoc service
  15118. * @name $provide
  15119. *
  15120. * @description
  15121. *
  15122. * The {@link auto.$provide $provide} service has a number of methods for registering components
  15123. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  15124. * {@link angular.Module}.
  15125. *
  15126. * An Angular **service** is a singleton object created by a **service factory**. These **service
  15127. * factories** are functions which, in turn, are created by a **service provider**.
  15128. * The **service providers** are constructor functions. When instantiated they must contain a
  15129. * property called `$get`, which holds the **service factory** function.
  15130. *
  15131. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  15132. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  15133. * function to get the instance of the **service**.
  15134. *
  15135. * Often services have no configuration options and there is no need to add methods to the service
  15136. * provider. The provider will be no more than a constructor function with a `$get` property. For
  15137. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  15138. * services without specifying a provider.
  15139. *
  15140. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  15141. * {@link auto.$injector $injector}
  15142. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  15143. * providers and services.
  15144. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  15145. * services, not providers.
  15146. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  15147. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  15148. * given factory function.
  15149. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  15150. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  15151. * a new object using the given constructor function.
  15152. *
  15153. * See the individual methods for more information and examples.
  15154. */
  15155. /**
  15156. * @ngdoc method
  15157. * @name $provide#provider
  15158. * @description
  15159. *
  15160. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  15161. * are constructor functions, whose instances are responsible for "providing" a factory for a
  15162. * service.
  15163. *
  15164. * Service provider names start with the name of the service they provide followed by `Provider`.
  15165. * For example, the {@link ng.$log $log} service has a provider called
  15166. * {@link ng.$logProvider $logProvider}.
  15167. *
  15168. * Service provider objects can have additional methods which allow configuration of the provider
  15169. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  15170. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  15171. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  15172. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  15173. * console or not.
  15174. *
  15175. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  15176. 'Provider'` key.
  15177. * @param {(Object|function())} provider If the provider is:
  15178. *
  15179. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  15180. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  15181. * - `Constructor`: a new instance of the provider will be created using
  15182. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  15183. *
  15184. * @returns {Object} registered provider instance
  15185. * @example
  15186. *
  15187. * The following example shows how to create a simple event tracking service and register it using
  15188. * {@link auto.$provide#provider $provide.provider()}.
  15189. *
  15190. * ```js
  15191. * // Define the eventTracker provider
  15192. * function EventTrackerProvider() {
  15193. * var trackingUrl = '/track';
  15194. *
  15195. * // A provider method for configuring where the tracked events should been saved
  15196. * this.setTrackingUrl = function(url) {
  15197. * trackingUrl = url;
  15198. * };
  15199. *
  15200. * // The service factory function
  15201. * this.$get = ['$http', function($http) {
  15202. * var trackedEvents = {};
  15203. * return {
  15204. * // Call this to track an event
  15205. * event: function(event) {
  15206. * var count = trackedEvents[event] || 0;
  15207. * count += 1;
  15208. * trackedEvents[event] = count;
  15209. * return count;
  15210. * },
  15211. * // Call this to save the tracked events to the trackingUrl
  15212. * save: function() {
  15213. * $http.post(trackingUrl, trackedEvents);
  15214. * }
  15215. * };
  15216. * }];
  15217. * }
  15218. *
  15219. * describe('eventTracker', function() {
  15220. * var postSpy;
  15221. *
  15222. * beforeEach(module(function($provide) {
  15223. * // Register the eventTracker provider
  15224. * $provide.provider('eventTracker', EventTrackerProvider);
  15225. * }));
  15226. *
  15227. * beforeEach(module(function(eventTrackerProvider) {
  15228. * // Configure eventTracker provider
  15229. * eventTrackerProvider.setTrackingUrl('/custom-track');
  15230. * }));
  15231. *
  15232. * it('tracks events', inject(function(eventTracker) {
  15233. * expect(eventTracker.event('login')).toEqual(1);
  15234. * expect(eventTracker.event('login')).toEqual(2);
  15235. * }));
  15236. *
  15237. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  15238. * postSpy = spyOn($http, 'post');
  15239. * eventTracker.event('login');
  15240. * eventTracker.save();
  15241. * expect(postSpy).toHaveBeenCalled();
  15242. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  15243. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  15244. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  15245. * }));
  15246. * });
  15247. * ```
  15248. */
  15249. /**
  15250. * @ngdoc method
  15251. * @name $provide#factory
  15252. * @description
  15253. *
  15254. * Register a **service factory**, which will be called to return the service instance.
  15255. * This is short for registering a service where its provider consists of only a `$get` property,
  15256. * which is the given service factory function.
  15257. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  15258. * configure your service in a provider.
  15259. *
  15260. * @param {string} name The name of the instance.
  15261. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  15262. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  15263. * @returns {Object} registered provider instance
  15264. *
  15265. * @example
  15266. * Here is an example of registering a service
  15267. * ```js
  15268. * $provide.factory('ping', ['$http', function($http) {
  15269. * return function ping() {
  15270. * return $http.send('/ping');
  15271. * };
  15272. * }]);
  15273. * ```
  15274. * You would then inject and use this service like this:
  15275. * ```js
  15276. * someModule.controller('Ctrl', ['ping', function(ping) {
  15277. * ping();
  15278. * }]);
  15279. * ```
  15280. */
  15281. /**
  15282. * @ngdoc method
  15283. * @name $provide#service
  15284. * @description
  15285. *
  15286. * Register a **service constructor**, which will be invoked with `new` to create the service
  15287. * instance.
  15288. * This is short for registering a service where its provider's `$get` property is a factory
  15289. * function that returns an instance instantiated by the injector from the service constructor
  15290. * function.
  15291. *
  15292. * Internally it looks a bit like this:
  15293. *
  15294. * ```
  15295. * {
  15296. * $get: function() {
  15297. * return $injector.instantiate(constructor);
  15298. * }
  15299. * }
  15300. * ```
  15301. *
  15302. *
  15303. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  15304. * as a type/class.
  15305. *
  15306. * @param {string} name The name of the instance.
  15307. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  15308. * that will be instantiated.
  15309. * @returns {Object} registered provider instance
  15310. *
  15311. * @example
  15312. * Here is an example of registering a service using
  15313. * {@link auto.$provide#service $provide.service(class)}.
  15314. * ```js
  15315. * var Ping = function($http) {
  15316. * this.$http = $http;
  15317. * };
  15318. *
  15319. * Ping.$inject = ['$http'];
  15320. *
  15321. * Ping.prototype.send = function() {
  15322. * return this.$http.get('/ping');
  15323. * };
  15324. * $provide.service('ping', Ping);
  15325. * ```
  15326. * You would then inject and use this service like this:
  15327. * ```js
  15328. * someModule.controller('Ctrl', ['ping', function(ping) {
  15329. * ping.send();
  15330. * }]);
  15331. * ```
  15332. */
  15333. /**
  15334. * @ngdoc method
  15335. * @name $provide#value
  15336. * @description
  15337. *
  15338. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  15339. * number, an array, an object or a function. This is short for registering a service where its
  15340. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  15341. * service**. That also means it is not possible to inject other services into a value service.
  15342. *
  15343. * Value services are similar to constant services, except that they cannot be injected into a
  15344. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  15345. * an Angular {@link auto.$provide#decorator decorator}.
  15346. *
  15347. * @param {string} name The name of the instance.
  15348. * @param {*} value The value.
  15349. * @returns {Object} registered provider instance
  15350. *
  15351. * @example
  15352. * Here are some examples of creating value services.
  15353. * ```js
  15354. * $provide.value('ADMIN_USER', 'admin');
  15355. *
  15356. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  15357. *
  15358. * $provide.value('halfOf', function(value) {
  15359. * return value / 2;
  15360. * });
  15361. * ```
  15362. */
  15363. /**
  15364. * @ngdoc method
  15365. * @name $provide#constant
  15366. * @description
  15367. *
  15368. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  15369. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  15370. * possible to inject other services into a constant.
  15371. *
  15372. * But unlike {@link auto.$provide#value value}, a constant can be
  15373. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  15374. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  15375. *
  15376. * @param {string} name The name of the constant.
  15377. * @param {*} value The constant value.
  15378. * @returns {Object} registered instance
  15379. *
  15380. * @example
  15381. * Here a some examples of creating constants:
  15382. * ```js
  15383. * $provide.constant('SHARD_HEIGHT', 306);
  15384. *
  15385. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  15386. *
  15387. * $provide.constant('double', function(value) {
  15388. * return value * 2;
  15389. * });
  15390. * ```
  15391. */
  15392. /**
  15393. * @ngdoc method
  15394. * @name $provide#decorator
  15395. * @description
  15396. *
  15397. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  15398. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  15399. * service. The object returned by the decorator may be the original service, or a new service
  15400. * object which replaces or wraps and delegates to the original service.
  15401. *
  15402. * @param {string} name The name of the service to decorate.
  15403. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  15404. * instantiated and should return the decorated service instance. The function is called using
  15405. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  15406. * Local injection arguments:
  15407. *
  15408. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  15409. * decorated or delegated to.
  15410. *
  15411. * @example
  15412. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  15413. * calls to {@link ng.$log#error $log.warn()}.
  15414. * ```js
  15415. * $provide.decorator('$log', ['$delegate', function($delegate) {
  15416. * $delegate.warn = $delegate.error;
  15417. * return $delegate;
  15418. * }]);
  15419. * ```
  15420. */
  15421. function createInjector(modulesToLoad, strictDi) {
  15422. strictDi = (strictDi === true);
  15423. var INSTANTIATING = {},
  15424. providerSuffix = 'Provider',
  15425. path = [],
  15426. loadedModules = new HashMap([], true),
  15427. providerCache = {
  15428. $provide: {
  15429. provider: supportObject(provider),
  15430. factory: supportObject(factory),
  15431. service: supportObject(service),
  15432. value: supportObject(value),
  15433. constant: supportObject(constant),
  15434. decorator: decorator
  15435. }
  15436. },
  15437. providerInjector = (providerCache.$injector =
  15438. createInternalInjector(providerCache, function(serviceName, caller) {
  15439. if (angular.isString(caller)) {
  15440. path.push(caller);
  15441. }
  15442. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  15443. })),
  15444. instanceCache = {},
  15445. protoInstanceInjector =
  15446. createInternalInjector(instanceCache, function(serviceName, caller) {
  15447. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  15448. return instanceInjector.invoke(
  15449. provider.$get, provider, undefined, serviceName);
  15450. }),
  15451. instanceInjector = protoInstanceInjector;
  15452. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  15453. var runBlocks = loadModules(modulesToLoad);
  15454. instanceInjector = protoInstanceInjector.get('$injector');
  15455. instanceInjector.strictDi = strictDi;
  15456. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  15457. return instanceInjector;
  15458. ////////////////////////////////////
  15459. // $provider
  15460. ////////////////////////////////////
  15461. function supportObject(delegate) {
  15462. return function(key, value) {
  15463. if (isObject(key)) {
  15464. forEach(key, reverseParams(delegate));
  15465. } else {
  15466. return delegate(key, value);
  15467. }
  15468. };
  15469. }
  15470. function provider(name, provider_) {
  15471. assertNotHasOwnProperty(name, 'service');
  15472. if (isFunction(provider_) || isArray(provider_)) {
  15473. provider_ = providerInjector.instantiate(provider_);
  15474. }
  15475. if (!provider_.$get) {
  15476. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  15477. }
  15478. return providerCache[name + providerSuffix] = provider_;
  15479. }
  15480. function enforceReturnValue(name, factory) {
  15481. return function enforcedReturnValue() {
  15482. var result = instanceInjector.invoke(factory, this);
  15483. if (isUndefined(result)) {
  15484. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  15485. }
  15486. return result;
  15487. };
  15488. }
  15489. function factory(name, factoryFn, enforce) {
  15490. return provider(name, {
  15491. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  15492. });
  15493. }
  15494. function service(name, constructor) {
  15495. return factory(name, ['$injector', function($injector) {
  15496. return $injector.instantiate(constructor);
  15497. }]);
  15498. }
  15499. function value(name, val) { return factory(name, valueFn(val), false); }
  15500. function constant(name, value) {
  15501. assertNotHasOwnProperty(name, 'constant');
  15502. providerCache[name] = value;
  15503. instanceCache[name] = value;
  15504. }
  15505. function decorator(serviceName, decorFn) {
  15506. var origProvider = providerInjector.get(serviceName + providerSuffix),
  15507. orig$get = origProvider.$get;
  15508. origProvider.$get = function() {
  15509. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  15510. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  15511. };
  15512. }
  15513. ////////////////////////////////////
  15514. // Module Loading
  15515. ////////////////////////////////////
  15516. function loadModules(modulesToLoad) {
  15517. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  15518. var runBlocks = [], moduleFn;
  15519. forEach(modulesToLoad, function(module) {
  15520. if (loadedModules.get(module)) return;
  15521. loadedModules.put(module, true);
  15522. function runInvokeQueue(queue) {
  15523. var i, ii;
  15524. for (i = 0, ii = queue.length; i < ii; i++) {
  15525. var invokeArgs = queue[i],
  15526. provider = providerInjector.get(invokeArgs[0]);
  15527. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  15528. }
  15529. }
  15530. try {
  15531. if (isString(module)) {
  15532. moduleFn = angularModule(module);
  15533. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  15534. runInvokeQueue(moduleFn._invokeQueue);
  15535. runInvokeQueue(moduleFn._configBlocks);
  15536. } else if (isFunction(module)) {
  15537. runBlocks.push(providerInjector.invoke(module));
  15538. } else if (isArray(module)) {
  15539. runBlocks.push(providerInjector.invoke(module));
  15540. } else {
  15541. assertArgFn(module, 'module');
  15542. }
  15543. } catch (e) {
  15544. if (isArray(module)) {
  15545. module = module[module.length - 1];
  15546. }
  15547. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  15548. // Safari & FF's stack traces don't contain error.message content
  15549. // unlike those of Chrome and IE
  15550. // So if stack doesn't contain message, we create a new string that contains both.
  15551. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  15552. /* jshint -W022 */
  15553. e = e.message + '\n' + e.stack;
  15554. }
  15555. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  15556. module, e.stack || e.message || e);
  15557. }
  15558. });
  15559. return runBlocks;
  15560. }
  15561. ////////////////////////////////////
  15562. // internal Injector
  15563. ////////////////////////////////////
  15564. function createInternalInjector(cache, factory) {
  15565. function getService(serviceName, caller) {
  15566. if (cache.hasOwnProperty(serviceName)) {
  15567. if (cache[serviceName] === INSTANTIATING) {
  15568. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  15569. serviceName + ' <- ' + path.join(' <- '));
  15570. }
  15571. return cache[serviceName];
  15572. } else {
  15573. try {
  15574. path.unshift(serviceName);
  15575. cache[serviceName] = INSTANTIATING;
  15576. return cache[serviceName] = factory(serviceName, caller);
  15577. } catch (err) {
  15578. if (cache[serviceName] === INSTANTIATING) {
  15579. delete cache[serviceName];
  15580. }
  15581. throw err;
  15582. } finally {
  15583. path.shift();
  15584. }
  15585. }
  15586. }
  15587. function injectionArgs(fn, locals, serviceName) {
  15588. var args = [],
  15589. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  15590. for (var i = 0, length = $inject.length; i < length; i++) {
  15591. var key = $inject[i];
  15592. if (typeof key !== 'string') {
  15593. throw $injectorMinErr('itkn',
  15594. 'Incorrect injection token! Expected service name as string, got {0}', key);
  15595. }
  15596. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  15597. getService(key, serviceName));
  15598. }
  15599. return args;
  15600. }
  15601. function isClass(func) {
  15602. // IE 9-11 do not support classes and IE9 leaks with the code below.
  15603. if (msie <= 11) {
  15604. return false;
  15605. }
  15606. // Workaround for MS Edge.
  15607. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
  15608. return typeof func === 'function'
  15609. && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
  15610. }
  15611. function invoke(fn, self, locals, serviceName) {
  15612. if (typeof locals === 'string') {
  15613. serviceName = locals;
  15614. locals = null;
  15615. }
  15616. var args = injectionArgs(fn, locals, serviceName);
  15617. if (isArray(fn)) {
  15618. fn = fn[fn.length - 1];
  15619. }
  15620. if (!isClass(fn)) {
  15621. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  15622. // #5388
  15623. return fn.apply(self, args);
  15624. } else {
  15625. args.unshift(null);
  15626. return new (Function.prototype.bind.apply(fn, args))();
  15627. }
  15628. }
  15629. function instantiate(Type, locals, serviceName) {
  15630. // Check if Type is annotated and use just the given function at n-1 as parameter
  15631. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  15632. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  15633. var args = injectionArgs(Type, locals, serviceName);
  15634. // Empty object at position 0 is ignored for invocation with `new`, but required.
  15635. args.unshift(null);
  15636. return new (Function.prototype.bind.apply(ctor, args))();
  15637. }
  15638. return {
  15639. invoke: invoke,
  15640. instantiate: instantiate,
  15641. get: getService,
  15642. annotate: createInjector.$$annotate,
  15643. has: function(name) {
  15644. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  15645. }
  15646. };
  15647. }
  15648. }
  15649. createInjector.$$annotate = annotate;
  15650. /**
  15651. * @ngdoc provider
  15652. * @name $anchorScrollProvider
  15653. *
  15654. * @description
  15655. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  15656. * {@link ng.$location#hash $location.hash()} changes.
  15657. */
  15658. function $AnchorScrollProvider() {
  15659. var autoScrollingEnabled = true;
  15660. /**
  15661. * @ngdoc method
  15662. * @name $anchorScrollProvider#disableAutoScrolling
  15663. *
  15664. * @description
  15665. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  15666. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  15667. * Use this method to disable automatic scrolling.
  15668. *
  15669. * If automatic scrolling is disabled, one must explicitly call
  15670. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  15671. * current hash.
  15672. */
  15673. this.disableAutoScrolling = function() {
  15674. autoScrollingEnabled = false;
  15675. };
  15676. /**
  15677. * @ngdoc service
  15678. * @name $anchorScroll
  15679. * @kind function
  15680. * @requires $window
  15681. * @requires $location
  15682. * @requires $rootScope
  15683. *
  15684. * @description
  15685. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  15686. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  15687. * in the
  15688. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  15689. *
  15690. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  15691. * match any anchor whenever it changes. This can be disabled by calling
  15692. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  15693. *
  15694. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  15695. * vertical scroll-offset (either fixed or dynamic).
  15696. *
  15697. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  15698. * {@link ng.$location#hash $location.hash()} will be used.
  15699. *
  15700. * @property {(number|function|jqLite)} yOffset
  15701. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  15702. * positioned elements at the top of the page, such as navbars, headers etc.
  15703. *
  15704. * `yOffset` can be specified in various ways:
  15705. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  15706. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  15707. * a number representing the offset (in pixels).<br /><br />
  15708. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  15709. * the top of the page to the element's bottom will be used as offset.<br />
  15710. * **Note**: The element will be taken into account only as long as its `position` is set to
  15711. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  15712. * their height and/or positioning according to the viewport's size.
  15713. *
  15714. * <br />
  15715. * <div class="alert alert-warning">
  15716. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  15717. * not some child element.
  15718. * </div>
  15719. *
  15720. * @example
  15721. <example module="anchorScrollExample">
  15722. <file name="index.html">
  15723. <div id="scrollArea" ng-controller="ScrollController">
  15724. <a ng-click="gotoBottom()">Go to bottom</a>
  15725. <a id="bottom"></a> You're at the bottom!
  15726. </div>
  15727. </file>
  15728. <file name="script.js">
  15729. angular.module('anchorScrollExample', [])
  15730. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  15731. function ($scope, $location, $anchorScroll) {
  15732. $scope.gotoBottom = function() {
  15733. // set the location.hash to the id of
  15734. // the element you wish to scroll to.
  15735. $location.hash('bottom');
  15736. // call $anchorScroll()
  15737. $anchorScroll();
  15738. };
  15739. }]);
  15740. </file>
  15741. <file name="style.css">
  15742. #scrollArea {
  15743. height: 280px;
  15744. overflow: auto;
  15745. }
  15746. #bottom {
  15747. display: block;
  15748. margin-top: 2000px;
  15749. }
  15750. </file>
  15751. </example>
  15752. *
  15753. * <hr />
  15754. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  15755. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  15756. *
  15757. * @example
  15758. <example module="anchorScrollOffsetExample">
  15759. <file name="index.html">
  15760. <div class="fixed-header" ng-controller="headerCtrl">
  15761. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  15762. Go to anchor {{x}}
  15763. </a>
  15764. </div>
  15765. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  15766. Anchor {{x}} of 5
  15767. </div>
  15768. </file>
  15769. <file name="script.js">
  15770. angular.module('anchorScrollOffsetExample', [])
  15771. .run(['$anchorScroll', function($anchorScroll) {
  15772. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  15773. }])
  15774. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  15775. function ($anchorScroll, $location, $scope) {
  15776. $scope.gotoAnchor = function(x) {
  15777. var newHash = 'anchor' + x;
  15778. if ($location.hash() !== newHash) {
  15779. // set the $location.hash to `newHash` and
  15780. // $anchorScroll will automatically scroll to it
  15781. $location.hash('anchor' + x);
  15782. } else {
  15783. // call $anchorScroll() explicitly,
  15784. // since $location.hash hasn't changed
  15785. $anchorScroll();
  15786. }
  15787. };
  15788. }
  15789. ]);
  15790. </file>
  15791. <file name="style.css">
  15792. body {
  15793. padding-top: 50px;
  15794. }
  15795. .anchor {
  15796. border: 2px dashed DarkOrchid;
  15797. padding: 10px 10px 200px 10px;
  15798. }
  15799. .fixed-header {
  15800. background-color: rgba(0, 0, 0, 0.2);
  15801. height: 50px;
  15802. position: fixed;
  15803. top: 0; left: 0; right: 0;
  15804. }
  15805. .fixed-header > a {
  15806. display: inline-block;
  15807. margin: 5px 15px;
  15808. }
  15809. </file>
  15810. </example>
  15811. */
  15812. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  15813. var document = $window.document;
  15814. // Helper function to get first anchor from a NodeList
  15815. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  15816. // and working in all supported browsers.)
  15817. function getFirstAnchor(list) {
  15818. var result = null;
  15819. Array.prototype.some.call(list, function(element) {
  15820. if (nodeName_(element) === 'a') {
  15821. result = element;
  15822. return true;
  15823. }
  15824. });
  15825. return result;
  15826. }
  15827. function getYOffset() {
  15828. var offset = scroll.yOffset;
  15829. if (isFunction(offset)) {
  15830. offset = offset();
  15831. } else if (isElement(offset)) {
  15832. var elem = offset[0];
  15833. var style = $window.getComputedStyle(elem);
  15834. if (style.position !== 'fixed') {
  15835. offset = 0;
  15836. } else {
  15837. offset = elem.getBoundingClientRect().bottom;
  15838. }
  15839. } else if (!isNumber(offset)) {
  15840. offset = 0;
  15841. }
  15842. return offset;
  15843. }
  15844. function scrollTo(elem) {
  15845. if (elem) {
  15846. elem.scrollIntoView();
  15847. var offset = getYOffset();
  15848. if (offset) {
  15849. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  15850. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  15851. // top of the viewport.
  15852. //
  15853. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  15854. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  15855. // way down the page.
  15856. //
  15857. // This is often the case for elements near the bottom of the page.
  15858. //
  15859. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  15860. // the top of the element and the offset, which is enough to align the top of `elem` at the
  15861. // desired position.
  15862. var elemTop = elem.getBoundingClientRect().top;
  15863. $window.scrollBy(0, elemTop - offset);
  15864. }
  15865. } else {
  15866. $window.scrollTo(0, 0);
  15867. }
  15868. }
  15869. function scroll(hash) {
  15870. hash = isString(hash) ? hash : $location.hash();
  15871. var elm;
  15872. // empty hash, scroll to the top of the page
  15873. if (!hash) scrollTo(null);
  15874. // element with given id
  15875. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  15876. // first anchor with given name :-D
  15877. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  15878. // no element and hash == 'top', scroll to the top of the page
  15879. else if (hash === 'top') scrollTo(null);
  15880. }
  15881. // does not scroll when user clicks on anchor link that is currently on
  15882. // (no url change, no $location.hash() change), browser native does scroll
  15883. if (autoScrollingEnabled) {
  15884. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  15885. function autoScrollWatchAction(newVal, oldVal) {
  15886. // skip the initial scroll if $location.hash is empty
  15887. if (newVal === oldVal && newVal === '') return;
  15888. jqLiteDocumentLoaded(function() {
  15889. $rootScope.$evalAsync(scroll);
  15890. });
  15891. });
  15892. }
  15893. return scroll;
  15894. }];
  15895. }
  15896. var $animateMinErr = minErr('$animate');
  15897. var ELEMENT_NODE = 1;
  15898. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  15899. function mergeClasses(a,b) {
  15900. if (!a && !b) return '';
  15901. if (!a) return b;
  15902. if (!b) return a;
  15903. if (isArray(a)) a = a.join(' ');
  15904. if (isArray(b)) b = b.join(' ');
  15905. return a + ' ' + b;
  15906. }
  15907. function extractElementNode(element) {
  15908. for (var i = 0; i < element.length; i++) {
  15909. var elm = element[i];
  15910. if (elm.nodeType === ELEMENT_NODE) {
  15911. return elm;
  15912. }
  15913. }
  15914. }
  15915. function splitClasses(classes) {
  15916. if (isString(classes)) {
  15917. classes = classes.split(' ');
  15918. }
  15919. // Use createMap() to prevent class assumptions involving property names in
  15920. // Object.prototype
  15921. var obj = createMap();
  15922. forEach(classes, function(klass) {
  15923. // sometimes the split leaves empty string values
  15924. // incase extra spaces were applied to the options
  15925. if (klass.length) {
  15926. obj[klass] = true;
  15927. }
  15928. });
  15929. return obj;
  15930. }
  15931. // if any other type of options value besides an Object value is
  15932. // passed into the $animate.method() animation then this helper code
  15933. // will be run which will ignore it. While this patch is not the
  15934. // greatest solution to this, a lot of existing plugins depend on
  15935. // $animate to either call the callback (< 1.2) or return a promise
  15936. // that can be changed. This helper function ensures that the options
  15937. // are wiped clean incase a callback function is provided.
  15938. function prepareAnimateOptions(options) {
  15939. return isObject(options)
  15940. ? options
  15941. : {};
  15942. }
  15943. var $$CoreAnimateJsProvider = function() {
  15944. this.$get = noop;
  15945. };
  15946. // this is prefixed with Core since it conflicts with
  15947. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  15948. var $$CoreAnimateQueueProvider = function() {
  15949. var postDigestQueue = new HashMap();
  15950. var postDigestElements = [];
  15951. this.$get = ['$$AnimateRunner', '$rootScope',
  15952. function($$AnimateRunner, $rootScope) {
  15953. return {
  15954. enabled: noop,
  15955. on: noop,
  15956. off: noop,
  15957. pin: noop,
  15958. push: function(element, event, options, domOperation) {
  15959. domOperation && domOperation();
  15960. options = options || {};
  15961. options.from && element.css(options.from);
  15962. options.to && element.css(options.to);
  15963. if (options.addClass || options.removeClass) {
  15964. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  15965. }
  15966. var runner = new $$AnimateRunner(); // jshint ignore:line
  15967. // since there are no animations to run the runner needs to be
  15968. // notified that the animation call is complete.
  15969. runner.complete();
  15970. return runner;
  15971. }
  15972. };
  15973. function updateData(data, classes, value) {
  15974. var changed = false;
  15975. if (classes) {
  15976. classes = isString(classes) ? classes.split(' ') :
  15977. isArray(classes) ? classes : [];
  15978. forEach(classes, function(className) {
  15979. if (className) {
  15980. changed = true;
  15981. data[className] = value;
  15982. }
  15983. });
  15984. }
  15985. return changed;
  15986. }
  15987. function handleCSSClassChanges() {
  15988. forEach(postDigestElements, function(element) {
  15989. var data = postDigestQueue.get(element);
  15990. if (data) {
  15991. var existing = splitClasses(element.attr('class'));
  15992. var toAdd = '';
  15993. var toRemove = '';
  15994. forEach(data, function(status, className) {
  15995. var hasClass = !!existing[className];
  15996. if (status !== hasClass) {
  15997. if (status) {
  15998. toAdd += (toAdd.length ? ' ' : '') + className;
  15999. } else {
  16000. toRemove += (toRemove.length ? ' ' : '') + className;
  16001. }
  16002. }
  16003. });
  16004. forEach(element, function(elm) {
  16005. toAdd && jqLiteAddClass(elm, toAdd);
  16006. toRemove && jqLiteRemoveClass(elm, toRemove);
  16007. });
  16008. postDigestQueue.remove(element);
  16009. }
  16010. });
  16011. postDigestElements.length = 0;
  16012. }
  16013. function addRemoveClassesPostDigest(element, add, remove) {
  16014. var data = postDigestQueue.get(element) || {};
  16015. var classesAdded = updateData(data, add, true);
  16016. var classesRemoved = updateData(data, remove, false);
  16017. if (classesAdded || classesRemoved) {
  16018. postDigestQueue.put(element, data);
  16019. postDigestElements.push(element);
  16020. if (postDigestElements.length === 1) {
  16021. $rootScope.$$postDigest(handleCSSClassChanges);
  16022. }
  16023. }
  16024. }
  16025. }];
  16026. };
  16027. /**
  16028. * @ngdoc provider
  16029. * @name $animateProvider
  16030. *
  16031. * @description
  16032. * Default implementation of $animate that doesn't perform any animations, instead just
  16033. * synchronously performs DOM updates and resolves the returned runner promise.
  16034. *
  16035. * In order to enable animations the `ngAnimate` module has to be loaded.
  16036. *
  16037. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  16038. */
  16039. var $AnimateProvider = ['$provide', function($provide) {
  16040. var provider = this;
  16041. this.$$registeredAnimations = Object.create(null);
  16042. /**
  16043. * @ngdoc method
  16044. * @name $animateProvider#register
  16045. *
  16046. * @description
  16047. * Registers a new injectable animation factory function. The factory function produces the
  16048. * animation object which contains callback functions for each event that is expected to be
  16049. * animated.
  16050. *
  16051. * * `eventFn`: `function(element, ... , doneFunction, options)`
  16052. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  16053. * on the type of animation additional arguments will be injected into the animation function. The
  16054. * list below explains the function signatures for the different animation methods:
  16055. *
  16056. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  16057. * - addClass: function(element, addedClasses, doneFunction, options)
  16058. * - removeClass: function(element, removedClasses, doneFunction, options)
  16059. * - enter, leave, move: function(element, doneFunction, options)
  16060. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  16061. *
  16062. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  16063. *
  16064. * ```js
  16065. * return {
  16066. * //enter, leave, move signature
  16067. * eventFn : function(element, done, options) {
  16068. * //code to run the animation
  16069. * //once complete, then run done()
  16070. * return function endFunction(wasCancelled) {
  16071. * //code to cancel the animation
  16072. * }
  16073. * }
  16074. * }
  16075. * ```
  16076. *
  16077. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  16078. * @param {Function} factory The factory function that will be executed to return the animation
  16079. * object.
  16080. */
  16081. this.register = function(name, factory) {
  16082. if (name && name.charAt(0) !== '.') {
  16083. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  16084. }
  16085. var key = name + '-animation';
  16086. provider.$$registeredAnimations[name.substr(1)] = key;
  16087. $provide.factory(key, factory);
  16088. };
  16089. /**
  16090. * @ngdoc method
  16091. * @name $animateProvider#classNameFilter
  16092. *
  16093. * @description
  16094. * Sets and/or returns the CSS class regular expression that is checked when performing
  16095. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  16096. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  16097. * When setting the `classNameFilter` value, animations will only be performed on elements
  16098. * that successfully match the filter expression. This in turn can boost performance
  16099. * for low-powered devices as well as applications containing a lot of structural operations.
  16100. * @param {RegExp=} expression The className expression which will be checked against all animations
  16101. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  16102. */
  16103. this.classNameFilter = function(expression) {
  16104. if (arguments.length === 1) {
  16105. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  16106. if (this.$$classNameFilter) {
  16107. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  16108. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  16109. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  16110. }
  16111. }
  16112. }
  16113. return this.$$classNameFilter;
  16114. };
  16115. this.$get = ['$$animateQueue', function($$animateQueue) {
  16116. function domInsert(element, parentElement, afterElement) {
  16117. // if for some reason the previous element was removed
  16118. // from the dom sometime before this code runs then let's
  16119. // just stick to using the parent element as the anchor
  16120. if (afterElement) {
  16121. var afterNode = extractElementNode(afterElement);
  16122. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  16123. afterElement = null;
  16124. }
  16125. }
  16126. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  16127. }
  16128. /**
  16129. * @ngdoc service
  16130. * @name $animate
  16131. * @description The $animate service exposes a series of DOM utility methods that provide support
  16132. * for animation hooks. The default behavior is the application of DOM operations, however,
  16133. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  16134. * to ensure that animation runs with the triggered DOM operation.
  16135. *
  16136. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  16137. * included and only when it is active then the animation hooks that `$animate` triggers will be
  16138. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  16139. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  16140. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  16141. *
  16142. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  16143. *
  16144. * To learn more about enabling animation support, click here to visit the
  16145. * {@link ngAnimate ngAnimate module page}.
  16146. */
  16147. return {
  16148. // we don't call it directly since non-existant arguments may
  16149. // be interpreted as null within the sub enabled function
  16150. /**
  16151. *
  16152. * @ngdoc method
  16153. * @name $animate#on
  16154. * @kind function
  16155. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  16156. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  16157. * is fired with the following params:
  16158. *
  16159. * ```js
  16160. * $animate.on('enter', container,
  16161. * function callback(element, phase) {
  16162. * // cool we detected an enter animation within the container
  16163. * }
  16164. * );
  16165. * ```
  16166. *
  16167. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  16168. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  16169. * as well as among its children
  16170. * @param {Function} callback the callback function that will be fired when the listener is triggered
  16171. *
  16172. * The arguments present in the callback function are:
  16173. * * `element` - The captured DOM element that the animation was fired on.
  16174. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  16175. */
  16176. on: $$animateQueue.on,
  16177. /**
  16178. *
  16179. * @ngdoc method
  16180. * @name $animate#off
  16181. * @kind function
  16182. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  16183. * can be used in three different ways depending on the arguments:
  16184. *
  16185. * ```js
  16186. * // remove all the animation event listeners listening for `enter`
  16187. * $animate.off('enter');
  16188. *
  16189. * // remove all the animation event listeners listening for `enter` on the given element and its children
  16190. * $animate.off('enter', container);
  16191. *
  16192. * // remove the event listener function provided by `callback` that is set
  16193. * // to listen for `enter` on the given `container` as well as its children
  16194. * $animate.off('enter', container, callback);
  16195. * ```
  16196. *
  16197. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  16198. * @param {DOMElement=} container the container element the event listener was placed on
  16199. * @param {Function=} callback the callback function that was registered as the listener
  16200. */
  16201. off: $$animateQueue.off,
  16202. /**
  16203. * @ngdoc method
  16204. * @name $animate#pin
  16205. * @kind function
  16206. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  16207. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  16208. * element despite being outside the realm of the application or within another application. Say for example if the application
  16209. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  16210. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  16211. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  16212. *
  16213. * Note that this feature is only active when the `ngAnimate` module is used.
  16214. *
  16215. * @param {DOMElement} element the external element that will be pinned
  16216. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  16217. */
  16218. pin: $$animateQueue.pin,
  16219. /**
  16220. *
  16221. * @ngdoc method
  16222. * @name $animate#enabled
  16223. * @kind function
  16224. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  16225. * function can be called in four ways:
  16226. *
  16227. * ```js
  16228. * // returns true or false
  16229. * $animate.enabled();
  16230. *
  16231. * // changes the enabled state for all animations
  16232. * $animate.enabled(false);
  16233. * $animate.enabled(true);
  16234. *
  16235. * // returns true or false if animations are enabled for an element
  16236. * $animate.enabled(element);
  16237. *
  16238. * // changes the enabled state for an element and its children
  16239. * $animate.enabled(element, true);
  16240. * $animate.enabled(element, false);
  16241. * ```
  16242. *
  16243. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  16244. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  16245. *
  16246. * @return {boolean} whether or not animations are enabled
  16247. */
  16248. enabled: $$animateQueue.enabled,
  16249. /**
  16250. * @ngdoc method
  16251. * @name $animate#cancel
  16252. * @kind function
  16253. * @description Cancels the provided animation.
  16254. *
  16255. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  16256. */
  16257. cancel: function(runner) {
  16258. runner.end && runner.end();
  16259. },
  16260. /**
  16261. *
  16262. * @ngdoc method
  16263. * @name $animate#enter
  16264. * @kind function
  16265. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  16266. * as the first child within the `parent` element and then triggers an animation.
  16267. * A promise is returned that will be resolved during the next digest once the animation
  16268. * has completed.
  16269. *
  16270. * @param {DOMElement} element the element which will be inserted into the DOM
  16271. * @param {DOMElement} parent the parent element which will append the element as
  16272. * a child (so long as the after element is not present)
  16273. * @param {DOMElement=} after the sibling element after which the element will be appended
  16274. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16275. *
  16276. * @return {Promise} the animation callback promise
  16277. */
  16278. enter: function(element, parent, after, options) {
  16279. parent = parent && jqLite(parent);
  16280. after = after && jqLite(after);
  16281. parent = parent || after.parent();
  16282. domInsert(element, parent, after);
  16283. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  16284. },
  16285. /**
  16286. *
  16287. * @ngdoc method
  16288. * @name $animate#move
  16289. * @kind function
  16290. * @description Inserts (moves) the element into its new position in the DOM either after
  16291. * the `after` element (if provided) or as the first child within the `parent` element
  16292. * and then triggers an animation. A promise is returned that will be resolved
  16293. * during the next digest once the animation has completed.
  16294. *
  16295. * @param {DOMElement} element the element which will be moved into the new DOM position
  16296. * @param {DOMElement} parent the parent element which will append the element as
  16297. * a child (so long as the after element is not present)
  16298. * @param {DOMElement=} after the sibling element after which the element will be appended
  16299. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16300. *
  16301. * @return {Promise} the animation callback promise
  16302. */
  16303. move: function(element, parent, after, options) {
  16304. parent = parent && jqLite(parent);
  16305. after = after && jqLite(after);
  16306. parent = parent || after.parent();
  16307. domInsert(element, parent, after);
  16308. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  16309. },
  16310. /**
  16311. * @ngdoc method
  16312. * @name $animate#leave
  16313. * @kind function
  16314. * @description Triggers an animation and then removes the element from the DOM.
  16315. * When the function is called a promise is returned that will be resolved during the next
  16316. * digest once the animation has completed.
  16317. *
  16318. * @param {DOMElement} element the element which will be removed from the DOM
  16319. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16320. *
  16321. * @return {Promise} the animation callback promise
  16322. */
  16323. leave: function(element, options) {
  16324. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  16325. element.remove();
  16326. });
  16327. },
  16328. /**
  16329. * @ngdoc method
  16330. * @name $animate#addClass
  16331. * @kind function
  16332. *
  16333. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  16334. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  16335. * animation if element already contains the CSS class or if the class is removed at a later step.
  16336. * Note that class-based animations are treated differently compared to structural animations
  16337. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16338. * depending if CSS or JavaScript animations are used.
  16339. *
  16340. * @param {DOMElement} element the element which the CSS classes will be applied to
  16341. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  16342. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16343. *
  16344. * @return {Promise} the animation callback promise
  16345. */
  16346. addClass: function(element, className, options) {
  16347. options = prepareAnimateOptions(options);
  16348. options.addClass = mergeClasses(options.addclass, className);
  16349. return $$animateQueue.push(element, 'addClass', options);
  16350. },
  16351. /**
  16352. * @ngdoc method
  16353. * @name $animate#removeClass
  16354. * @kind function
  16355. *
  16356. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  16357. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  16358. * animation if element does not contain the CSS class or if the class is added at a later step.
  16359. * Note that class-based animations are treated differently compared to structural animations
  16360. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16361. * depending if CSS or JavaScript animations are used.
  16362. *
  16363. * @param {DOMElement} element the element which the CSS classes will be applied to
  16364. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  16365. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16366. *
  16367. * @return {Promise} the animation callback promise
  16368. */
  16369. removeClass: function(element, className, options) {
  16370. options = prepareAnimateOptions(options);
  16371. options.removeClass = mergeClasses(options.removeClass, className);
  16372. return $$animateQueue.push(element, 'removeClass', options);
  16373. },
  16374. /**
  16375. * @ngdoc method
  16376. * @name $animate#setClass
  16377. * @kind function
  16378. *
  16379. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  16380. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  16381. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  16382. * passed. Note that class-based animations are treated differently compared to structural animations
  16383. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16384. * depending if CSS or JavaScript animations are used.
  16385. *
  16386. * @param {DOMElement} element the element which the CSS classes will be applied to
  16387. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  16388. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  16389. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16390. *
  16391. * @return {Promise} the animation callback promise
  16392. */
  16393. setClass: function(element, add, remove, options) {
  16394. options = prepareAnimateOptions(options);
  16395. options.addClass = mergeClasses(options.addClass, add);
  16396. options.removeClass = mergeClasses(options.removeClass, remove);
  16397. return $$animateQueue.push(element, 'setClass', options);
  16398. },
  16399. /**
  16400. * @ngdoc method
  16401. * @name $animate#animate
  16402. * @kind function
  16403. *
  16404. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  16405. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  16406. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  16407. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  16408. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  16409. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  16410. * method (or as part of the `options` parameter):
  16411. *
  16412. * ```js
  16413. * ngModule.animation('.my-inline-animation', function() {
  16414. * return {
  16415. * animate : function(element, from, to, done, options) {
  16416. * //animation
  16417. * done();
  16418. * }
  16419. * }
  16420. * });
  16421. * ```
  16422. *
  16423. * @param {DOMElement} element the element which the CSS styles will be applied to
  16424. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  16425. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  16426. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  16427. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  16428. * (Note that if no animation is detected then this value will not be applied to the element.)
  16429. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16430. *
  16431. * @return {Promise} the animation callback promise
  16432. */
  16433. animate: function(element, from, to, className, options) {
  16434. options = prepareAnimateOptions(options);
  16435. options.from = options.from ? extend(options.from, from) : from;
  16436. options.to = options.to ? extend(options.to, to) : to;
  16437. className = className || 'ng-inline-animate';
  16438. options.tempClasses = mergeClasses(options.tempClasses, className);
  16439. return $$animateQueue.push(element, 'animate', options);
  16440. }
  16441. };
  16442. }];
  16443. }];
  16444. var $$AnimateAsyncRunFactoryProvider = function() {
  16445. this.$get = ['$$rAF', function($$rAF) {
  16446. var waitQueue = [];
  16447. function waitForTick(fn) {
  16448. waitQueue.push(fn);
  16449. if (waitQueue.length > 1) return;
  16450. $$rAF(function() {
  16451. for (var i = 0; i < waitQueue.length; i++) {
  16452. waitQueue[i]();
  16453. }
  16454. waitQueue = [];
  16455. });
  16456. }
  16457. return function() {
  16458. var passed = false;
  16459. waitForTick(function() {
  16460. passed = true;
  16461. });
  16462. return function(callback) {
  16463. passed ? callback() : waitForTick(callback);
  16464. };
  16465. };
  16466. }];
  16467. };
  16468. var $$AnimateRunnerFactoryProvider = function() {
  16469. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  16470. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  16471. var INITIAL_STATE = 0;
  16472. var DONE_PENDING_STATE = 1;
  16473. var DONE_COMPLETE_STATE = 2;
  16474. AnimateRunner.chain = function(chain, callback) {
  16475. var index = 0;
  16476. next();
  16477. function next() {
  16478. if (index === chain.length) {
  16479. callback(true);
  16480. return;
  16481. }
  16482. chain[index](function(response) {
  16483. if (response === false) {
  16484. callback(false);
  16485. return;
  16486. }
  16487. index++;
  16488. next();
  16489. });
  16490. }
  16491. };
  16492. AnimateRunner.all = function(runners, callback) {
  16493. var count = 0;
  16494. var status = true;
  16495. forEach(runners, function(runner) {
  16496. runner.done(onProgress);
  16497. });
  16498. function onProgress(response) {
  16499. status = status && response;
  16500. if (++count === runners.length) {
  16501. callback(status);
  16502. }
  16503. }
  16504. };
  16505. function AnimateRunner(host) {
  16506. this.setHost(host);
  16507. var rafTick = $$animateAsyncRun();
  16508. var timeoutTick = function(fn) {
  16509. $timeout(fn, 0, false);
  16510. };
  16511. this._doneCallbacks = [];
  16512. this._tick = function(fn) {
  16513. var doc = $document[0];
  16514. // the document may not be ready or attached
  16515. // to the module for some internal tests
  16516. if (doc && doc.hidden) {
  16517. timeoutTick(fn);
  16518. } else {
  16519. rafTick(fn);
  16520. }
  16521. };
  16522. this._state = 0;
  16523. }
  16524. AnimateRunner.prototype = {
  16525. setHost: function(host) {
  16526. this.host = host || {};
  16527. },
  16528. done: function(fn) {
  16529. if (this._state === DONE_COMPLETE_STATE) {
  16530. fn();
  16531. } else {
  16532. this._doneCallbacks.push(fn);
  16533. }
  16534. },
  16535. progress: noop,
  16536. getPromise: function() {
  16537. if (!this.promise) {
  16538. var self = this;
  16539. this.promise = $q(function(resolve, reject) {
  16540. self.done(function(status) {
  16541. status === false ? reject() : resolve();
  16542. });
  16543. });
  16544. }
  16545. return this.promise;
  16546. },
  16547. then: function(resolveHandler, rejectHandler) {
  16548. return this.getPromise().then(resolveHandler, rejectHandler);
  16549. },
  16550. 'catch': function(handler) {
  16551. return this.getPromise()['catch'](handler);
  16552. },
  16553. 'finally': function(handler) {
  16554. return this.getPromise()['finally'](handler);
  16555. },
  16556. pause: function() {
  16557. if (this.host.pause) {
  16558. this.host.pause();
  16559. }
  16560. },
  16561. resume: function() {
  16562. if (this.host.resume) {
  16563. this.host.resume();
  16564. }
  16565. },
  16566. end: function() {
  16567. if (this.host.end) {
  16568. this.host.end();
  16569. }
  16570. this._resolve(true);
  16571. },
  16572. cancel: function() {
  16573. if (this.host.cancel) {
  16574. this.host.cancel();
  16575. }
  16576. this._resolve(false);
  16577. },
  16578. complete: function(response) {
  16579. var self = this;
  16580. if (self._state === INITIAL_STATE) {
  16581. self._state = DONE_PENDING_STATE;
  16582. self._tick(function() {
  16583. self._resolve(response);
  16584. });
  16585. }
  16586. },
  16587. _resolve: function(response) {
  16588. if (this._state !== DONE_COMPLETE_STATE) {
  16589. forEach(this._doneCallbacks, function(fn) {
  16590. fn(response);
  16591. });
  16592. this._doneCallbacks.length = 0;
  16593. this._state = DONE_COMPLETE_STATE;
  16594. }
  16595. }
  16596. };
  16597. return AnimateRunner;
  16598. }];
  16599. };
  16600. /**
  16601. * @ngdoc service
  16602. * @name $animateCss
  16603. * @kind object
  16604. *
  16605. * @description
  16606. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  16607. * then the `$animateCss` service will actually perform animations.
  16608. *
  16609. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  16610. */
  16611. var $CoreAnimateCssProvider = function() {
  16612. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  16613. return function(element, initialOptions) {
  16614. // all of the animation functions should create
  16615. // a copy of the options data, however, if a
  16616. // parent service has already created a copy then
  16617. // we should stick to using that
  16618. var options = initialOptions || {};
  16619. if (!options.$$prepared) {
  16620. options = copy(options);
  16621. }
  16622. // there is no point in applying the styles since
  16623. // there is no animation that goes on at all in
  16624. // this version of $animateCss.
  16625. if (options.cleanupStyles) {
  16626. options.from = options.to = null;
  16627. }
  16628. if (options.from) {
  16629. element.css(options.from);
  16630. options.from = null;
  16631. }
  16632. /* jshint newcap: false */
  16633. var closed, runner = new $$AnimateRunner();
  16634. return {
  16635. start: run,
  16636. end: run
  16637. };
  16638. function run() {
  16639. $$rAF(function() {
  16640. applyAnimationContents();
  16641. if (!closed) {
  16642. runner.complete();
  16643. }
  16644. closed = true;
  16645. });
  16646. return runner;
  16647. }
  16648. function applyAnimationContents() {
  16649. if (options.addClass) {
  16650. element.addClass(options.addClass);
  16651. options.addClass = null;
  16652. }
  16653. if (options.removeClass) {
  16654. element.removeClass(options.removeClass);
  16655. options.removeClass = null;
  16656. }
  16657. if (options.to) {
  16658. element.css(options.to);
  16659. options.to = null;
  16660. }
  16661. }
  16662. };
  16663. }];
  16664. };
  16665. /* global stripHash: true */
  16666. /**
  16667. * ! This is a private undocumented service !
  16668. *
  16669. * @name $browser
  16670. * @requires $log
  16671. * @description
  16672. * This object has two goals:
  16673. *
  16674. * - hide all the global state in the browser caused by the window object
  16675. * - abstract away all the browser specific features and inconsistencies
  16676. *
  16677. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  16678. * service, which can be used for convenient testing of the application without the interaction with
  16679. * the real browser apis.
  16680. */
  16681. /**
  16682. * @param {object} window The global window object.
  16683. * @param {object} document jQuery wrapped document.
  16684. * @param {object} $log window.console or an object with the same interface.
  16685. * @param {object} $sniffer $sniffer service
  16686. */
  16687. function Browser(window, document, $log, $sniffer) {
  16688. var self = this,
  16689. location = window.location,
  16690. history = window.history,
  16691. setTimeout = window.setTimeout,
  16692. clearTimeout = window.clearTimeout,
  16693. pendingDeferIds = {};
  16694. self.isMock = false;
  16695. var outstandingRequestCount = 0;
  16696. var outstandingRequestCallbacks = [];
  16697. // TODO(vojta): remove this temporary api
  16698. self.$$completeOutstandingRequest = completeOutstandingRequest;
  16699. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  16700. /**
  16701. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  16702. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  16703. */
  16704. function completeOutstandingRequest(fn) {
  16705. try {
  16706. fn.apply(null, sliceArgs(arguments, 1));
  16707. } finally {
  16708. outstandingRequestCount--;
  16709. if (outstandingRequestCount === 0) {
  16710. while (outstandingRequestCallbacks.length) {
  16711. try {
  16712. outstandingRequestCallbacks.pop()();
  16713. } catch (e) {
  16714. $log.error(e);
  16715. }
  16716. }
  16717. }
  16718. }
  16719. }
  16720. function getHash(url) {
  16721. var index = url.indexOf('#');
  16722. return index === -1 ? '' : url.substr(index);
  16723. }
  16724. /**
  16725. * @private
  16726. * Note: this method is used only by scenario runner
  16727. * TODO(vojta): prefix this method with $$ ?
  16728. * @param {function()} callback Function that will be called when no outstanding request
  16729. */
  16730. self.notifyWhenNoOutstandingRequests = function(callback) {
  16731. if (outstandingRequestCount === 0) {
  16732. callback();
  16733. } else {
  16734. outstandingRequestCallbacks.push(callback);
  16735. }
  16736. };
  16737. //////////////////////////////////////////////////////////////
  16738. // URL API
  16739. //////////////////////////////////////////////////////////////
  16740. var cachedState, lastHistoryState,
  16741. lastBrowserUrl = location.href,
  16742. baseElement = document.find('base'),
  16743. pendingLocation = null,
  16744. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  16745. try {
  16746. return history.state;
  16747. } catch (e) {
  16748. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  16749. }
  16750. };
  16751. cacheState();
  16752. lastHistoryState = cachedState;
  16753. /**
  16754. * @name $browser#url
  16755. *
  16756. * @description
  16757. * GETTER:
  16758. * Without any argument, this method just returns current value of location.href.
  16759. *
  16760. * SETTER:
  16761. * With at least one argument, this method sets url to new value.
  16762. * If html5 history api supported, pushState/replaceState is used, otherwise
  16763. * location.href/location.replace is used.
  16764. * Returns its own instance to allow chaining
  16765. *
  16766. * NOTE: this api is intended for use only by the $location service. Please use the
  16767. * {@link ng.$location $location service} to change url.
  16768. *
  16769. * @param {string} url New url (when used as setter)
  16770. * @param {boolean=} replace Should new url replace current history record?
  16771. * @param {object=} state object to use with pushState/replaceState
  16772. */
  16773. self.url = function(url, replace, state) {
  16774. // In modern browsers `history.state` is `null` by default; treating it separately
  16775. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  16776. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  16777. if (isUndefined(state)) {
  16778. state = null;
  16779. }
  16780. // Android Browser BFCache causes location, history reference to become stale.
  16781. if (location !== window.location) location = window.location;
  16782. if (history !== window.history) history = window.history;
  16783. // setter
  16784. if (url) {
  16785. var sameState = lastHistoryState === state;
  16786. // Don't change anything if previous and current URLs and states match. This also prevents
  16787. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  16788. // See https://github.com/angular/angular.js/commit/ffb2701
  16789. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  16790. return self;
  16791. }
  16792. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  16793. lastBrowserUrl = url;
  16794. lastHistoryState = state;
  16795. // Don't use history API if only the hash changed
  16796. // due to a bug in IE10/IE11 which leads
  16797. // to not firing a `hashchange` nor `popstate` event
  16798. // in some cases (see #9143).
  16799. if ($sniffer.history && (!sameBase || !sameState)) {
  16800. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  16801. cacheState();
  16802. // Do the assignment again so that those two variables are referentially identical.
  16803. lastHistoryState = cachedState;
  16804. } else {
  16805. if (!sameBase || pendingLocation) {
  16806. pendingLocation = url;
  16807. }
  16808. if (replace) {
  16809. location.replace(url);
  16810. } else if (!sameBase) {
  16811. location.href = url;
  16812. } else {
  16813. location.hash = getHash(url);
  16814. }
  16815. if (location.href !== url) {
  16816. pendingLocation = url;
  16817. }
  16818. }
  16819. return self;
  16820. // getter
  16821. } else {
  16822. // - pendingLocation is needed as browsers don't allow to read out
  16823. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  16824. // https://openradar.appspot.com/22186109).
  16825. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  16826. return pendingLocation || location.href.replace(/%27/g,"'");
  16827. }
  16828. };
  16829. /**
  16830. * @name $browser#state
  16831. *
  16832. * @description
  16833. * This method is a getter.
  16834. *
  16835. * Return history.state or null if history.state is undefined.
  16836. *
  16837. * @returns {object} state
  16838. */
  16839. self.state = function() {
  16840. return cachedState;
  16841. };
  16842. var urlChangeListeners = [],
  16843. urlChangeInit = false;
  16844. function cacheStateAndFireUrlChange() {
  16845. pendingLocation = null;
  16846. cacheState();
  16847. fireUrlChange();
  16848. }
  16849. // This variable should be used *only* inside the cacheState function.
  16850. var lastCachedState = null;
  16851. function cacheState() {
  16852. // This should be the only place in $browser where `history.state` is read.
  16853. cachedState = getCurrentState();
  16854. cachedState = isUndefined(cachedState) ? null : cachedState;
  16855. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  16856. if (equals(cachedState, lastCachedState)) {
  16857. cachedState = lastCachedState;
  16858. }
  16859. lastCachedState = cachedState;
  16860. }
  16861. function fireUrlChange() {
  16862. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  16863. return;
  16864. }
  16865. lastBrowserUrl = self.url();
  16866. lastHistoryState = cachedState;
  16867. forEach(urlChangeListeners, function(listener) {
  16868. listener(self.url(), cachedState);
  16869. });
  16870. }
  16871. /**
  16872. * @name $browser#onUrlChange
  16873. *
  16874. * @description
  16875. * Register callback function that will be called, when url changes.
  16876. *
  16877. * It's only called when the url is changed from outside of angular:
  16878. * - user types different url into address bar
  16879. * - user clicks on history (forward/back) button
  16880. * - user clicks on a link
  16881. *
  16882. * It's not called when url is changed by $browser.url() method
  16883. *
  16884. * The listener gets called with new url as parameter.
  16885. *
  16886. * NOTE: this api is intended for use only by the $location service. Please use the
  16887. * {@link ng.$location $location service} to monitor url changes in angular apps.
  16888. *
  16889. * @param {function(string)} listener Listener function to be called when url changes.
  16890. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  16891. */
  16892. self.onUrlChange = function(callback) {
  16893. // TODO(vojta): refactor to use node's syntax for events
  16894. if (!urlChangeInit) {
  16895. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  16896. // don't fire popstate when user change the address bar and don't fire hashchange when url
  16897. // changed by push/replaceState
  16898. // html5 history api - popstate event
  16899. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  16900. // hashchange event
  16901. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  16902. urlChangeInit = true;
  16903. }
  16904. urlChangeListeners.push(callback);
  16905. return callback;
  16906. };
  16907. /**
  16908. * @private
  16909. * Remove popstate and hashchange handler from window.
  16910. *
  16911. * NOTE: this api is intended for use only by $rootScope.
  16912. */
  16913. self.$$applicationDestroyed = function() {
  16914. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  16915. };
  16916. /**
  16917. * Checks whether the url has changed outside of Angular.
  16918. * Needs to be exported to be able to check for changes that have been done in sync,
  16919. * as hashchange/popstate events fire in async.
  16920. */
  16921. self.$$checkUrlChange = fireUrlChange;
  16922. //////////////////////////////////////////////////////////////
  16923. // Misc API
  16924. //////////////////////////////////////////////////////////////
  16925. /**
  16926. * @name $browser#baseHref
  16927. *
  16928. * @description
  16929. * Returns current <base href>
  16930. * (always relative - without domain)
  16931. *
  16932. * @returns {string} The current base href
  16933. */
  16934. self.baseHref = function() {
  16935. var href = baseElement.attr('href');
  16936. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  16937. };
  16938. /**
  16939. * @name $browser#defer
  16940. * @param {function()} fn A function, who's execution should be deferred.
  16941. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  16942. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  16943. *
  16944. * @description
  16945. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  16946. *
  16947. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  16948. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  16949. * via `$browser.defer.flush()`.
  16950. *
  16951. */
  16952. self.defer = function(fn, delay) {
  16953. var timeoutId;
  16954. outstandingRequestCount++;
  16955. timeoutId = setTimeout(function() {
  16956. delete pendingDeferIds[timeoutId];
  16957. completeOutstandingRequest(fn);
  16958. }, delay || 0);
  16959. pendingDeferIds[timeoutId] = true;
  16960. return timeoutId;
  16961. };
  16962. /**
  16963. * @name $browser#defer.cancel
  16964. *
  16965. * @description
  16966. * Cancels a deferred task identified with `deferId`.
  16967. *
  16968. * @param {*} deferId Token returned by the `$browser.defer` function.
  16969. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16970. * canceled.
  16971. */
  16972. self.defer.cancel = function(deferId) {
  16973. if (pendingDeferIds[deferId]) {
  16974. delete pendingDeferIds[deferId];
  16975. clearTimeout(deferId);
  16976. completeOutstandingRequest(noop);
  16977. return true;
  16978. }
  16979. return false;
  16980. };
  16981. }
  16982. function $BrowserProvider() {
  16983. this.$get = ['$window', '$log', '$sniffer', '$document',
  16984. function($window, $log, $sniffer, $document) {
  16985. return new Browser($window, $document, $log, $sniffer);
  16986. }];
  16987. }
  16988. /**
  16989. * @ngdoc service
  16990. * @name $cacheFactory
  16991. *
  16992. * @description
  16993. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  16994. * them.
  16995. *
  16996. * ```js
  16997. *
  16998. * var cache = $cacheFactory('cacheId');
  16999. * expect($cacheFactory.get('cacheId')).toBe(cache);
  17000. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  17001. *
  17002. * cache.put("key", "value");
  17003. * cache.put("another key", "another value");
  17004. *
  17005. * // We've specified no options on creation
  17006. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  17007. *
  17008. * ```
  17009. *
  17010. *
  17011. * @param {string} cacheId Name or id of the newly created cache.
  17012. * @param {object=} options Options object that specifies the cache behavior. Properties:
  17013. *
  17014. * - `{number=}` `capacity` — turns the cache into LRU cache.
  17015. *
  17016. * @returns {object} Newly created cache object with the following set of methods:
  17017. *
  17018. * - `{object}` `info()` — Returns id, size, and options of cache.
  17019. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  17020. * it.
  17021. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  17022. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  17023. * - `{void}` `removeAll()` — Removes all cached values.
  17024. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  17025. *
  17026. * @example
  17027. <example module="cacheExampleApp">
  17028. <file name="index.html">
  17029. <div ng-controller="CacheController">
  17030. <input ng-model="newCacheKey" placeholder="Key">
  17031. <input ng-model="newCacheValue" placeholder="Value">
  17032. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  17033. <p ng-if="keys.length">Cached Values</p>
  17034. <div ng-repeat="key in keys">
  17035. <span ng-bind="key"></span>
  17036. <span>: </span>
  17037. <b ng-bind="cache.get(key)"></b>
  17038. </div>
  17039. <p>Cache Info</p>
  17040. <div ng-repeat="(key, value) in cache.info()">
  17041. <span ng-bind="key"></span>
  17042. <span>: </span>
  17043. <b ng-bind="value"></b>
  17044. </div>
  17045. </div>
  17046. </file>
  17047. <file name="script.js">
  17048. angular.module('cacheExampleApp', []).
  17049. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  17050. $scope.keys = [];
  17051. $scope.cache = $cacheFactory('cacheId');
  17052. $scope.put = function(key, value) {
  17053. if (angular.isUndefined($scope.cache.get(key))) {
  17054. $scope.keys.push(key);
  17055. }
  17056. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  17057. };
  17058. }]);
  17059. </file>
  17060. <file name="style.css">
  17061. p {
  17062. margin: 10px 0 3px;
  17063. }
  17064. </file>
  17065. </example>
  17066. */
  17067. function $CacheFactoryProvider() {
  17068. this.$get = function() {
  17069. var caches = {};
  17070. function cacheFactory(cacheId, options) {
  17071. if (cacheId in caches) {
  17072. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  17073. }
  17074. var size = 0,
  17075. stats = extend({}, options, {id: cacheId}),
  17076. data = createMap(),
  17077. capacity = (options && options.capacity) || Number.MAX_VALUE,
  17078. lruHash = createMap(),
  17079. freshEnd = null,
  17080. staleEnd = null;
  17081. /**
  17082. * @ngdoc type
  17083. * @name $cacheFactory.Cache
  17084. *
  17085. * @description
  17086. * A cache object used to store and retrieve data, primarily used by
  17087. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  17088. * templates and other data.
  17089. *
  17090. * ```js
  17091. * angular.module('superCache')
  17092. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  17093. * return $cacheFactory('super-cache');
  17094. * }]);
  17095. * ```
  17096. *
  17097. * Example test:
  17098. *
  17099. * ```js
  17100. * it('should behave like a cache', inject(function(superCache) {
  17101. * superCache.put('key', 'value');
  17102. * superCache.put('another key', 'another value');
  17103. *
  17104. * expect(superCache.info()).toEqual({
  17105. * id: 'super-cache',
  17106. * size: 2
  17107. * });
  17108. *
  17109. * superCache.remove('another key');
  17110. * expect(superCache.get('another key')).toBeUndefined();
  17111. *
  17112. * superCache.removeAll();
  17113. * expect(superCache.info()).toEqual({
  17114. * id: 'super-cache',
  17115. * size: 0
  17116. * });
  17117. * }));
  17118. * ```
  17119. */
  17120. return caches[cacheId] = {
  17121. /**
  17122. * @ngdoc method
  17123. * @name $cacheFactory.Cache#put
  17124. * @kind function
  17125. *
  17126. * @description
  17127. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  17128. * retrieved later, and incrementing the size of the cache if the key was not already
  17129. * present in the cache. If behaving like an LRU cache, it will also remove stale
  17130. * entries from the set.
  17131. *
  17132. * It will not insert undefined values into the cache.
  17133. *
  17134. * @param {string} key the key under which the cached data is stored.
  17135. * @param {*} value the value to store alongside the key. If it is undefined, the key
  17136. * will not be stored.
  17137. * @returns {*} the value stored.
  17138. */
  17139. put: function(key, value) {
  17140. if (isUndefined(value)) return;
  17141. if (capacity < Number.MAX_VALUE) {
  17142. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  17143. refresh(lruEntry);
  17144. }
  17145. if (!(key in data)) size++;
  17146. data[key] = value;
  17147. if (size > capacity) {
  17148. this.remove(staleEnd.key);
  17149. }
  17150. return value;
  17151. },
  17152. /**
  17153. * @ngdoc method
  17154. * @name $cacheFactory.Cache#get
  17155. * @kind function
  17156. *
  17157. * @description
  17158. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  17159. *
  17160. * @param {string} key the key of the data to be retrieved
  17161. * @returns {*} the value stored.
  17162. */
  17163. get: function(key) {
  17164. if (capacity < Number.MAX_VALUE) {
  17165. var lruEntry = lruHash[key];
  17166. if (!lruEntry) return;
  17167. refresh(lruEntry);
  17168. }
  17169. return data[key];
  17170. },
  17171. /**
  17172. * @ngdoc method
  17173. * @name $cacheFactory.Cache#remove
  17174. * @kind function
  17175. *
  17176. * @description
  17177. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  17178. *
  17179. * @param {string} key the key of the entry to be removed
  17180. */
  17181. remove: function(key) {
  17182. if (capacity < Number.MAX_VALUE) {
  17183. var lruEntry = lruHash[key];
  17184. if (!lruEntry) return;
  17185. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  17186. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  17187. link(lruEntry.n,lruEntry.p);
  17188. delete lruHash[key];
  17189. }
  17190. if (!(key in data)) return;
  17191. delete data[key];
  17192. size--;
  17193. },
  17194. /**
  17195. * @ngdoc method
  17196. * @name $cacheFactory.Cache#removeAll
  17197. * @kind function
  17198. *
  17199. * @description
  17200. * Clears the cache object of any entries.
  17201. */
  17202. removeAll: function() {
  17203. data = createMap();
  17204. size = 0;
  17205. lruHash = createMap();
  17206. freshEnd = staleEnd = null;
  17207. },
  17208. /**
  17209. * @ngdoc method
  17210. * @name $cacheFactory.Cache#destroy
  17211. * @kind function
  17212. *
  17213. * @description
  17214. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  17215. * removing it from the {@link $cacheFactory $cacheFactory} set.
  17216. */
  17217. destroy: function() {
  17218. data = null;
  17219. stats = null;
  17220. lruHash = null;
  17221. delete caches[cacheId];
  17222. },
  17223. /**
  17224. * @ngdoc method
  17225. * @name $cacheFactory.Cache#info
  17226. * @kind function
  17227. *
  17228. * @description
  17229. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  17230. *
  17231. * @returns {object} an object with the following properties:
  17232. * <ul>
  17233. * <li>**id**: the id of the cache instance</li>
  17234. * <li>**size**: the number of entries kept in the cache instance</li>
  17235. * <li>**...**: any additional properties from the options object when creating the
  17236. * cache.</li>
  17237. * </ul>
  17238. */
  17239. info: function() {
  17240. return extend({}, stats, {size: size});
  17241. }
  17242. };
  17243. /**
  17244. * makes the `entry` the freshEnd of the LRU linked list
  17245. */
  17246. function refresh(entry) {
  17247. if (entry != freshEnd) {
  17248. if (!staleEnd) {
  17249. staleEnd = entry;
  17250. } else if (staleEnd == entry) {
  17251. staleEnd = entry.n;
  17252. }
  17253. link(entry.n, entry.p);
  17254. link(entry, freshEnd);
  17255. freshEnd = entry;
  17256. freshEnd.n = null;
  17257. }
  17258. }
  17259. /**
  17260. * bidirectionally links two entries of the LRU linked list
  17261. */
  17262. function link(nextEntry, prevEntry) {
  17263. if (nextEntry != prevEntry) {
  17264. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  17265. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  17266. }
  17267. }
  17268. }
  17269. /**
  17270. * @ngdoc method
  17271. * @name $cacheFactory#info
  17272. *
  17273. * @description
  17274. * Get information about all the caches that have been created
  17275. *
  17276. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  17277. */
  17278. cacheFactory.info = function() {
  17279. var info = {};
  17280. forEach(caches, function(cache, cacheId) {
  17281. info[cacheId] = cache.info();
  17282. });
  17283. return info;
  17284. };
  17285. /**
  17286. * @ngdoc method
  17287. * @name $cacheFactory#get
  17288. *
  17289. * @description
  17290. * Get access to a cache object by the `cacheId` used when it was created.
  17291. *
  17292. * @param {string} cacheId Name or id of a cache to access.
  17293. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  17294. */
  17295. cacheFactory.get = function(cacheId) {
  17296. return caches[cacheId];
  17297. };
  17298. return cacheFactory;
  17299. };
  17300. }
  17301. /**
  17302. * @ngdoc service
  17303. * @name $templateCache
  17304. *
  17305. * @description
  17306. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  17307. * can load templates directly into the cache in a `script` tag, or by consuming the
  17308. * `$templateCache` service directly.
  17309. *
  17310. * Adding via the `script` tag:
  17311. *
  17312. * ```html
  17313. * <script type="text/ng-template" id="templateId.html">
  17314. * <p>This is the content of the template</p>
  17315. * </script>
  17316. * ```
  17317. *
  17318. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  17319. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  17320. * element with ng-app attribute), otherwise the template will be ignored.
  17321. *
  17322. * Adding via the `$templateCache` service:
  17323. *
  17324. * ```js
  17325. * var myApp = angular.module('myApp', []);
  17326. * myApp.run(function($templateCache) {
  17327. * $templateCache.put('templateId.html', 'This is the content of the template');
  17328. * });
  17329. * ```
  17330. *
  17331. * To retrieve the template later, simply use it in your HTML:
  17332. * ```html
  17333. * <div ng-include=" 'templateId.html' "></div>
  17334. * ```
  17335. *
  17336. * or get it via Javascript:
  17337. * ```js
  17338. * $templateCache.get('templateId.html')
  17339. * ```
  17340. *
  17341. * See {@link ng.$cacheFactory $cacheFactory}.
  17342. *
  17343. */
  17344. function $TemplateCacheProvider() {
  17345. this.$get = ['$cacheFactory', function($cacheFactory) {
  17346. return $cacheFactory('templates');
  17347. }];
  17348. }
  17349. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17350. * Any commits to this file should be reviewed with security in mind. *
  17351. * Changes to this file can potentially create security vulnerabilities. *
  17352. * An approval from 2 Core members with history of modifying *
  17353. * this file is required. *
  17354. * *
  17355. * Does the change somehow allow for arbitrary javascript to be executed? *
  17356. * Or allows for someone to change the prototype of built-in objects? *
  17357. * Or gives undesired access to variables likes document or window? *
  17358. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17359. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  17360. *
  17361. * DOM-related variables:
  17362. *
  17363. * - "node" - DOM Node
  17364. * - "element" - DOM Element or Node
  17365. * - "$node" or "$element" - jqLite-wrapped node or element
  17366. *
  17367. *
  17368. * Compiler related stuff:
  17369. *
  17370. * - "linkFn" - linking fn of a single directive
  17371. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  17372. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  17373. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  17374. */
  17375. /**
  17376. * @ngdoc service
  17377. * @name $compile
  17378. * @kind function
  17379. *
  17380. * @description
  17381. * Compiles an HTML string or DOM into a template and produces a template function, which
  17382. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  17383. *
  17384. * The compilation is a process of walking the DOM tree and matching DOM elements to
  17385. * {@link ng.$compileProvider#directive directives}.
  17386. *
  17387. * <div class="alert alert-warning">
  17388. * **Note:** This document is an in-depth reference of all directive options.
  17389. * For a gentle introduction to directives with examples of common use cases,
  17390. * see the {@link guide/directive directive guide}.
  17391. * </div>
  17392. *
  17393. * ## Comprehensive Directive API
  17394. *
  17395. * There are many different options for a directive.
  17396. *
  17397. * The difference resides in the return value of the factory function.
  17398. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  17399. * or just the `postLink` function (all other properties will have the default values).
  17400. *
  17401. * <div class="alert alert-success">
  17402. * **Best Practice:** It's recommended to use the "directive definition object" form.
  17403. * </div>
  17404. *
  17405. * Here's an example directive declared with a Directive Definition Object:
  17406. *
  17407. * ```js
  17408. * var myModule = angular.module(...);
  17409. *
  17410. * myModule.directive('directiveName', function factory(injectables) {
  17411. * var directiveDefinitionObject = {
  17412. * priority: 0,
  17413. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  17414. * // or
  17415. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  17416. * transclude: false,
  17417. * restrict: 'A',
  17418. * templateNamespace: 'html',
  17419. * scope: false,
  17420. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  17421. * controllerAs: 'stringIdentifier',
  17422. * bindToController: false,
  17423. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  17424. * compile: function compile(tElement, tAttrs, transclude) {
  17425. * return {
  17426. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  17427. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  17428. * }
  17429. * // or
  17430. * // return function postLink( ... ) { ... }
  17431. * },
  17432. * // or
  17433. * // link: {
  17434. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  17435. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  17436. * // }
  17437. * // or
  17438. * // link: function postLink( ... ) { ... }
  17439. * };
  17440. * return directiveDefinitionObject;
  17441. * });
  17442. * ```
  17443. *
  17444. * <div class="alert alert-warning">
  17445. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  17446. * </div>
  17447. *
  17448. * Therefore the above can be simplified as:
  17449. *
  17450. * ```js
  17451. * var myModule = angular.module(...);
  17452. *
  17453. * myModule.directive('directiveName', function factory(injectables) {
  17454. * var directiveDefinitionObject = {
  17455. * link: function postLink(scope, iElement, iAttrs) { ... }
  17456. * };
  17457. * return directiveDefinitionObject;
  17458. * // or
  17459. * // return function postLink(scope, iElement, iAttrs) { ... }
  17460. * });
  17461. * ```
  17462. *
  17463. *
  17464. *
  17465. * ### Directive Definition Object
  17466. *
  17467. * The directive definition object provides instructions to the {@link ng.$compile
  17468. * compiler}. The attributes are:
  17469. *
  17470. * #### `multiElement`
  17471. * When this property is set to true, the HTML compiler will collect DOM nodes between
  17472. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  17473. * together as the directive elements. It is recommended that this feature be used on directives
  17474. * which are not strictly behavioral (such as {@link ngClick}), and which
  17475. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  17476. *
  17477. * #### `priority`
  17478. * When there are multiple directives defined on a single DOM element, sometimes it
  17479. * is necessary to specify the order in which the directives are applied. The `priority` is used
  17480. * to sort the directives before their `compile` functions get called. Priority is defined as a
  17481. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  17482. * are also run in priority order, but post-link functions are run in reverse order. The order
  17483. * of directives with the same priority is undefined. The default priority is `0`.
  17484. *
  17485. * #### `terminal`
  17486. * If set to true then the current `priority` will be the last set of directives
  17487. * which will execute (any directives at the current priority will still execute
  17488. * as the order of execution on same `priority` is undefined). Note that expressions
  17489. * and other directives used in the directive's template will also be excluded from execution.
  17490. *
  17491. * #### `scope`
  17492. * The scope property can be `true`, an object or a falsy value:
  17493. *
  17494. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  17495. *
  17496. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  17497. * the directive's element. If multiple directives on the same element request a new scope,
  17498. * only one new scope is created. The new scope rule does not apply for the root of the template
  17499. * since the root of the template always gets a new scope.
  17500. *
  17501. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  17502. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  17503. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  17504. * data in the parent scope.
  17505. *
  17506. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  17507. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  17508. * the object hash map to the name of the property on the isolate scope; the values define how the property
  17509. * is bound to the parent scope, via matching attributes on the directive's element:
  17510. *
  17511. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  17512. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  17513. * attribute name is assumed to be the same as the local name. Given `<my-component
  17514. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  17515. * the directive's scope property `localName` will reflect the interpolated value of `hello
  17516. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  17517. * scope. The `name` is read from the parent scope (not the directive's scope).
  17518. *
  17519. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  17520. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  17521. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  17522. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  17523. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  17524. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  17525. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  17526. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  17527. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  17528. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  17529. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  17530. * method is used for tracking changes, and the equality check is based on object identity.
  17531. * However, if an object literal or an array literal is passed as the binding expression, the
  17532. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  17533. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  17534. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  17535. *
  17536. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  17537. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  17538. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  17539. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  17540. *
  17541. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  17542. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  17543. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  17544. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  17545. * two caveats:
  17546. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  17547. * sets the same value. That means if your bound value is an object, changes to its properties
  17548. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  17549. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  17550. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  17551. * to the value has changed. In most cases, this should not be of concern, but can be important
  17552. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  17553. * If you now change a property of the object in your parent scope, the change will not be
  17554. * propagated to the isolated scope, because the identity of the object on the parent scope
  17555. * has not changed. Instead you must assign a new object.
  17556. *
  17557. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  17558. * back to the parent. However, it does not make this completely impossible.
  17559. *
  17560. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  17561. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  17562. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  17563. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  17564. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  17565. * via an expression to the parent scope. This can be done by passing a map of local variable names
  17566. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  17567. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  17568. *
  17569. * In general it's possible to apply more than one directive to one element, but there might be limitations
  17570. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  17571. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  17572. *
  17573. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  17574. * * **child scope** + **no scope** => Both directives will share one single child scope
  17575. * * **child scope** + **child scope** => Both directives will share one single child scope
  17576. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  17577. * its parent's scope
  17578. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  17579. * be applied to the same element.
  17580. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  17581. * cannot be applied to the same element.
  17582. *
  17583. *
  17584. * #### `bindToController`
  17585. * This property is used to bind scope properties directly to the controller. It can be either
  17586. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  17587. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  17588. * definition: `controller: 'myCtrl as myAlias'`.
  17589. *
  17590. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  17591. * allow a component to have its properties bound to the controller, rather than to scope.
  17592. *
  17593. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  17594. * properties. You can access these bindings once they have been initialized by providing a controller method called
  17595. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  17596. * initialized.
  17597. *
  17598. * <div class="alert alert-warning">
  17599. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  17600. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  17601. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  17602. * </div>
  17603. *
  17604. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  17605. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  17606. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  17607. * scope (useful for component directives).
  17608. *
  17609. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  17610. *
  17611. *
  17612. * #### `controller`
  17613. * Controller constructor function. The controller is instantiated before the
  17614. * pre-linking phase and can be accessed by other directives (see
  17615. * `require` attribute). This allows the directives to communicate with each other and augment
  17616. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  17617. *
  17618. * * `$scope` - Current scope associated with the element
  17619. * * `$element` - Current element
  17620. * * `$attrs` - Current attributes object for the element
  17621. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  17622. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  17623. * * `scope`: (optional) override the scope.
  17624. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  17625. * * `futureParentElement` (optional):
  17626. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  17627. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  17628. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  17629. * and when the `cloneLinkinFn` is passed,
  17630. * as those elements need to created and cloned in a special way when they are defined outside their
  17631. * usual containers (e.g. like `<svg>`).
  17632. * * See also the `directive.templateNamespace` property.
  17633. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  17634. * then the default translusion is provided.
  17635. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  17636. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  17637. *
  17638. * The controller can provide the following methods that act as life-cycle hooks:
  17639. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  17640. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  17641. * this element). This is a good place to put initialization code for your controller.
  17642. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  17643. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  17644. * object of the form `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component
  17645. * such as cloning the bound value to prevent accidental mutation of the outer value.
  17646. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  17647. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  17648. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  17649. * components will have their `$onDestroy()` hook called before child components.
  17650. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  17651. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  17652. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  17653. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  17654. * suspended until that occurs.
  17655. *
  17656. *
  17657. * #### `require`
  17658. * Require another directive and inject its controller as the fourth argument to the linking function. The
  17659. * `require` property can be a string, an array or an object:
  17660. * * a **string** containing the name of the directive to pass to the linking function
  17661. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  17662. * linking function will be an array of controllers in the same order as the names in the `require` property
  17663. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  17664. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  17665. * controllers.
  17666. *
  17667. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  17668. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  17669. * have been constructed but before `$onInit` is called.
  17670. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  17671. *
  17672. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  17673. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  17674. * controller, in which case error checking is skipped). The name can be prefixed with:
  17675. *
  17676. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  17677. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  17678. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  17679. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  17680. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  17681. * `null` to the `link` fn if not found.
  17682. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  17683. * `null` to the `link` fn if not found.
  17684. *
  17685. *
  17686. * #### `controllerAs`
  17687. * Identifier name for a reference to the controller in the directive's scope.
  17688. * This allows the controller to be referenced from the directive template. This is especially
  17689. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  17690. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  17691. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  17692. *
  17693. *
  17694. * #### `restrict`
  17695. * String of subset of `EACM` which restricts the directive to a specific directive
  17696. * declaration style. If omitted, the defaults (elements and attributes) are used.
  17697. *
  17698. * * `E` - Element name (default): `<my-directive></my-directive>`
  17699. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  17700. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  17701. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  17702. *
  17703. *
  17704. * #### `templateNamespace`
  17705. * String representing the document type used by the markup in the template.
  17706. * AngularJS needs this information as those elements need to be created and cloned
  17707. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  17708. *
  17709. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  17710. * top-level elements such as `<svg>` or `<math>`.
  17711. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  17712. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  17713. *
  17714. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  17715. *
  17716. * #### `template`
  17717. * HTML markup that may:
  17718. * * Replace the contents of the directive's element (default).
  17719. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  17720. * * Wrap the contents of the directive's element (if `transclude` is true).
  17721. *
  17722. * Value may be:
  17723. *
  17724. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  17725. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  17726. * function api below) and returns a string value.
  17727. *
  17728. *
  17729. * #### `templateUrl`
  17730. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  17731. *
  17732. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  17733. * for later when the template has been resolved. In the meantime it will continue to compile and link
  17734. * sibling and parent elements as though this element had not contained any directives.
  17735. *
  17736. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  17737. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  17738. * case when only one deeply nested directive has `templateUrl`.
  17739. *
  17740. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  17741. *
  17742. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  17743. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  17744. * a string value representing the url. In either case, the template URL is passed through {@link
  17745. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  17746. *
  17747. *
  17748. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  17749. * specify what the template should replace. Defaults to `false`.
  17750. *
  17751. * * `true` - the template will replace the directive's element.
  17752. * * `false` - the template will replace the contents of the directive's element.
  17753. *
  17754. * The replacement process migrates all of the attributes / classes from the old element to the new
  17755. * one. See the {@link guide/directive#template-expanding-directive
  17756. * Directives Guide} for an example.
  17757. *
  17758. * There are very few scenarios where element replacement is required for the application function,
  17759. * the main one being reusable custom components that are used within SVG contexts
  17760. * (because SVG doesn't work with custom elements in the DOM tree).
  17761. *
  17762. * #### `transclude`
  17763. * Extract the contents of the element where the directive appears and make it available to the directive.
  17764. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  17765. * {@link $compile#transclusion Transclusion} section below.
  17766. *
  17767. *
  17768. * #### `compile`
  17769. *
  17770. * ```js
  17771. * function compile(tElement, tAttrs, transclude) { ... }
  17772. * ```
  17773. *
  17774. * The compile function deals with transforming the template DOM. Since most directives do not do
  17775. * template transformation, it is not used often. The compile function takes the following arguments:
  17776. *
  17777. * * `tElement` - template element - The element where the directive has been declared. It is
  17778. * safe to do template transformation on the element and child elements only.
  17779. *
  17780. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  17781. * between all directive compile functions.
  17782. *
  17783. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  17784. *
  17785. * <div class="alert alert-warning">
  17786. * **Note:** The template instance and the link instance may be different objects if the template has
  17787. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  17788. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  17789. * should be done in a linking function rather than in a compile function.
  17790. * </div>
  17791. * <div class="alert alert-warning">
  17792. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  17793. * own templates or compile functions. Compiling these directives results in an infinite loop and
  17794. * stack overflow errors.
  17795. *
  17796. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  17797. * a directive's template instead of relying on automatic template compilation via `template` or
  17798. * `templateUrl` declaration or manual compilation inside the compile function.
  17799. * </div>
  17800. *
  17801. * <div class="alert alert-danger">
  17802. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  17803. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  17804. * to the link function instead.
  17805. * </div>
  17806. * A compile function can have a return value which can be either a function or an object.
  17807. *
  17808. * * returning a (post-link) function - is equivalent to registering the linking function via the
  17809. * `link` property of the config object when the compile function is empty.
  17810. *
  17811. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  17812. * control when a linking function should be called during the linking phase. See info about
  17813. * pre-linking and post-linking functions below.
  17814. *
  17815. *
  17816. * #### `link`
  17817. * This property is used only if the `compile` property is not defined.
  17818. *
  17819. * ```js
  17820. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  17821. * ```
  17822. *
  17823. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  17824. * executed after the template has been cloned. This is where most of the directive logic will be
  17825. * put.
  17826. *
  17827. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  17828. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  17829. *
  17830. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  17831. * manipulate the children of the element only in `postLink` function since the children have
  17832. * already been linked.
  17833. *
  17834. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  17835. * between all directive linking functions.
  17836. *
  17837. * * `controller` - the directive's required controller instance(s) - Instances are shared
  17838. * among all directives, which allows the directives to use the controllers as a communication
  17839. * channel. The exact value depends on the directive's `require` property:
  17840. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  17841. * * `string`: the controller instance
  17842. * * `array`: array of controller instances
  17843. *
  17844. * If a required controller cannot be found, and it is optional, the instance is `null`,
  17845. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  17846. *
  17847. * Note that you can also require the directive's own controller - it will be made available like
  17848. * any other controller.
  17849. *
  17850. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  17851. * This is the same as the `$transclude`
  17852. * parameter of directive controllers, see there for details.
  17853. * `function([scope], cloneLinkingFn, futureParentElement)`.
  17854. *
  17855. * #### Pre-linking function
  17856. *
  17857. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  17858. * compiler linking function will fail to locate the correct elements for linking.
  17859. *
  17860. * #### Post-linking function
  17861. *
  17862. * Executed after the child elements are linked.
  17863. *
  17864. * Note that child elements that contain `templateUrl` directives will not have been compiled
  17865. * and linked since they are waiting for their template to load asynchronously and their own
  17866. * compilation and linking has been suspended until that occurs.
  17867. *
  17868. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  17869. * for their async templates to be resolved.
  17870. *
  17871. *
  17872. * ### Transclusion
  17873. *
  17874. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  17875. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  17876. * scope from where they were taken.
  17877. *
  17878. * Transclusion is used (often with {@link ngTransclude}) to insert the
  17879. * original contents of a directive's element into a specified place in the template of the directive.
  17880. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  17881. * content has access to the properties on the scope from which it was taken, even if the directive
  17882. * has isolated scope.
  17883. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  17884. *
  17885. * This makes it possible for the widget to have private state for its template, while the transcluded
  17886. * content has access to its originating scope.
  17887. *
  17888. * <div class="alert alert-warning">
  17889. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  17890. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  17891. * Testing Transclusion Directives}.
  17892. * </div>
  17893. *
  17894. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  17895. * directive's element, the entire element or multiple parts of the element contents:
  17896. *
  17897. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  17898. * * `'element'` - transclude the whole of the directive's element including any directives on this
  17899. * element that defined at a lower priority than this directive. When used, the `template`
  17900. * property is ignored.
  17901. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  17902. *
  17903. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  17904. *
  17905. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  17906. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  17907. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  17908. *
  17909. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  17910. *
  17911. * If the element selector is prefixed with a `?` then that slot is optional.
  17912. *
  17913. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  17914. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  17915. *
  17916. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  17917. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  17918. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  17919. * injectable into the directive's controller.
  17920. *
  17921. *
  17922. * #### Transclusion Functions
  17923. *
  17924. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  17925. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  17926. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  17927. *
  17928. * <div class="alert alert-info">
  17929. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  17930. * ngTransclude will deal with it for us.
  17931. * </div>
  17932. *
  17933. * If you want to manually control the insertion and removal of the transcluded content in your directive
  17934. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  17935. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  17936. *
  17937. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  17938. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  17939. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  17940. *
  17941. * <div class="alert alert-info">
  17942. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  17943. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  17944. * </div>
  17945. *
  17946. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  17947. * attach function**:
  17948. *
  17949. * ```js
  17950. * var transcludedContent, transclusionScope;
  17951. *
  17952. * $transclude(function(clone, scope) {
  17953. * element.append(clone);
  17954. * transcludedContent = clone;
  17955. * transclusionScope = scope;
  17956. * });
  17957. * ```
  17958. *
  17959. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  17960. * associated transclusion scope:
  17961. *
  17962. * ```js
  17963. * transcludedContent.remove();
  17964. * transclusionScope.$destroy();
  17965. * ```
  17966. *
  17967. * <div class="alert alert-info">
  17968. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  17969. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  17970. * then you are also responsible for calling `$destroy` on the transclusion scope.
  17971. * </div>
  17972. *
  17973. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  17974. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  17975. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  17976. *
  17977. *
  17978. * #### Transclusion Scopes
  17979. *
  17980. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  17981. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  17982. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  17983. * was taken.
  17984. *
  17985. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  17986. * like this:
  17987. *
  17988. * ```html
  17989. * <div ng-app>
  17990. * <div isolate>
  17991. * <div transclusion>
  17992. * </div>
  17993. * </div>
  17994. * </div>
  17995. * ```
  17996. *
  17997. * The `$parent` scope hierarchy will look like this:
  17998. *
  17999. ```
  18000. - $rootScope
  18001. - isolate
  18002. - transclusion
  18003. ```
  18004. *
  18005. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  18006. *
  18007. ```
  18008. - $rootScope
  18009. - transclusion
  18010. - isolate
  18011. ```
  18012. *
  18013. *
  18014. * ### Attributes
  18015. *
  18016. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  18017. * `link()` or `compile()` functions. It has a variety of uses.
  18018. *
  18019. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  18020. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  18021. * to the attributes.
  18022. *
  18023. * * *Directive inter-communication:* All directives share the same instance of the attributes
  18024. * object which allows the directives to use the attributes object as inter directive
  18025. * communication.
  18026. *
  18027. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  18028. * allowing other directives to read the interpolated value.
  18029. *
  18030. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  18031. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  18032. * the only way to easily get the actual value because during the linking phase the interpolation
  18033. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  18034. *
  18035. * ```js
  18036. * function linkingFn(scope, elm, attrs, ctrl) {
  18037. * // get the attribute value
  18038. * console.log(attrs.ngModel);
  18039. *
  18040. * // change the attribute
  18041. * attrs.$set('ngModel', 'new value');
  18042. *
  18043. * // observe changes to interpolated attribute
  18044. * attrs.$observe('ngModel', function(value) {
  18045. * console.log('ngModel has changed value to ' + value);
  18046. * });
  18047. * }
  18048. * ```
  18049. *
  18050. * ## Example
  18051. *
  18052. * <div class="alert alert-warning">
  18053. * **Note**: Typically directives are registered with `module.directive`. The example below is
  18054. * to illustrate how `$compile` works.
  18055. * </div>
  18056. *
  18057. <example module="compileExample">
  18058. <file name="index.html">
  18059. <script>
  18060. angular.module('compileExample', [], function($compileProvider) {
  18061. // configure new 'compile' directive by passing a directive
  18062. // factory function. The factory function injects the '$compile'
  18063. $compileProvider.directive('compile', function($compile) {
  18064. // directive factory creates a link function
  18065. return function(scope, element, attrs) {
  18066. scope.$watch(
  18067. function(scope) {
  18068. // watch the 'compile' expression for changes
  18069. return scope.$eval(attrs.compile);
  18070. },
  18071. function(value) {
  18072. // when the 'compile' expression changes
  18073. // assign it into the current DOM
  18074. element.html(value);
  18075. // compile the new DOM and link it to the current
  18076. // scope.
  18077. // NOTE: we only compile .childNodes so that
  18078. // we don't get into infinite loop compiling ourselves
  18079. $compile(element.contents())(scope);
  18080. }
  18081. );
  18082. };
  18083. });
  18084. })
  18085. .controller('GreeterController', ['$scope', function($scope) {
  18086. $scope.name = 'Angular';
  18087. $scope.html = 'Hello {{name}}';
  18088. }]);
  18089. </script>
  18090. <div ng-controller="GreeterController">
  18091. <input ng-model="name"> <br/>
  18092. <textarea ng-model="html"></textarea> <br/>
  18093. <div compile="html"></div>
  18094. </div>
  18095. </file>
  18096. <file name="protractor.js" type="protractor">
  18097. it('should auto compile', function() {
  18098. var textarea = $('textarea');
  18099. var output = $('div[compile]');
  18100. // The initial state reads 'Hello Angular'.
  18101. expect(output.getText()).toBe('Hello Angular');
  18102. textarea.clear();
  18103. textarea.sendKeys('{{name}}!');
  18104. expect(output.getText()).toBe('Angular!');
  18105. });
  18106. </file>
  18107. </example>
  18108. *
  18109. *
  18110. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  18111. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  18112. *
  18113. * <div class="alert alert-danger">
  18114. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  18115. * e.g. will not use the right outer scope. Please pass the transclude function as a
  18116. * `parentBoundTranscludeFn` to the link function instead.
  18117. * </div>
  18118. *
  18119. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  18120. * root element(s), not their children)
  18121. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  18122. * (a DOM element/tree) to a scope. Where:
  18123. *
  18124. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  18125. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  18126. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  18127. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  18128. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  18129. *
  18130. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  18131. * * `scope` - is the current scope with which the linking function is working with.
  18132. *
  18133. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  18134. * keys may be used to control linking behavior:
  18135. *
  18136. * * `parentBoundTranscludeFn` - the transclude function made available to
  18137. * directives; if given, it will be passed through to the link functions of
  18138. * directives found in `element` during compilation.
  18139. * * `transcludeControllers` - an object hash with keys that map controller names
  18140. * to a hash with the key `instance`, which maps to the controller instance;
  18141. * if given, it will make the controllers available to directives on the compileNode:
  18142. * ```
  18143. * {
  18144. * parent: {
  18145. * instance: parentControllerInstance
  18146. * }
  18147. * }
  18148. * ```
  18149. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  18150. * the cloned elements; only needed for transcludes that are allowed to contain non html
  18151. * elements (e.g. SVG elements). See also the directive.controller property.
  18152. *
  18153. * Calling the linking function returns the element of the template. It is either the original
  18154. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  18155. *
  18156. * After linking the view is not updated until after a call to $digest which typically is done by
  18157. * Angular automatically.
  18158. *
  18159. * If you need access to the bound view, there are two ways to do it:
  18160. *
  18161. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  18162. * before you send them to the compiler and keep this reference around.
  18163. * ```js
  18164. * var element = $compile('<p>{{total}}</p>')(scope);
  18165. * ```
  18166. *
  18167. * - if on the other hand, you need the element to be cloned, the view reference from the original
  18168. * example would not point to the clone, but rather to the original template that was cloned. In
  18169. * this case, you can access the clone via the cloneAttachFn:
  18170. * ```js
  18171. * var templateElement = angular.element('<p>{{total}}</p>'),
  18172. * scope = ....;
  18173. *
  18174. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  18175. * //attach the clone to DOM document at the right place
  18176. * });
  18177. *
  18178. * //now we have reference to the cloned DOM via `clonedElement`
  18179. * ```
  18180. *
  18181. *
  18182. * For information on how the compiler works, see the
  18183. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  18184. */
  18185. var $compileMinErr = minErr('$compile');
  18186. /**
  18187. * @ngdoc provider
  18188. * @name $compileProvider
  18189. *
  18190. * @description
  18191. */
  18192. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  18193. function $CompileProvider($provide, $$sanitizeUriProvider) {
  18194. var hasDirectives = {},
  18195. Suffix = 'Directive',
  18196. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  18197. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  18198. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  18199. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  18200. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  18201. // The assumption is that future DOM event attribute names will begin with
  18202. // 'on' and be composed of only English letters.
  18203. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  18204. var bindingCache = createMap();
  18205. function parseIsolateBindings(scope, directiveName, isController) {
  18206. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  18207. var bindings = {};
  18208. forEach(scope, function(definition, scopeName) {
  18209. if (definition in bindingCache) {
  18210. bindings[scopeName] = bindingCache[definition];
  18211. return;
  18212. }
  18213. var match = definition.match(LOCAL_REGEXP);
  18214. if (!match) {
  18215. throw $compileMinErr('iscp',
  18216. "Invalid {3} for directive '{0}'." +
  18217. " Definition: {... {1}: '{2}' ...}",
  18218. directiveName, scopeName, definition,
  18219. (isController ? "controller bindings definition" :
  18220. "isolate scope definition"));
  18221. }
  18222. bindings[scopeName] = {
  18223. mode: match[1][0],
  18224. collection: match[2] === '*',
  18225. optional: match[3] === '?',
  18226. attrName: match[4] || scopeName
  18227. };
  18228. if (match[4]) {
  18229. bindingCache[definition] = bindings[scopeName];
  18230. }
  18231. });
  18232. return bindings;
  18233. }
  18234. function parseDirectiveBindings(directive, directiveName) {
  18235. var bindings = {
  18236. isolateScope: null,
  18237. bindToController: null
  18238. };
  18239. if (isObject(directive.scope)) {
  18240. if (directive.bindToController === true) {
  18241. bindings.bindToController = parseIsolateBindings(directive.scope,
  18242. directiveName, true);
  18243. bindings.isolateScope = {};
  18244. } else {
  18245. bindings.isolateScope = parseIsolateBindings(directive.scope,
  18246. directiveName, false);
  18247. }
  18248. }
  18249. if (isObject(directive.bindToController)) {
  18250. bindings.bindToController =
  18251. parseIsolateBindings(directive.bindToController, directiveName, true);
  18252. }
  18253. if (isObject(bindings.bindToController)) {
  18254. var controller = directive.controller;
  18255. var controllerAs = directive.controllerAs;
  18256. if (!controller) {
  18257. // There is no controller, there may or may not be a controllerAs property
  18258. throw $compileMinErr('noctrl',
  18259. "Cannot bind to controller without directive '{0}'s controller.",
  18260. directiveName);
  18261. } else if (!identifierForController(controller, controllerAs)) {
  18262. // There is a controller, but no identifier or controllerAs property
  18263. throw $compileMinErr('noident',
  18264. "Cannot bind to controller without identifier for directive '{0}'.",
  18265. directiveName);
  18266. }
  18267. }
  18268. return bindings;
  18269. }
  18270. function assertValidDirectiveName(name) {
  18271. var letter = name.charAt(0);
  18272. if (!letter || letter !== lowercase(letter)) {
  18273. throw $compileMinErr('baddir', "Directive/Component name '{0}' is invalid. The first character must be a lowercase letter", name);
  18274. }
  18275. if (name !== name.trim()) {
  18276. throw $compileMinErr('baddir',
  18277. "Directive/Component name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  18278. name);
  18279. }
  18280. }
  18281. /**
  18282. * @ngdoc method
  18283. * @name $compileProvider#directive
  18284. * @kind function
  18285. *
  18286. * @description
  18287. * Register a new directive with the compiler.
  18288. *
  18289. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  18290. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  18291. * names and the values are the factories.
  18292. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  18293. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  18294. * @returns {ng.$compileProvider} Self for chaining.
  18295. */
  18296. this.directive = function registerDirective(name, directiveFactory) {
  18297. assertNotHasOwnProperty(name, 'directive');
  18298. if (isString(name)) {
  18299. assertValidDirectiveName(name);
  18300. assertArg(directiveFactory, 'directiveFactory');
  18301. if (!hasDirectives.hasOwnProperty(name)) {
  18302. hasDirectives[name] = [];
  18303. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  18304. function($injector, $exceptionHandler) {
  18305. var directives = [];
  18306. forEach(hasDirectives[name], function(directiveFactory, index) {
  18307. try {
  18308. var directive = $injector.invoke(directiveFactory);
  18309. if (isFunction(directive)) {
  18310. directive = { compile: valueFn(directive) };
  18311. } else if (!directive.compile && directive.link) {
  18312. directive.compile = valueFn(directive.link);
  18313. }
  18314. directive.priority = directive.priority || 0;
  18315. directive.index = index;
  18316. directive.name = directive.name || name;
  18317. directive.require = directive.require || (directive.controller && directive.name);
  18318. directive.restrict = directive.restrict || 'EA';
  18319. directive.$$moduleName = directiveFactory.$$moduleName;
  18320. directives.push(directive);
  18321. } catch (e) {
  18322. $exceptionHandler(e);
  18323. }
  18324. });
  18325. return directives;
  18326. }]);
  18327. }
  18328. hasDirectives[name].push(directiveFactory);
  18329. } else {
  18330. forEach(name, reverseParams(registerDirective));
  18331. }
  18332. return this;
  18333. };
  18334. /**
  18335. * @ngdoc method
  18336. * @name $compileProvider#component
  18337. * @module ng
  18338. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  18339. * @param {Object} options Component definition object (a simplified
  18340. * {@link ng.$compile#directive-definition-object directive definition object}),
  18341. * with the following properties (all optional):
  18342. *
  18343. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  18344. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  18345. * registered controller} if passed as a string. An empty `noop` function by default.
  18346. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  18347. * If present, the controller will be published to scope under the `controllerAs` name.
  18348. * If not present, this will default to be `$ctrl`.
  18349. * - `template` – `{string=|function()=}` – html template as a string or a function that
  18350. * returns an html template as a string which should be used as the contents of this component.
  18351. * Empty string by default.
  18352. *
  18353. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  18354. * the following locals:
  18355. *
  18356. * - `$element` - Current element
  18357. * - `$attrs` - Current attributes object for the element
  18358. *
  18359. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  18360. * template that should be used as the contents of this component.
  18361. *
  18362. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  18363. * the following locals:
  18364. *
  18365. * - `$element` - Current element
  18366. * - `$attrs` - Current attributes object for the element
  18367. *
  18368. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  18369. * Component properties are always bound to the component controller and not to the scope.
  18370. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  18371. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  18372. * Disabled by default.
  18373. * - `$...` – additional properties to attach to the directive factory function and the controller
  18374. * constructor function. (This is used by the component router to annotate)
  18375. *
  18376. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  18377. * @description
  18378. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  18379. * type of directive, which represents a self-contained UI component in your application. Such components
  18380. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  18381. *
  18382. * Component definitions are very simple and do not require as much configuration as defining general
  18383. * directives. Component definitions usually consist only of a template and a controller backing it.
  18384. *
  18385. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  18386. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  18387. *
  18388. * Here are a few examples of how you would usually define components:
  18389. *
  18390. * ```js
  18391. * var myMod = angular.module(...);
  18392. * myMod.component('myComp', {
  18393. * template: '<div>My name is {{$ctrl.name}}</div>',
  18394. * controller: function() {
  18395. * this.name = 'shahar';
  18396. * }
  18397. * });
  18398. *
  18399. * myMod.component('myComp', {
  18400. * template: '<div>My name is {{$ctrl.name}}</div>',
  18401. * bindings: {name: '@'}
  18402. * });
  18403. *
  18404. * myMod.component('myComp', {
  18405. * templateUrl: 'views/my-comp.html',
  18406. * controller: 'MyCtrl',
  18407. * controllerAs: 'ctrl',
  18408. * bindings: {name: '@'}
  18409. * });
  18410. *
  18411. * ```
  18412. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  18413. *
  18414. * <br />
  18415. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  18416. */
  18417. this.component = function registerComponent(name, options) {
  18418. var controller = options.controller || noop;
  18419. function factory($injector) {
  18420. function makeInjectable(fn) {
  18421. if (isFunction(fn) || isArray(fn)) {
  18422. return function(tElement, tAttrs) {
  18423. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  18424. };
  18425. } else {
  18426. return fn;
  18427. }
  18428. }
  18429. var template = (!options.template && !options.templateUrl ? '' : options.template);
  18430. return {
  18431. controller: controller,
  18432. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  18433. template: makeInjectable(template),
  18434. templateUrl: makeInjectable(options.templateUrl),
  18435. transclude: options.transclude,
  18436. scope: {},
  18437. bindToController: options.bindings || {},
  18438. restrict: 'E',
  18439. require: options.require
  18440. };
  18441. }
  18442. // Copy any annotation properties (starting with $) over to the factory function
  18443. // These could be used by libraries such as the new component router
  18444. forEach(options, function(val, key) {
  18445. if (key.charAt(0) === '$') {
  18446. factory[key] = val;
  18447. controller[key] = val;
  18448. }
  18449. });
  18450. factory.$inject = ['$injector'];
  18451. return this.directive(name, factory);
  18452. };
  18453. /**
  18454. * @ngdoc method
  18455. * @name $compileProvider#aHrefSanitizationWhitelist
  18456. * @kind function
  18457. *
  18458. * @description
  18459. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  18460. * urls during a[href] sanitization.
  18461. *
  18462. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  18463. *
  18464. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  18465. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  18466. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  18467. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  18468. *
  18469. * @param {RegExp=} regexp New regexp to whitelist urls with.
  18470. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18471. * chaining otherwise.
  18472. */
  18473. this.aHrefSanitizationWhitelist = function(regexp) {
  18474. if (isDefined(regexp)) {
  18475. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  18476. return this;
  18477. } else {
  18478. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  18479. }
  18480. };
  18481. /**
  18482. * @ngdoc method
  18483. * @name $compileProvider#imgSrcSanitizationWhitelist
  18484. * @kind function
  18485. *
  18486. * @description
  18487. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  18488. * urls during img[src] sanitization.
  18489. *
  18490. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  18491. *
  18492. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  18493. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  18494. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  18495. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  18496. *
  18497. * @param {RegExp=} regexp New regexp to whitelist urls with.
  18498. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18499. * chaining otherwise.
  18500. */
  18501. this.imgSrcSanitizationWhitelist = function(regexp) {
  18502. if (isDefined(regexp)) {
  18503. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  18504. return this;
  18505. } else {
  18506. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  18507. }
  18508. };
  18509. /**
  18510. * @ngdoc method
  18511. * @name $compileProvider#debugInfoEnabled
  18512. *
  18513. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  18514. * current debugInfoEnabled state
  18515. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  18516. *
  18517. * @kind function
  18518. *
  18519. * @description
  18520. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  18521. * binding information and a reference to the current scope on to DOM elements.
  18522. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  18523. * * `ng-binding` CSS class
  18524. * * `$binding` data property containing an array of the binding expressions
  18525. *
  18526. * You may want to disable this in production for a significant performance boost. See
  18527. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  18528. *
  18529. * The default value is true.
  18530. */
  18531. var debugInfoEnabled = true;
  18532. this.debugInfoEnabled = function(enabled) {
  18533. if (isDefined(enabled)) {
  18534. debugInfoEnabled = enabled;
  18535. return this;
  18536. }
  18537. return debugInfoEnabled;
  18538. };
  18539. var TTL = 10;
  18540. /**
  18541. * @ngdoc method
  18542. * @name $compileProvider#onChangesTtl
  18543. * @description
  18544. *
  18545. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  18546. * assuming that the model is unstable.
  18547. *
  18548. * The current default is 10 iterations.
  18549. *
  18550. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  18551. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  18552. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  18553. * the `$onChanges` hook execution.
  18554. *
  18555. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  18556. *
  18557. * @param {number} limit The number of `$onChanges` hook iterations.
  18558. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  18559. */
  18560. this.onChangesTtl = function(value) {
  18561. if (arguments.length) {
  18562. TTL = value;
  18563. return this;
  18564. }
  18565. return TTL;
  18566. };
  18567. this.$get = [
  18568. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  18569. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  18570. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  18571. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  18572. var SIMPLE_ATTR_NAME = /^\w/;
  18573. var specialAttrHolder = document.createElement('div');
  18574. var onChangesTtl = TTL;
  18575. // The onChanges hooks should all be run together in a single digest
  18576. // When changes occur, the call to trigger their hooks will be added to this queue
  18577. var onChangesQueue;
  18578. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  18579. function flushOnChangesQueue() {
  18580. try {
  18581. if (!(--onChangesTtl)) {
  18582. // We have hit the TTL limit so reset everything
  18583. onChangesQueue = undefined;
  18584. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  18585. }
  18586. // We must run this hook in an apply since the $$postDigest runs outside apply
  18587. $rootScope.$apply(function() {
  18588. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  18589. onChangesQueue[i]();
  18590. }
  18591. // Reset the queue to trigger a new schedule next time there is a change
  18592. onChangesQueue = undefined;
  18593. });
  18594. } finally {
  18595. onChangesTtl++;
  18596. }
  18597. }
  18598. function Attributes(element, attributesToCopy) {
  18599. if (attributesToCopy) {
  18600. var keys = Object.keys(attributesToCopy);
  18601. var i, l, key;
  18602. for (i = 0, l = keys.length; i < l; i++) {
  18603. key = keys[i];
  18604. this[key] = attributesToCopy[key];
  18605. }
  18606. } else {
  18607. this.$attr = {};
  18608. }
  18609. this.$$element = element;
  18610. }
  18611. Attributes.prototype = {
  18612. /**
  18613. * @ngdoc method
  18614. * @name $compile.directive.Attributes#$normalize
  18615. * @kind function
  18616. *
  18617. * @description
  18618. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  18619. * `data-`) to its normalized, camelCase form.
  18620. *
  18621. * Also there is special case for Moz prefix starting with upper case letter.
  18622. *
  18623. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  18624. *
  18625. * @param {string} name Name to normalize
  18626. */
  18627. $normalize: directiveNormalize,
  18628. /**
  18629. * @ngdoc method
  18630. * @name $compile.directive.Attributes#$addClass
  18631. * @kind function
  18632. *
  18633. * @description
  18634. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  18635. * are enabled then an animation will be triggered for the class addition.
  18636. *
  18637. * @param {string} classVal The className value that will be added to the element
  18638. */
  18639. $addClass: function(classVal) {
  18640. if (classVal && classVal.length > 0) {
  18641. $animate.addClass(this.$$element, classVal);
  18642. }
  18643. },
  18644. /**
  18645. * @ngdoc method
  18646. * @name $compile.directive.Attributes#$removeClass
  18647. * @kind function
  18648. *
  18649. * @description
  18650. * Removes the CSS class value specified by the classVal parameter from the element. If
  18651. * animations are enabled then an animation will be triggered for the class removal.
  18652. *
  18653. * @param {string} classVal The className value that will be removed from the element
  18654. */
  18655. $removeClass: function(classVal) {
  18656. if (classVal && classVal.length > 0) {
  18657. $animate.removeClass(this.$$element, classVal);
  18658. }
  18659. },
  18660. /**
  18661. * @ngdoc method
  18662. * @name $compile.directive.Attributes#$updateClass
  18663. * @kind function
  18664. *
  18665. * @description
  18666. * Adds and removes the appropriate CSS class values to the element based on the difference
  18667. * between the new and old CSS class values (specified as newClasses and oldClasses).
  18668. *
  18669. * @param {string} newClasses The current CSS className value
  18670. * @param {string} oldClasses The former CSS className value
  18671. */
  18672. $updateClass: function(newClasses, oldClasses) {
  18673. var toAdd = tokenDifference(newClasses, oldClasses);
  18674. if (toAdd && toAdd.length) {
  18675. $animate.addClass(this.$$element, toAdd);
  18676. }
  18677. var toRemove = tokenDifference(oldClasses, newClasses);
  18678. if (toRemove && toRemove.length) {
  18679. $animate.removeClass(this.$$element, toRemove);
  18680. }
  18681. },
  18682. /**
  18683. * Set a normalized attribute on the element in a way such that all directives
  18684. * can share the attribute. This function properly handles boolean attributes.
  18685. * @param {string} key Normalized key. (ie ngAttribute)
  18686. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  18687. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  18688. * Defaults to true.
  18689. * @param {string=} attrName Optional none normalized name. Defaults to key.
  18690. */
  18691. $set: function(key, value, writeAttr, attrName) {
  18692. // TODO: decide whether or not to throw an error if "class"
  18693. //is set through this function since it may cause $updateClass to
  18694. //become unstable.
  18695. var node = this.$$element[0],
  18696. booleanKey = getBooleanAttrName(node, key),
  18697. aliasedKey = getAliasedAttrName(key),
  18698. observer = key,
  18699. nodeName;
  18700. if (booleanKey) {
  18701. this.$$element.prop(key, value);
  18702. attrName = booleanKey;
  18703. } else if (aliasedKey) {
  18704. this[aliasedKey] = value;
  18705. observer = aliasedKey;
  18706. }
  18707. this[key] = value;
  18708. // translate normalized key to actual key
  18709. if (attrName) {
  18710. this.$attr[key] = attrName;
  18711. } else {
  18712. attrName = this.$attr[key];
  18713. if (!attrName) {
  18714. this.$attr[key] = attrName = snake_case(key, '-');
  18715. }
  18716. }
  18717. nodeName = nodeName_(this.$$element);
  18718. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  18719. (nodeName === 'img' && key === 'src')) {
  18720. // sanitize a[href] and img[src] values
  18721. this[key] = value = $$sanitizeUri(value, key === 'src');
  18722. } else if (nodeName === 'img' && key === 'srcset') {
  18723. // sanitize img[srcset] values
  18724. var result = "";
  18725. // first check if there are spaces because it's not the same pattern
  18726. var trimmedSrcset = trim(value);
  18727. // ( 999x ,| 999w ,| ,|, )
  18728. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  18729. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  18730. // split srcset into tuple of uri and descriptor except for the last item
  18731. var rawUris = trimmedSrcset.split(pattern);
  18732. // for each tuples
  18733. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  18734. for (var i = 0; i < nbrUrisWith2parts; i++) {
  18735. var innerIdx = i * 2;
  18736. // sanitize the uri
  18737. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  18738. // add the descriptor
  18739. result += (" " + trim(rawUris[innerIdx + 1]));
  18740. }
  18741. // split the last item into uri and descriptor
  18742. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  18743. // sanitize the last uri
  18744. result += $$sanitizeUri(trim(lastTuple[0]), true);
  18745. // and add the last descriptor if any
  18746. if (lastTuple.length === 2) {
  18747. result += (" " + trim(lastTuple[1]));
  18748. }
  18749. this[key] = value = result;
  18750. }
  18751. if (writeAttr !== false) {
  18752. if (value === null || isUndefined(value)) {
  18753. this.$$element.removeAttr(attrName);
  18754. } else {
  18755. if (SIMPLE_ATTR_NAME.test(attrName)) {
  18756. this.$$element.attr(attrName, value);
  18757. } else {
  18758. setSpecialAttr(this.$$element[0], attrName, value);
  18759. }
  18760. }
  18761. }
  18762. // fire observers
  18763. var $$observers = this.$$observers;
  18764. $$observers && forEach($$observers[observer], function(fn) {
  18765. try {
  18766. fn(value);
  18767. } catch (e) {
  18768. $exceptionHandler(e);
  18769. }
  18770. });
  18771. },
  18772. /**
  18773. * @ngdoc method
  18774. * @name $compile.directive.Attributes#$observe
  18775. * @kind function
  18776. *
  18777. * @description
  18778. * Observes an interpolated attribute.
  18779. *
  18780. * The observer function will be invoked once during the next `$digest` following
  18781. * compilation. The observer is then invoked whenever the interpolated value
  18782. * changes.
  18783. *
  18784. * @param {string} key Normalized key. (ie ngAttribute) .
  18785. * @param {function(interpolatedValue)} fn Function that will be called whenever
  18786. the interpolated value of the attribute changes.
  18787. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  18788. * guide} for more info.
  18789. * @returns {function()} Returns a deregistration function for this observer.
  18790. */
  18791. $observe: function(key, fn) {
  18792. var attrs = this,
  18793. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  18794. listeners = ($$observers[key] || ($$observers[key] = []));
  18795. listeners.push(fn);
  18796. $rootScope.$evalAsync(function() {
  18797. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  18798. // no one registered attribute interpolation function, so lets call it manually
  18799. fn(attrs[key]);
  18800. }
  18801. });
  18802. return function() {
  18803. arrayRemove(listeners, fn);
  18804. };
  18805. }
  18806. };
  18807. function setSpecialAttr(element, attrName, value) {
  18808. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  18809. // so we have to jump through some hoops to get such an attribute
  18810. // https://github.com/angular/angular.js/pull/13318
  18811. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  18812. var attributes = specialAttrHolder.firstChild.attributes;
  18813. var attribute = attributes[0];
  18814. // We have to remove the attribute from its container element before we can add it to the destination element
  18815. attributes.removeNamedItem(attribute.name);
  18816. attribute.value = value;
  18817. element.attributes.setNamedItem(attribute);
  18818. }
  18819. function safeAddClass($element, className) {
  18820. try {
  18821. $element.addClass(className);
  18822. } catch (e) {
  18823. // ignore, since it means that we are trying to set class on
  18824. // SVG element, where class name is read-only.
  18825. }
  18826. }
  18827. var startSymbol = $interpolate.startSymbol(),
  18828. endSymbol = $interpolate.endSymbol(),
  18829. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  18830. ? identity
  18831. : function denormalizeTemplate(template) {
  18832. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  18833. },
  18834. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  18835. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  18836. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  18837. var bindings = $element.data('$binding') || [];
  18838. if (isArray(binding)) {
  18839. bindings = bindings.concat(binding);
  18840. } else {
  18841. bindings.push(binding);
  18842. }
  18843. $element.data('$binding', bindings);
  18844. } : noop;
  18845. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  18846. safeAddClass($element, 'ng-binding');
  18847. } : noop;
  18848. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  18849. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  18850. $element.data(dataName, scope);
  18851. } : noop;
  18852. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  18853. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  18854. } : noop;
  18855. compile.$$createComment = function(directiveName, comment) {
  18856. var content = '';
  18857. if (debugInfoEnabled) {
  18858. content = ' ' + (directiveName || '') + ': ' + (comment || '') + ' ';
  18859. }
  18860. return document.createComment(content);
  18861. };
  18862. return compile;
  18863. //================================
  18864. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  18865. previousCompileContext) {
  18866. if (!($compileNodes instanceof jqLite)) {
  18867. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  18868. // modify it.
  18869. $compileNodes = jqLite($compileNodes);
  18870. }
  18871. var NOT_EMPTY = /\S+/;
  18872. // We can not compile top level text elements since text nodes can be merged and we will
  18873. // not be able to attach scope data to them, so we will wrap them in <span>
  18874. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  18875. var domNode = $compileNodes[i];
  18876. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  18877. jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
  18878. }
  18879. }
  18880. var compositeLinkFn =
  18881. compileNodes($compileNodes, transcludeFn, $compileNodes,
  18882. maxPriority, ignoreDirective, previousCompileContext);
  18883. compile.$$addScopeClass($compileNodes);
  18884. var namespace = null;
  18885. return function publicLinkFn(scope, cloneConnectFn, options) {
  18886. assertArg(scope, 'scope');
  18887. if (previousCompileContext && previousCompileContext.needsNewScope) {
  18888. // A parent directive did a replace and a directive on this element asked
  18889. // for transclusion, which caused us to lose a layer of element on which
  18890. // we could hold the new transclusion scope, so we will create it manually
  18891. // here.
  18892. scope = scope.$parent.$new();
  18893. }
  18894. options = options || {};
  18895. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  18896. transcludeControllers = options.transcludeControllers,
  18897. futureParentElement = options.futureParentElement;
  18898. // When `parentBoundTranscludeFn` is passed, it is a
  18899. // `controllersBoundTransclude` function (it was previously passed
  18900. // as `transclude` to directive.link) so we must unwrap it to get
  18901. // its `boundTranscludeFn`
  18902. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  18903. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  18904. }
  18905. if (!namespace) {
  18906. namespace = detectNamespaceForChildElements(futureParentElement);
  18907. }
  18908. var $linkNode;
  18909. if (namespace !== 'html') {
  18910. // When using a directive with replace:true and templateUrl the $compileNodes
  18911. // (or a child element inside of them)
  18912. // might change, so we need to recreate the namespace adapted compileNodes
  18913. // for call to the link function.
  18914. // Note: This will already clone the nodes...
  18915. $linkNode = jqLite(
  18916. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  18917. );
  18918. } else if (cloneConnectFn) {
  18919. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  18920. // and sometimes changes the structure of the DOM.
  18921. $linkNode = JQLitePrototype.clone.call($compileNodes);
  18922. } else {
  18923. $linkNode = $compileNodes;
  18924. }
  18925. if (transcludeControllers) {
  18926. for (var controllerName in transcludeControllers) {
  18927. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  18928. }
  18929. }
  18930. compile.$$addScopeInfo($linkNode, scope);
  18931. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  18932. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  18933. return $linkNode;
  18934. };
  18935. }
  18936. function detectNamespaceForChildElements(parentElement) {
  18937. // TODO: Make this detect MathML as well...
  18938. var node = parentElement && parentElement[0];
  18939. if (!node) {
  18940. return 'html';
  18941. } else {
  18942. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  18943. }
  18944. }
  18945. /**
  18946. * Compile function matches each node in nodeList against the directives. Once all directives
  18947. * for a particular node are collected their compile functions are executed. The compile
  18948. * functions return values - the linking functions - are combined into a composite linking
  18949. * function, which is the a linking function for the node.
  18950. *
  18951. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  18952. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  18953. * scope argument is auto-generated to the new child of the transcluded parent scope.
  18954. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  18955. * the rootElement must be set the jqLite collection of the compile root. This is
  18956. * needed so that the jqLite collection items can be replaced with widgets.
  18957. * @param {number=} maxPriority Max directive priority.
  18958. * @returns {Function} A composite linking function of all of the matched directives or null.
  18959. */
  18960. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  18961. previousCompileContext) {
  18962. var linkFns = [],
  18963. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  18964. for (var i = 0; i < nodeList.length; i++) {
  18965. attrs = new Attributes();
  18966. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  18967. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  18968. ignoreDirective);
  18969. nodeLinkFn = (directives.length)
  18970. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  18971. null, [], [], previousCompileContext)
  18972. : null;
  18973. if (nodeLinkFn && nodeLinkFn.scope) {
  18974. compile.$$addScopeClass(attrs.$$element);
  18975. }
  18976. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  18977. !(childNodes = nodeList[i].childNodes) ||
  18978. !childNodes.length)
  18979. ? null
  18980. : compileNodes(childNodes,
  18981. nodeLinkFn ? (
  18982. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  18983. && nodeLinkFn.transclude) : transcludeFn);
  18984. if (nodeLinkFn || childLinkFn) {
  18985. linkFns.push(i, nodeLinkFn, childLinkFn);
  18986. linkFnFound = true;
  18987. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  18988. }
  18989. //use the previous context only for the first element in the virtual group
  18990. previousCompileContext = null;
  18991. }
  18992. // return a linking function if we have found anything, null otherwise
  18993. return linkFnFound ? compositeLinkFn : null;
  18994. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  18995. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  18996. var stableNodeList;
  18997. if (nodeLinkFnFound) {
  18998. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  18999. // offsets don't get screwed up
  19000. var nodeListLength = nodeList.length;
  19001. stableNodeList = new Array(nodeListLength);
  19002. // create a sparse array by only copying the elements which have a linkFn
  19003. for (i = 0; i < linkFns.length; i+=3) {
  19004. idx = linkFns[i];
  19005. stableNodeList[idx] = nodeList[idx];
  19006. }
  19007. } else {
  19008. stableNodeList = nodeList;
  19009. }
  19010. for (i = 0, ii = linkFns.length; i < ii;) {
  19011. node = stableNodeList[linkFns[i++]];
  19012. nodeLinkFn = linkFns[i++];
  19013. childLinkFn = linkFns[i++];
  19014. if (nodeLinkFn) {
  19015. if (nodeLinkFn.scope) {
  19016. childScope = scope.$new();
  19017. compile.$$addScopeInfo(jqLite(node), childScope);
  19018. } else {
  19019. childScope = scope;
  19020. }
  19021. if (nodeLinkFn.transcludeOnThisElement) {
  19022. childBoundTranscludeFn = createBoundTranscludeFn(
  19023. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  19024. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  19025. childBoundTranscludeFn = parentBoundTranscludeFn;
  19026. } else if (!parentBoundTranscludeFn && transcludeFn) {
  19027. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  19028. } else {
  19029. childBoundTranscludeFn = null;
  19030. }
  19031. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  19032. } else if (childLinkFn) {
  19033. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  19034. }
  19035. }
  19036. }
  19037. }
  19038. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  19039. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  19040. if (!transcludedScope) {
  19041. transcludedScope = scope.$new(false, containingScope);
  19042. transcludedScope.$$transcluded = true;
  19043. }
  19044. return transcludeFn(transcludedScope, cloneFn, {
  19045. parentBoundTranscludeFn: previousBoundTranscludeFn,
  19046. transcludeControllers: controllers,
  19047. futureParentElement: futureParentElement
  19048. });
  19049. }
  19050. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  19051. // so that they are available inside the `controllersBoundTransclude` function
  19052. var boundSlots = boundTranscludeFn.$$slots = createMap();
  19053. for (var slotName in transcludeFn.$$slots) {
  19054. if (transcludeFn.$$slots[slotName]) {
  19055. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  19056. } else {
  19057. boundSlots[slotName] = null;
  19058. }
  19059. }
  19060. return boundTranscludeFn;
  19061. }
  19062. /**
  19063. * Looks for directives on the given node and adds them to the directive collection which is
  19064. * sorted.
  19065. *
  19066. * @param node Node to search.
  19067. * @param directives An array to which the directives are added to. This array is sorted before
  19068. * the function returns.
  19069. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  19070. * @param {number=} maxPriority Max directive priority.
  19071. */
  19072. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  19073. var nodeType = node.nodeType,
  19074. attrsMap = attrs.$attr,
  19075. match,
  19076. className;
  19077. switch (nodeType) {
  19078. case NODE_TYPE_ELEMENT: /* Element */
  19079. // use the node name: <directive>
  19080. addDirective(directives,
  19081. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  19082. // iterate over the attributes
  19083. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  19084. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  19085. var attrStartName = false;
  19086. var attrEndName = false;
  19087. attr = nAttrs[j];
  19088. name = attr.name;
  19089. value = trim(attr.value);
  19090. // support ngAttr attribute binding
  19091. ngAttrName = directiveNormalize(name);
  19092. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  19093. name = name.replace(PREFIX_REGEXP, '')
  19094. .substr(8).replace(/_(.)/g, function(match, letter) {
  19095. return letter.toUpperCase();
  19096. });
  19097. }
  19098. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  19099. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  19100. attrStartName = name;
  19101. attrEndName = name.substr(0, name.length - 5) + 'end';
  19102. name = name.substr(0, name.length - 6);
  19103. }
  19104. nName = directiveNormalize(name.toLowerCase());
  19105. attrsMap[nName] = name;
  19106. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  19107. attrs[nName] = value;
  19108. if (getBooleanAttrName(node, nName)) {
  19109. attrs[nName] = true; // presence means true
  19110. }
  19111. }
  19112. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  19113. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  19114. attrEndName);
  19115. }
  19116. // use class as directive
  19117. className = node.className;
  19118. if (isObject(className)) {
  19119. // Maybe SVGAnimatedString
  19120. className = className.animVal;
  19121. }
  19122. if (isString(className) && className !== '') {
  19123. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  19124. nName = directiveNormalize(match[2]);
  19125. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  19126. attrs[nName] = trim(match[3]);
  19127. }
  19128. className = className.substr(match.index + match[0].length);
  19129. }
  19130. }
  19131. break;
  19132. case NODE_TYPE_TEXT: /* Text Node */
  19133. if (msie === 11) {
  19134. // Workaround for #11781
  19135. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  19136. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  19137. node.parentNode.removeChild(node.nextSibling);
  19138. }
  19139. }
  19140. addTextInterpolateDirective(directives, node.nodeValue);
  19141. break;
  19142. case NODE_TYPE_COMMENT: /* Comment */
  19143. try {
  19144. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  19145. if (match) {
  19146. nName = directiveNormalize(match[1]);
  19147. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  19148. attrs[nName] = trim(match[2]);
  19149. }
  19150. }
  19151. } catch (e) {
  19152. // turns out that under some circumstances IE9 throws errors when one attempts to read
  19153. // comment's node value.
  19154. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  19155. }
  19156. break;
  19157. }
  19158. directives.sort(byPriority);
  19159. return directives;
  19160. }
  19161. /**
  19162. * Given a node with an directive-start it collects all of the siblings until it finds
  19163. * directive-end.
  19164. * @param node
  19165. * @param attrStart
  19166. * @param attrEnd
  19167. * @returns {*}
  19168. */
  19169. function groupScan(node, attrStart, attrEnd) {
  19170. var nodes = [];
  19171. var depth = 0;
  19172. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  19173. do {
  19174. if (!node) {
  19175. throw $compileMinErr('uterdir',
  19176. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  19177. attrStart, attrEnd);
  19178. }
  19179. if (node.nodeType == NODE_TYPE_ELEMENT) {
  19180. if (node.hasAttribute(attrStart)) depth++;
  19181. if (node.hasAttribute(attrEnd)) depth--;
  19182. }
  19183. nodes.push(node);
  19184. node = node.nextSibling;
  19185. } while (depth > 0);
  19186. } else {
  19187. nodes.push(node);
  19188. }
  19189. return jqLite(nodes);
  19190. }
  19191. /**
  19192. * Wrapper for linking function which converts normal linking function into a grouped
  19193. * linking function.
  19194. * @param linkFn
  19195. * @param attrStart
  19196. * @param attrEnd
  19197. * @returns {Function}
  19198. */
  19199. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  19200. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  19201. element = groupScan(element[0], attrStart, attrEnd);
  19202. return linkFn(scope, element, attrs, controllers, transcludeFn);
  19203. };
  19204. }
  19205. /**
  19206. * A function generator that is used to support both eager and lazy compilation
  19207. * linking function.
  19208. * @param eager
  19209. * @param $compileNodes
  19210. * @param transcludeFn
  19211. * @param maxPriority
  19212. * @param ignoreDirective
  19213. * @param previousCompileContext
  19214. * @returns {Function}
  19215. */
  19216. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  19217. var compiled;
  19218. if (eager) {
  19219. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  19220. }
  19221. return function lazyCompilation() {
  19222. if (!compiled) {
  19223. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  19224. // Null out all of these references in order to make them eligible for garbage collection
  19225. // since this is a potentially long lived closure
  19226. $compileNodes = transcludeFn = previousCompileContext = null;
  19227. }
  19228. return compiled.apply(this, arguments);
  19229. };
  19230. }
  19231. /**
  19232. * Once the directives have been collected, their compile functions are executed. This method
  19233. * is responsible for inlining directive templates as well as terminating the application
  19234. * of the directives if the terminal directive has been reached.
  19235. *
  19236. * @param {Array} directives Array of collected directives to execute their compile function.
  19237. * this needs to be pre-sorted by priority order.
  19238. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  19239. * @param {Object} templateAttrs The shared attribute function
  19240. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  19241. * scope argument is auto-generated to the new
  19242. * child of the transcluded parent scope.
  19243. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  19244. * argument has the root jqLite array so that we can replace nodes
  19245. * on it.
  19246. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  19247. * compiling the transclusion.
  19248. * @param {Array.<Function>} preLinkFns
  19249. * @param {Array.<Function>} postLinkFns
  19250. * @param {Object} previousCompileContext Context used for previous compilation of the current
  19251. * node
  19252. * @returns {Function} linkFn
  19253. */
  19254. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  19255. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  19256. previousCompileContext) {
  19257. previousCompileContext = previousCompileContext || {};
  19258. var terminalPriority = -Number.MAX_VALUE,
  19259. newScopeDirective = previousCompileContext.newScopeDirective,
  19260. controllerDirectives = previousCompileContext.controllerDirectives,
  19261. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  19262. templateDirective = previousCompileContext.templateDirective,
  19263. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  19264. hasTranscludeDirective = false,
  19265. hasTemplate = false,
  19266. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  19267. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  19268. directive,
  19269. directiveName,
  19270. $template,
  19271. replaceDirective = originalReplaceDirective,
  19272. childTranscludeFn = transcludeFn,
  19273. linkFn,
  19274. didScanForMultipleTransclusion = false,
  19275. mightHaveMultipleTransclusionError = false,
  19276. directiveValue;
  19277. // executes all directives on the current element
  19278. for (var i = 0, ii = directives.length; i < ii; i++) {
  19279. directive = directives[i];
  19280. var attrStart = directive.$$start;
  19281. var attrEnd = directive.$$end;
  19282. // collect multiblock sections
  19283. if (attrStart) {
  19284. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  19285. }
  19286. $template = undefined;
  19287. if (terminalPriority > directive.priority) {
  19288. break; // prevent further processing of directives
  19289. }
  19290. if (directiveValue = directive.scope) {
  19291. // skip the check for directives with async templates, we'll check the derived sync
  19292. // directive when the template arrives
  19293. if (!directive.templateUrl) {
  19294. if (isObject(directiveValue)) {
  19295. // This directive is trying to add an isolated scope.
  19296. // Check that there is no scope of any kind already
  19297. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  19298. directive, $compileNode);
  19299. newIsolateScopeDirective = directive;
  19300. } else {
  19301. // This directive is trying to add a child scope.
  19302. // Check that there is no isolated scope already
  19303. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  19304. $compileNode);
  19305. }
  19306. }
  19307. newScopeDirective = newScopeDirective || directive;
  19308. }
  19309. directiveName = directive.name;
  19310. // If we encounter a condition that can result in transclusion on the directive,
  19311. // then scan ahead in the remaining directives for others that may cause a multiple
  19312. // transclusion error to be thrown during the compilation process. If a matching directive
  19313. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  19314. // compile the `transclude` function rather than doing it lazily in order to throw
  19315. // exceptions at the correct time
  19316. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  19317. || (directive.transclude && !directive.$$tlb))) {
  19318. var candidateDirective;
  19319. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  19320. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  19321. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  19322. mightHaveMultipleTransclusionError = true;
  19323. break;
  19324. }
  19325. }
  19326. didScanForMultipleTransclusion = true;
  19327. }
  19328. if (!directive.templateUrl && directive.controller) {
  19329. directiveValue = directive.controller;
  19330. controllerDirectives = controllerDirectives || createMap();
  19331. assertNoDuplicate("'" + directiveName + "' controller",
  19332. controllerDirectives[directiveName], directive, $compileNode);
  19333. controllerDirectives[directiveName] = directive;
  19334. }
  19335. if (directiveValue = directive.transclude) {
  19336. hasTranscludeDirective = true;
  19337. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  19338. // This option should only be used by directives that know how to safely handle element transclusion,
  19339. // where the transcluded nodes are added or replaced after linking.
  19340. if (!directive.$$tlb) {
  19341. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  19342. nonTlbTranscludeDirective = directive;
  19343. }
  19344. if (directiveValue == 'element') {
  19345. hasElementTranscludeDirective = true;
  19346. terminalPriority = directive.priority;
  19347. $template = $compileNode;
  19348. $compileNode = templateAttrs.$$element =
  19349. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  19350. compileNode = $compileNode[0];
  19351. replaceWith(jqCollection, sliceArgs($template), compileNode);
  19352. // Support: Chrome < 50
  19353. // https://github.com/angular/angular.js/issues/14041
  19354. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  19355. // in the `replaceWith` function is improperly garbage collected despite still
  19356. // being referenced by the `parentNode` property of all of the child nodes. By adding
  19357. // a reference to the fragment via a different property, we can avoid that incorrect
  19358. // behavior.
  19359. // TODO: remove this line after Chrome 50 has been released
  19360. $template[0].$$parentNode = $template[0].parentNode;
  19361. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  19362. replaceDirective && replaceDirective.name, {
  19363. // Don't pass in:
  19364. // - controllerDirectives - otherwise we'll create duplicates controllers
  19365. // - newIsolateScopeDirective or templateDirective - combining templates with
  19366. // element transclusion doesn't make sense.
  19367. //
  19368. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  19369. // on the same element more than once.
  19370. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  19371. });
  19372. } else {
  19373. var slots = createMap();
  19374. $template = jqLite(jqLiteClone(compileNode)).contents();
  19375. if (isObject(directiveValue)) {
  19376. // We have transclusion slots,
  19377. // collect them up, compile them and store their transclusion functions
  19378. $template = [];
  19379. var slotMap = createMap();
  19380. var filledSlots = createMap();
  19381. // Parse the element selectors
  19382. forEach(directiveValue, function(elementSelector, slotName) {
  19383. // If an element selector starts with a ? then it is optional
  19384. var optional = (elementSelector.charAt(0) === '?');
  19385. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  19386. slotMap[elementSelector] = slotName;
  19387. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  19388. // Later when calling boundTransclusion functions with a slot name we only error if the
  19389. // slot is `undefined`
  19390. slots[slotName] = null;
  19391. // filledSlots contains `true` for all slots that are either optional or have been
  19392. // filled. This is used to check that we have not missed any required slots
  19393. filledSlots[slotName] = optional;
  19394. });
  19395. // Add the matching elements into their slot
  19396. forEach($compileNode.contents(), function(node) {
  19397. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  19398. if (slotName) {
  19399. filledSlots[slotName] = true;
  19400. slots[slotName] = slots[slotName] || [];
  19401. slots[slotName].push(node);
  19402. } else {
  19403. $template.push(node);
  19404. }
  19405. });
  19406. // Check for required slots that were not filled
  19407. forEach(filledSlots, function(filled, slotName) {
  19408. if (!filled) {
  19409. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  19410. }
  19411. });
  19412. for (var slotName in slots) {
  19413. if (slots[slotName]) {
  19414. // Only define a transclusion function if the slot was filled
  19415. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  19416. }
  19417. }
  19418. }
  19419. $compileNode.empty(); // clear contents
  19420. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  19421. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  19422. childTranscludeFn.$$slots = slots;
  19423. }
  19424. }
  19425. if (directive.template) {
  19426. hasTemplate = true;
  19427. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  19428. templateDirective = directive;
  19429. directiveValue = (isFunction(directive.template))
  19430. ? directive.template($compileNode, templateAttrs)
  19431. : directive.template;
  19432. directiveValue = denormalizeTemplate(directiveValue);
  19433. if (directive.replace) {
  19434. replaceDirective = directive;
  19435. if (jqLiteIsTextNode(directiveValue)) {
  19436. $template = [];
  19437. } else {
  19438. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  19439. }
  19440. compileNode = $template[0];
  19441. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  19442. throw $compileMinErr('tplrt',
  19443. "Template for directive '{0}' must have exactly one root element. {1}",
  19444. directiveName, '');
  19445. }
  19446. replaceWith(jqCollection, $compileNode, compileNode);
  19447. var newTemplateAttrs = {$attr: {}};
  19448. // combine directives from the original node and from the template:
  19449. // - take the array of directives for this element
  19450. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  19451. // - collect directives from the template and sort them by priority
  19452. // - combine directives as: processed + template + unprocessed
  19453. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  19454. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  19455. if (newIsolateScopeDirective || newScopeDirective) {
  19456. // The original directive caused the current element to be replaced but this element
  19457. // also needs to have a new scope, so we need to tell the template directives
  19458. // that they would need to get their scope from further up, if they require transclusion
  19459. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  19460. }
  19461. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  19462. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  19463. ii = directives.length;
  19464. } else {
  19465. $compileNode.html(directiveValue);
  19466. }
  19467. }
  19468. if (directive.templateUrl) {
  19469. hasTemplate = true;
  19470. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  19471. templateDirective = directive;
  19472. if (directive.replace) {
  19473. replaceDirective = directive;
  19474. }
  19475. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  19476. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  19477. controllerDirectives: controllerDirectives,
  19478. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  19479. newIsolateScopeDirective: newIsolateScopeDirective,
  19480. templateDirective: templateDirective,
  19481. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  19482. });
  19483. ii = directives.length;
  19484. } else if (directive.compile) {
  19485. try {
  19486. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  19487. if (isFunction(linkFn)) {
  19488. addLinkFns(null, linkFn, attrStart, attrEnd);
  19489. } else if (linkFn) {
  19490. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  19491. }
  19492. } catch (e) {
  19493. $exceptionHandler(e, startingTag($compileNode));
  19494. }
  19495. }
  19496. if (directive.terminal) {
  19497. nodeLinkFn.terminal = true;
  19498. terminalPriority = Math.max(terminalPriority, directive.priority);
  19499. }
  19500. }
  19501. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  19502. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  19503. nodeLinkFn.templateOnThisElement = hasTemplate;
  19504. nodeLinkFn.transclude = childTranscludeFn;
  19505. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  19506. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  19507. return nodeLinkFn;
  19508. ////////////////////
  19509. function addLinkFns(pre, post, attrStart, attrEnd) {
  19510. if (pre) {
  19511. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  19512. pre.require = directive.require;
  19513. pre.directiveName = directiveName;
  19514. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  19515. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  19516. }
  19517. preLinkFns.push(pre);
  19518. }
  19519. if (post) {
  19520. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  19521. post.require = directive.require;
  19522. post.directiveName = directiveName;
  19523. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  19524. post = cloneAndAnnotateFn(post, {isolateScope: true});
  19525. }
  19526. postLinkFns.push(post);
  19527. }
  19528. }
  19529. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  19530. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  19531. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  19532. if (compileNode === linkNode) {
  19533. attrs = templateAttrs;
  19534. $element = templateAttrs.$$element;
  19535. } else {
  19536. $element = jqLite(linkNode);
  19537. attrs = new Attributes($element, templateAttrs);
  19538. }
  19539. controllerScope = scope;
  19540. if (newIsolateScopeDirective) {
  19541. isolateScope = scope.$new(true);
  19542. } else if (newScopeDirective) {
  19543. controllerScope = scope.$parent;
  19544. }
  19545. if (boundTranscludeFn) {
  19546. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  19547. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  19548. transcludeFn = controllersBoundTransclude;
  19549. transcludeFn.$$boundTransclude = boundTranscludeFn;
  19550. // expose the slots on the `$transclude` function
  19551. transcludeFn.isSlotFilled = function(slotName) {
  19552. return !!boundTranscludeFn.$$slots[slotName];
  19553. };
  19554. }
  19555. if (controllerDirectives) {
  19556. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  19557. }
  19558. if (newIsolateScopeDirective) {
  19559. // Initialize isolate scope bindings for new isolate scope directive.
  19560. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  19561. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  19562. compile.$$addScopeClass($element, true);
  19563. isolateScope.$$isolateBindings =
  19564. newIsolateScopeDirective.$$isolateBindings;
  19565. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  19566. isolateScope.$$isolateBindings,
  19567. newIsolateScopeDirective);
  19568. if (removeScopeBindingWatches) {
  19569. isolateScope.$on('$destroy', removeScopeBindingWatches);
  19570. }
  19571. }
  19572. // Initialize bindToController bindings
  19573. for (var name in elementControllers) {
  19574. var controllerDirective = controllerDirectives[name];
  19575. var controller = elementControllers[name];
  19576. var bindings = controllerDirective.$$bindings.bindToController;
  19577. if (controller.identifier && bindings) {
  19578. removeControllerBindingWatches =
  19579. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  19580. }
  19581. var controllerResult = controller();
  19582. if (controllerResult !== controller.instance) {
  19583. // If the controller constructor has a return value, overwrite the instance
  19584. // from setupControllers
  19585. controller.instance = controllerResult;
  19586. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  19587. removeControllerBindingWatches && removeControllerBindingWatches();
  19588. removeControllerBindingWatches =
  19589. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  19590. }
  19591. }
  19592. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  19593. forEach(controllerDirectives, function(controllerDirective, name) {
  19594. var require = controllerDirective.require;
  19595. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  19596. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  19597. }
  19598. });
  19599. // Handle the init and destroy lifecycle hooks on all controllers that have them
  19600. forEach(elementControllers, function(controller) {
  19601. var controllerInstance = controller.instance;
  19602. if (isFunction(controllerInstance.$onInit)) {
  19603. controllerInstance.$onInit();
  19604. }
  19605. if (isFunction(controllerInstance.$onDestroy)) {
  19606. controllerScope.$on('$destroy', function callOnDestroyHook() {
  19607. controllerInstance.$onDestroy();
  19608. });
  19609. }
  19610. });
  19611. // PRELINKING
  19612. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  19613. linkFn = preLinkFns[i];
  19614. invokeLinkFn(linkFn,
  19615. linkFn.isolateScope ? isolateScope : scope,
  19616. $element,
  19617. attrs,
  19618. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  19619. transcludeFn
  19620. );
  19621. }
  19622. // RECURSION
  19623. // We only pass the isolate scope, if the isolate directive has a template,
  19624. // otherwise the child elements do not belong to the isolate directive.
  19625. var scopeToChild = scope;
  19626. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  19627. scopeToChild = isolateScope;
  19628. }
  19629. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  19630. // POSTLINKING
  19631. for (i = postLinkFns.length - 1; i >= 0; i--) {
  19632. linkFn = postLinkFns[i];
  19633. invokeLinkFn(linkFn,
  19634. linkFn.isolateScope ? isolateScope : scope,
  19635. $element,
  19636. attrs,
  19637. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  19638. transcludeFn
  19639. );
  19640. }
  19641. // Trigger $postLink lifecycle hooks
  19642. forEach(elementControllers, function(controller) {
  19643. var controllerInstance = controller.instance;
  19644. if (isFunction(controllerInstance.$postLink)) {
  19645. controllerInstance.$postLink();
  19646. }
  19647. });
  19648. // This is the function that is injected as `$transclude`.
  19649. // Note: all arguments are optional!
  19650. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  19651. var transcludeControllers;
  19652. // No scope passed in:
  19653. if (!isScope(scope)) {
  19654. slotName = futureParentElement;
  19655. futureParentElement = cloneAttachFn;
  19656. cloneAttachFn = scope;
  19657. scope = undefined;
  19658. }
  19659. if (hasElementTranscludeDirective) {
  19660. transcludeControllers = elementControllers;
  19661. }
  19662. if (!futureParentElement) {
  19663. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  19664. }
  19665. if (slotName) {
  19666. // slotTranscludeFn can be one of three things:
  19667. // * a transclude function - a filled slot
  19668. // * `null` - an optional slot that was not filled
  19669. // * `undefined` - a slot that was not declared (i.e. invalid)
  19670. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  19671. if (slotTranscludeFn) {
  19672. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  19673. } else if (isUndefined(slotTranscludeFn)) {
  19674. throw $compileMinErr('noslot',
  19675. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  19676. 'Element: {1}',
  19677. slotName, startingTag($element));
  19678. }
  19679. } else {
  19680. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  19681. }
  19682. }
  19683. }
  19684. }
  19685. function getControllers(directiveName, require, $element, elementControllers) {
  19686. var value;
  19687. if (isString(require)) {
  19688. var match = require.match(REQUIRE_PREFIX_REGEXP);
  19689. var name = require.substring(match[0].length);
  19690. var inheritType = match[1] || match[3];
  19691. var optional = match[2] === '?';
  19692. //If only parents then start at the parent element
  19693. if (inheritType === '^^') {
  19694. $element = $element.parent();
  19695. //Otherwise attempt getting the controller from elementControllers in case
  19696. //the element is transcluded (and has no data) and to avoid .data if possible
  19697. } else {
  19698. value = elementControllers && elementControllers[name];
  19699. value = value && value.instance;
  19700. }
  19701. if (!value) {
  19702. var dataName = '$' + name + 'Controller';
  19703. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  19704. }
  19705. if (!value && !optional) {
  19706. throw $compileMinErr('ctreq',
  19707. "Controller '{0}', required by directive '{1}', can't be found!",
  19708. name, directiveName);
  19709. }
  19710. } else if (isArray(require)) {
  19711. value = [];
  19712. for (var i = 0, ii = require.length; i < ii; i++) {
  19713. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  19714. }
  19715. } else if (isObject(require)) {
  19716. value = {};
  19717. forEach(require, function(controller, property) {
  19718. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  19719. });
  19720. }
  19721. return value || null;
  19722. }
  19723. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  19724. var elementControllers = createMap();
  19725. for (var controllerKey in controllerDirectives) {
  19726. var directive = controllerDirectives[controllerKey];
  19727. var locals = {
  19728. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  19729. $element: $element,
  19730. $attrs: attrs,
  19731. $transclude: transcludeFn
  19732. };
  19733. var controller = directive.controller;
  19734. if (controller == '@') {
  19735. controller = attrs[directive.name];
  19736. }
  19737. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  19738. // For directives with element transclusion the element is a comment.
  19739. // In this case .data will not attach any data.
  19740. // Instead, we save the controllers for the element in a local hash and attach to .data
  19741. // later, once we have the actual element.
  19742. elementControllers[directive.name] = controllerInstance;
  19743. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  19744. }
  19745. return elementControllers;
  19746. }
  19747. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  19748. // or child scope created. For instance:
  19749. // * if the directive has been pulled into a template because another directive with a higher priority
  19750. // asked for element transclusion
  19751. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  19752. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  19753. function markDirectiveScope(directives, isolateScope, newScope) {
  19754. for (var j = 0, jj = directives.length; j < jj; j++) {
  19755. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  19756. }
  19757. }
  19758. /**
  19759. * looks up the directive and decorates it with exception handling and proper parameters. We
  19760. * call this the boundDirective.
  19761. *
  19762. * @param {string} name name of the directive to look up.
  19763. * @param {string} location The directive must be found in specific format.
  19764. * String containing any of theses characters:
  19765. *
  19766. * * `E`: element name
  19767. * * `A': attribute
  19768. * * `C`: class
  19769. * * `M`: comment
  19770. * @returns {boolean} true if directive was added.
  19771. */
  19772. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  19773. endAttrName) {
  19774. if (name === ignoreDirective) return null;
  19775. var match = null;
  19776. if (hasDirectives.hasOwnProperty(name)) {
  19777. for (var directive, directives = $injector.get(name + Suffix),
  19778. i = 0, ii = directives.length; i < ii; i++) {
  19779. try {
  19780. directive = directives[i];
  19781. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  19782. directive.restrict.indexOf(location) != -1) {
  19783. if (startAttrName) {
  19784. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  19785. }
  19786. if (!directive.$$bindings) {
  19787. var bindings = directive.$$bindings =
  19788. parseDirectiveBindings(directive, directive.name);
  19789. if (isObject(bindings.isolateScope)) {
  19790. directive.$$isolateBindings = bindings.isolateScope;
  19791. }
  19792. }
  19793. tDirectives.push(directive);
  19794. match = directive;
  19795. }
  19796. } catch (e) { $exceptionHandler(e); }
  19797. }
  19798. }
  19799. return match;
  19800. }
  19801. /**
  19802. * looks up the directive and returns true if it is a multi-element directive,
  19803. * and therefore requires DOM nodes between -start and -end markers to be grouped
  19804. * together.
  19805. *
  19806. * @param {string} name name of the directive to look up.
  19807. * @returns true if directive was registered as multi-element.
  19808. */
  19809. function directiveIsMultiElement(name) {
  19810. if (hasDirectives.hasOwnProperty(name)) {
  19811. for (var directive, directives = $injector.get(name + Suffix),
  19812. i = 0, ii = directives.length; i < ii; i++) {
  19813. directive = directives[i];
  19814. if (directive.multiElement) {
  19815. return true;
  19816. }
  19817. }
  19818. }
  19819. return false;
  19820. }
  19821. /**
  19822. * When the element is replaced with HTML template then the new attributes
  19823. * on the template need to be merged with the existing attributes in the DOM.
  19824. * The desired effect is to have both of the attributes present.
  19825. *
  19826. * @param {object} dst destination attributes (original DOM)
  19827. * @param {object} src source attributes (from the directive template)
  19828. */
  19829. function mergeTemplateAttributes(dst, src) {
  19830. var srcAttr = src.$attr,
  19831. dstAttr = dst.$attr,
  19832. $element = dst.$$element;
  19833. // reapply the old attributes to the new element
  19834. forEach(dst, function(value, key) {
  19835. if (key.charAt(0) != '$') {
  19836. if (src[key] && src[key] !== value) {
  19837. value += (key === 'style' ? ';' : ' ') + src[key];
  19838. }
  19839. dst.$set(key, value, true, srcAttr[key]);
  19840. }
  19841. });
  19842. // copy the new attributes on the old attrs object
  19843. forEach(src, function(value, key) {
  19844. if (key == 'class') {
  19845. safeAddClass($element, value);
  19846. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  19847. } else if (key == 'style') {
  19848. $element.attr('style', $element.attr('style') + ';' + value);
  19849. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  19850. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  19851. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  19852. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  19853. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  19854. dst[key] = value;
  19855. dstAttr[key] = srcAttr[key];
  19856. }
  19857. });
  19858. }
  19859. function compileTemplateUrl(directives, $compileNode, tAttrs,
  19860. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  19861. var linkQueue = [],
  19862. afterTemplateNodeLinkFn,
  19863. afterTemplateChildLinkFn,
  19864. beforeTemplateCompileNode = $compileNode[0],
  19865. origAsyncDirective = directives.shift(),
  19866. derivedSyncDirective = inherit(origAsyncDirective, {
  19867. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  19868. }),
  19869. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  19870. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  19871. : origAsyncDirective.templateUrl,
  19872. templateNamespace = origAsyncDirective.templateNamespace;
  19873. $compileNode.empty();
  19874. $templateRequest(templateUrl)
  19875. .then(function(content) {
  19876. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  19877. content = denormalizeTemplate(content);
  19878. if (origAsyncDirective.replace) {
  19879. if (jqLiteIsTextNode(content)) {
  19880. $template = [];
  19881. } else {
  19882. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  19883. }
  19884. compileNode = $template[0];
  19885. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  19886. throw $compileMinErr('tplrt',
  19887. "Template for directive '{0}' must have exactly one root element. {1}",
  19888. origAsyncDirective.name, templateUrl);
  19889. }
  19890. tempTemplateAttrs = {$attr: {}};
  19891. replaceWith($rootElement, $compileNode, compileNode);
  19892. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  19893. if (isObject(origAsyncDirective.scope)) {
  19894. // the original directive that caused the template to be loaded async required
  19895. // an isolate scope
  19896. markDirectiveScope(templateDirectives, true);
  19897. }
  19898. directives = templateDirectives.concat(directives);
  19899. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  19900. } else {
  19901. compileNode = beforeTemplateCompileNode;
  19902. $compileNode.html(content);
  19903. }
  19904. directives.unshift(derivedSyncDirective);
  19905. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  19906. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  19907. previousCompileContext);
  19908. forEach($rootElement, function(node, i) {
  19909. if (node == compileNode) {
  19910. $rootElement[i] = $compileNode[0];
  19911. }
  19912. });
  19913. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  19914. while (linkQueue.length) {
  19915. var scope = linkQueue.shift(),
  19916. beforeTemplateLinkNode = linkQueue.shift(),
  19917. linkRootElement = linkQueue.shift(),
  19918. boundTranscludeFn = linkQueue.shift(),
  19919. linkNode = $compileNode[0];
  19920. if (scope.$$destroyed) continue;
  19921. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  19922. var oldClasses = beforeTemplateLinkNode.className;
  19923. if (!(previousCompileContext.hasElementTranscludeDirective &&
  19924. origAsyncDirective.replace)) {
  19925. // it was cloned therefore we have to clone as well.
  19926. linkNode = jqLiteClone(compileNode);
  19927. }
  19928. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  19929. // Copy in CSS classes from original node
  19930. safeAddClass(jqLite(linkNode), oldClasses);
  19931. }
  19932. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  19933. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  19934. } else {
  19935. childBoundTranscludeFn = boundTranscludeFn;
  19936. }
  19937. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  19938. childBoundTranscludeFn);
  19939. }
  19940. linkQueue = null;
  19941. });
  19942. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  19943. var childBoundTranscludeFn = boundTranscludeFn;
  19944. if (scope.$$destroyed) return;
  19945. if (linkQueue) {
  19946. linkQueue.push(scope,
  19947. node,
  19948. rootElement,
  19949. childBoundTranscludeFn);
  19950. } else {
  19951. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  19952. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  19953. }
  19954. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  19955. }
  19956. };
  19957. }
  19958. /**
  19959. * Sorting function for bound directives.
  19960. */
  19961. function byPriority(a, b) {
  19962. var diff = b.priority - a.priority;
  19963. if (diff !== 0) return diff;
  19964. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  19965. return a.index - b.index;
  19966. }
  19967. function assertNoDuplicate(what, previousDirective, directive, element) {
  19968. function wrapModuleNameIfDefined(moduleName) {
  19969. return moduleName ?
  19970. (' (module: ' + moduleName + ')') :
  19971. '';
  19972. }
  19973. if (previousDirective) {
  19974. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  19975. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  19976. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  19977. }
  19978. }
  19979. function addTextInterpolateDirective(directives, text) {
  19980. var interpolateFn = $interpolate(text, true);
  19981. if (interpolateFn) {
  19982. directives.push({
  19983. priority: 0,
  19984. compile: function textInterpolateCompileFn(templateNode) {
  19985. var templateNodeParent = templateNode.parent(),
  19986. hasCompileParent = !!templateNodeParent.length;
  19987. // When transcluding a template that has bindings in the root
  19988. // we don't have a parent and thus need to add the class during linking fn.
  19989. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  19990. return function textInterpolateLinkFn(scope, node) {
  19991. var parent = node.parent();
  19992. if (!hasCompileParent) compile.$$addBindingClass(parent);
  19993. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  19994. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  19995. node[0].nodeValue = value;
  19996. });
  19997. };
  19998. }
  19999. });
  20000. }
  20001. }
  20002. function wrapTemplate(type, template) {
  20003. type = lowercase(type || 'html');
  20004. switch (type) {
  20005. case 'svg':
  20006. case 'math':
  20007. var wrapper = document.createElement('div');
  20008. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  20009. return wrapper.childNodes[0].childNodes;
  20010. default:
  20011. return template;
  20012. }
  20013. }
  20014. function getTrustedContext(node, attrNormalizedName) {
  20015. if (attrNormalizedName == "srcdoc") {
  20016. return $sce.HTML;
  20017. }
  20018. var tag = nodeName_(node);
  20019. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  20020. if (attrNormalizedName == "xlinkHref" ||
  20021. (tag == "form" && attrNormalizedName == "action") ||
  20022. (tag != "img" && (attrNormalizedName == "src" ||
  20023. attrNormalizedName == "ngSrc"))) {
  20024. return $sce.RESOURCE_URL;
  20025. }
  20026. }
  20027. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  20028. var trustedContext = getTrustedContext(node, name);
  20029. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  20030. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  20031. // no interpolation found -> ignore
  20032. if (!interpolateFn) return;
  20033. if (name === "multiple" && nodeName_(node) === "select") {
  20034. throw $compileMinErr("selmulti",
  20035. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  20036. startingTag(node));
  20037. }
  20038. directives.push({
  20039. priority: 100,
  20040. compile: function() {
  20041. return {
  20042. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  20043. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  20044. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  20045. throw $compileMinErr('nodomevents',
  20046. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  20047. "ng- versions (such as ng-click instead of onclick) instead.");
  20048. }
  20049. // If the attribute has changed since last $interpolate()ed
  20050. var newValue = attr[name];
  20051. if (newValue !== value) {
  20052. // we need to interpolate again since the attribute value has been updated
  20053. // (e.g. by another directive's compile function)
  20054. // ensure unset/empty values make interpolateFn falsy
  20055. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  20056. value = newValue;
  20057. }
  20058. // if attribute was updated so that there is no interpolation going on we don't want to
  20059. // register any observers
  20060. if (!interpolateFn) return;
  20061. // initialize attr object so that it's ready in case we need the value for isolate
  20062. // scope initialization, otherwise the value would not be available from isolate
  20063. // directive's linking fn during linking phase
  20064. attr[name] = interpolateFn(scope);
  20065. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  20066. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  20067. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  20068. //special case for class attribute addition + removal
  20069. //so that class changes can tap into the animation
  20070. //hooks provided by the $animate service. Be sure to
  20071. //skip animations when the first digest occurs (when
  20072. //both the new and the old values are the same) since
  20073. //the CSS classes are the non-interpolated values
  20074. if (name === 'class' && newValue != oldValue) {
  20075. attr.$updateClass(newValue, oldValue);
  20076. } else {
  20077. attr.$set(name, newValue);
  20078. }
  20079. });
  20080. }
  20081. };
  20082. }
  20083. });
  20084. }
  20085. /**
  20086. * This is a special jqLite.replaceWith, which can replace items which
  20087. * have no parents, provided that the containing jqLite collection is provided.
  20088. *
  20089. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  20090. * in the root of the tree.
  20091. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  20092. * the shell, but replace its DOM node reference.
  20093. * @param {Node} newNode The new DOM node.
  20094. */
  20095. function replaceWith($rootElement, elementsToRemove, newNode) {
  20096. var firstElementToRemove = elementsToRemove[0],
  20097. removeCount = elementsToRemove.length,
  20098. parent = firstElementToRemove.parentNode,
  20099. i, ii;
  20100. if ($rootElement) {
  20101. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  20102. if ($rootElement[i] == firstElementToRemove) {
  20103. $rootElement[i++] = newNode;
  20104. for (var j = i, j2 = j + removeCount - 1,
  20105. jj = $rootElement.length;
  20106. j < jj; j++, j2++) {
  20107. if (j2 < jj) {
  20108. $rootElement[j] = $rootElement[j2];
  20109. } else {
  20110. delete $rootElement[j];
  20111. }
  20112. }
  20113. $rootElement.length -= removeCount - 1;
  20114. // If the replaced element is also the jQuery .context then replace it
  20115. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  20116. // http://api.jquery.com/context/
  20117. if ($rootElement.context === firstElementToRemove) {
  20118. $rootElement.context = newNode;
  20119. }
  20120. break;
  20121. }
  20122. }
  20123. }
  20124. if (parent) {
  20125. parent.replaceChild(newNode, firstElementToRemove);
  20126. }
  20127. // Append all the `elementsToRemove` to a fragment. This will...
  20128. // - remove them from the DOM
  20129. // - allow them to still be traversed with .nextSibling
  20130. // - allow a single fragment.qSA to fetch all elements being removed
  20131. var fragment = document.createDocumentFragment();
  20132. for (i = 0; i < removeCount; i++) {
  20133. fragment.appendChild(elementsToRemove[i]);
  20134. }
  20135. if (jqLite.hasData(firstElementToRemove)) {
  20136. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  20137. // data here because there's no public interface in jQuery to do that and copying over
  20138. // event listeners (which is the main use of private data) wouldn't work anyway.
  20139. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  20140. // Remove $destroy event listeners from `firstElementToRemove`
  20141. jqLite(firstElementToRemove).off('$destroy');
  20142. }
  20143. // Cleanup any data/listeners on the elements and children.
  20144. // This includes invoking the $destroy event on any elements with listeners.
  20145. jqLite.cleanData(fragment.querySelectorAll('*'));
  20146. // Update the jqLite collection to only contain the `newNode`
  20147. for (i = 1; i < removeCount; i++) {
  20148. delete elementsToRemove[i];
  20149. }
  20150. elementsToRemove[0] = newNode;
  20151. elementsToRemove.length = 1;
  20152. }
  20153. function cloneAndAnnotateFn(fn, annotation) {
  20154. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  20155. }
  20156. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  20157. try {
  20158. linkFn(scope, $element, attrs, controllers, transcludeFn);
  20159. } catch (e) {
  20160. $exceptionHandler(e, startingTag($element));
  20161. }
  20162. }
  20163. // Set up $watches for isolate scope and controller bindings. This process
  20164. // only occurs for isolate scopes and new scopes with controllerAs.
  20165. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  20166. var removeWatchCollection = [];
  20167. var changes;
  20168. forEach(bindings, function initializeBinding(definition, scopeName) {
  20169. var attrName = definition.attrName,
  20170. optional = definition.optional,
  20171. mode = definition.mode, // @, =, or &
  20172. lastValue,
  20173. parentGet, parentSet, compare, removeWatch;
  20174. switch (mode) {
  20175. case '@':
  20176. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  20177. destination[scopeName] = attrs[attrName] = void 0;
  20178. }
  20179. attrs.$observe(attrName, function(value) {
  20180. if (isString(value)) {
  20181. var oldValue = destination[scopeName];
  20182. recordChanges(scopeName, value, oldValue);
  20183. destination[scopeName] = value;
  20184. }
  20185. });
  20186. attrs.$$observers[attrName].$$scope = scope;
  20187. lastValue = attrs[attrName];
  20188. if (isString(lastValue)) {
  20189. // If the attribute has been provided then we trigger an interpolation to ensure
  20190. // the value is there for use in the link fn
  20191. destination[scopeName] = $interpolate(lastValue)(scope);
  20192. } else if (isBoolean(lastValue)) {
  20193. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  20194. // the value to boolean rather than a string, so we special case this situation
  20195. destination[scopeName] = lastValue;
  20196. }
  20197. break;
  20198. case '=':
  20199. if (!hasOwnProperty.call(attrs, attrName)) {
  20200. if (optional) break;
  20201. attrs[attrName] = void 0;
  20202. }
  20203. if (optional && !attrs[attrName]) break;
  20204. parentGet = $parse(attrs[attrName]);
  20205. if (parentGet.literal) {
  20206. compare = equals;
  20207. } else {
  20208. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  20209. }
  20210. parentSet = parentGet.assign || function() {
  20211. // reset the change, or we will throw this exception on every $digest
  20212. lastValue = destination[scopeName] = parentGet(scope);
  20213. throw $compileMinErr('nonassign',
  20214. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  20215. attrs[attrName], attrName, directive.name);
  20216. };
  20217. lastValue = destination[scopeName] = parentGet(scope);
  20218. var parentValueWatch = function parentValueWatch(parentValue) {
  20219. if (!compare(parentValue, destination[scopeName])) {
  20220. // we are out of sync and need to copy
  20221. if (!compare(parentValue, lastValue)) {
  20222. // parent changed and it has precedence
  20223. destination[scopeName] = parentValue;
  20224. } else {
  20225. // if the parent can be assigned then do so
  20226. parentSet(scope, parentValue = destination[scopeName]);
  20227. }
  20228. }
  20229. return lastValue = parentValue;
  20230. };
  20231. parentValueWatch.$stateful = true;
  20232. if (definition.collection) {
  20233. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  20234. } else {
  20235. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  20236. }
  20237. removeWatchCollection.push(removeWatch);
  20238. break;
  20239. case '<':
  20240. if (!hasOwnProperty.call(attrs, attrName)) {
  20241. if (optional) break;
  20242. attrs[attrName] = void 0;
  20243. }
  20244. if (optional && !attrs[attrName]) break;
  20245. parentGet = $parse(attrs[attrName]);
  20246. destination[scopeName] = parentGet(scope);
  20247. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
  20248. var oldValue = destination[scopeName];
  20249. recordChanges(scopeName, newParentValue, oldValue);
  20250. destination[scopeName] = newParentValue;
  20251. }, parentGet.literal);
  20252. removeWatchCollection.push(removeWatch);
  20253. break;
  20254. case '&':
  20255. // Don't assign Object.prototype method to scope
  20256. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  20257. // Don't assign noop to destination if expression is not valid
  20258. if (parentGet === noop && optional) break;
  20259. destination[scopeName] = function(locals) {
  20260. return parentGet(scope, locals);
  20261. };
  20262. break;
  20263. }
  20264. });
  20265. function recordChanges(key, currentValue, previousValue) {
  20266. if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
  20267. // If we have not already scheduled the top level onChangesQueue handler then do so now
  20268. if (!onChangesQueue) {
  20269. scope.$$postDigest(flushOnChangesQueue);
  20270. onChangesQueue = [];
  20271. }
  20272. // If we have not already queued a trigger of onChanges for this controller then do so now
  20273. if (!changes) {
  20274. changes = {};
  20275. onChangesQueue.push(triggerOnChangesHook);
  20276. }
  20277. // If the has been a change on this property already then we need to reuse the previous value
  20278. if (changes[key]) {
  20279. previousValue = changes[key].previousValue;
  20280. }
  20281. // Store this change
  20282. changes[key] = {previousValue: previousValue, currentValue: currentValue};
  20283. }
  20284. }
  20285. function triggerOnChangesHook() {
  20286. destination.$onChanges(changes);
  20287. // Now clear the changes so that we schedule onChanges when more changes arrive
  20288. changes = undefined;
  20289. }
  20290. return removeWatchCollection.length && function removeWatches() {
  20291. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  20292. removeWatchCollection[i]();
  20293. }
  20294. };
  20295. }
  20296. }];
  20297. }
  20298. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  20299. /**
  20300. * Converts all accepted directives format into proper directive name.
  20301. * @param name Name to normalize
  20302. */
  20303. function directiveNormalize(name) {
  20304. return camelCase(name.replace(PREFIX_REGEXP, ''));
  20305. }
  20306. /**
  20307. * @ngdoc type
  20308. * @name $compile.directive.Attributes
  20309. *
  20310. * @description
  20311. * A shared object between directive compile / linking functions which contains normalized DOM
  20312. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  20313. * needed since all of these are treated as equivalent in Angular:
  20314. *
  20315. * ```
  20316. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  20317. * ```
  20318. */
  20319. /**
  20320. * @ngdoc property
  20321. * @name $compile.directive.Attributes#$attr
  20322. *
  20323. * @description
  20324. * A map of DOM element attribute names to the normalized name. This is
  20325. * needed to do reverse lookup from normalized name back to actual name.
  20326. */
  20327. /**
  20328. * @ngdoc method
  20329. * @name $compile.directive.Attributes#$set
  20330. * @kind function
  20331. *
  20332. * @description
  20333. * Set DOM element attribute value.
  20334. *
  20335. *
  20336. * @param {string} name Normalized element attribute name of the property to modify. The name is
  20337. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  20338. * property to the original name.
  20339. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  20340. */
  20341. /**
  20342. * Closure compiler type information
  20343. */
  20344. function nodesetLinkingFn(
  20345. /* angular.Scope */ scope,
  20346. /* NodeList */ nodeList,
  20347. /* Element */ rootElement,
  20348. /* function(Function) */ boundTranscludeFn
  20349. ) {}
  20350. function directiveLinkingFn(
  20351. /* nodesetLinkingFn */ nodesetLinkingFn,
  20352. /* angular.Scope */ scope,
  20353. /* Node */ node,
  20354. /* Element */ rootElement,
  20355. /* function(Function) */ boundTranscludeFn
  20356. ) {}
  20357. function tokenDifference(str1, str2) {
  20358. var values = '',
  20359. tokens1 = str1.split(/\s+/),
  20360. tokens2 = str2.split(/\s+/);
  20361. outer:
  20362. for (var i = 0; i < tokens1.length; i++) {
  20363. var token = tokens1[i];
  20364. for (var j = 0; j < tokens2.length; j++) {
  20365. if (token == tokens2[j]) continue outer;
  20366. }
  20367. values += (values.length > 0 ? ' ' : '') + token;
  20368. }
  20369. return values;
  20370. }
  20371. function removeComments(jqNodes) {
  20372. jqNodes = jqLite(jqNodes);
  20373. var i = jqNodes.length;
  20374. if (i <= 1) {
  20375. return jqNodes;
  20376. }
  20377. while (i--) {
  20378. var node = jqNodes[i];
  20379. if (node.nodeType === NODE_TYPE_COMMENT) {
  20380. splice.call(jqNodes, i, 1);
  20381. }
  20382. }
  20383. return jqNodes;
  20384. }
  20385. var $controllerMinErr = minErr('$controller');
  20386. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  20387. function identifierForController(controller, ident) {
  20388. if (ident && isString(ident)) return ident;
  20389. if (isString(controller)) {
  20390. var match = CNTRL_REG.exec(controller);
  20391. if (match) return match[3];
  20392. }
  20393. }
  20394. /**
  20395. * @ngdoc provider
  20396. * @name $controllerProvider
  20397. * @description
  20398. * The {@link ng.$controller $controller service} is used by Angular to create new
  20399. * controllers.
  20400. *
  20401. * This provider allows controller registration via the
  20402. * {@link ng.$controllerProvider#register register} method.
  20403. */
  20404. function $ControllerProvider() {
  20405. var controllers = {},
  20406. globals = false;
  20407. /**
  20408. * @ngdoc method
  20409. * @name $controllerProvider#has
  20410. * @param {string} name Controller name to check.
  20411. */
  20412. this.has = function(name) {
  20413. return controllers.hasOwnProperty(name);
  20414. };
  20415. /**
  20416. * @ngdoc method
  20417. * @name $controllerProvider#register
  20418. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  20419. * the names and the values are the constructors.
  20420. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  20421. * annotations in the array notation).
  20422. */
  20423. this.register = function(name, constructor) {
  20424. assertNotHasOwnProperty(name, 'controller');
  20425. if (isObject(name)) {
  20426. extend(controllers, name);
  20427. } else {
  20428. controllers[name] = constructor;
  20429. }
  20430. };
  20431. /**
  20432. * @ngdoc method
  20433. * @name $controllerProvider#allowGlobals
  20434. * @description If called, allows `$controller` to find controller constructors on `window`
  20435. */
  20436. this.allowGlobals = function() {
  20437. globals = true;
  20438. };
  20439. this.$get = ['$injector', '$window', function($injector, $window) {
  20440. /**
  20441. * @ngdoc service
  20442. * @name $controller
  20443. * @requires $injector
  20444. *
  20445. * @param {Function|string} constructor If called with a function then it's considered to be the
  20446. * controller constructor function. Otherwise it's considered to be a string which is used
  20447. * to retrieve the controller constructor using the following steps:
  20448. *
  20449. * * check if a controller with given name is registered via `$controllerProvider`
  20450. * * check if evaluating the string on the current scope returns a constructor
  20451. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  20452. * `window` object (not recommended)
  20453. *
  20454. * The string can use the `controller as property` syntax, where the controller instance is published
  20455. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  20456. * to work correctly.
  20457. *
  20458. * @param {Object} locals Injection locals for Controller.
  20459. * @return {Object} Instance of given controller.
  20460. *
  20461. * @description
  20462. * `$controller` service is responsible for instantiating controllers.
  20463. *
  20464. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  20465. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  20466. */
  20467. return function $controller(expression, locals, later, ident) {
  20468. // PRIVATE API:
  20469. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  20470. // If true, $controller will allocate the object with the correct
  20471. // prototype chain, but will not invoke the controller until a returned
  20472. // callback is invoked.
  20473. // param `ident` --- An optional label which overrides the label parsed from the controller
  20474. // expression, if any.
  20475. var instance, match, constructor, identifier;
  20476. later = later === true;
  20477. if (ident && isString(ident)) {
  20478. identifier = ident;
  20479. }
  20480. if (isString(expression)) {
  20481. match = expression.match(CNTRL_REG);
  20482. if (!match) {
  20483. throw $controllerMinErr('ctrlfmt',
  20484. "Badly formed controller string '{0}'. " +
  20485. "Must match `__name__ as __id__` or `__name__`.", expression);
  20486. }
  20487. constructor = match[1],
  20488. identifier = identifier || match[3];
  20489. expression = controllers.hasOwnProperty(constructor)
  20490. ? controllers[constructor]
  20491. : getter(locals.$scope, constructor, true) ||
  20492. (globals ? getter($window, constructor, true) : undefined);
  20493. assertArgFn(expression, constructor, true);
  20494. }
  20495. if (later) {
  20496. // Instantiate controller later:
  20497. // This machinery is used to create an instance of the object before calling the
  20498. // controller's constructor itself.
  20499. //
  20500. // This allows properties to be added to the controller before the constructor is
  20501. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  20502. //
  20503. // This feature is not intended for use by applications, and is thus not documented
  20504. // publicly.
  20505. // Object creation: http://jsperf.com/create-constructor/2
  20506. var controllerPrototype = (isArray(expression) ?
  20507. expression[expression.length - 1] : expression).prototype;
  20508. instance = Object.create(controllerPrototype || null);
  20509. if (identifier) {
  20510. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20511. }
  20512. var instantiate;
  20513. return instantiate = extend(function $controllerInit() {
  20514. var result = $injector.invoke(expression, instance, locals, constructor);
  20515. if (result !== instance && (isObject(result) || isFunction(result))) {
  20516. instance = result;
  20517. if (identifier) {
  20518. // If result changed, re-assign controllerAs value to scope.
  20519. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20520. }
  20521. }
  20522. return instance;
  20523. }, {
  20524. instance: instance,
  20525. identifier: identifier
  20526. });
  20527. }
  20528. instance = $injector.instantiate(expression, locals, constructor);
  20529. if (identifier) {
  20530. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20531. }
  20532. return instance;
  20533. };
  20534. function addIdentifier(locals, identifier, instance, name) {
  20535. if (!(locals && isObject(locals.$scope))) {
  20536. throw minErr('$controller')('noscp',
  20537. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  20538. name, identifier);
  20539. }
  20540. locals.$scope[identifier] = instance;
  20541. }
  20542. }];
  20543. }
  20544. /**
  20545. * @ngdoc service
  20546. * @name $document
  20547. * @requires $window
  20548. *
  20549. * @description
  20550. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  20551. *
  20552. * @example
  20553. <example module="documentExample">
  20554. <file name="index.html">
  20555. <div ng-controller="ExampleController">
  20556. <p>$document title: <b ng-bind="title"></b></p>
  20557. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  20558. </div>
  20559. </file>
  20560. <file name="script.js">
  20561. angular.module('documentExample', [])
  20562. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  20563. $scope.title = $document[0].title;
  20564. $scope.windowTitle = angular.element(window.document)[0].title;
  20565. }]);
  20566. </file>
  20567. </example>
  20568. */
  20569. function $DocumentProvider() {
  20570. this.$get = ['$window', function(window) {
  20571. return jqLite(window.document);
  20572. }];
  20573. }
  20574. /**
  20575. * @ngdoc service
  20576. * @name $exceptionHandler
  20577. * @requires ng.$log
  20578. *
  20579. * @description
  20580. * Any uncaught exception in angular expressions is delegated to this service.
  20581. * The default implementation simply delegates to `$log.error` which logs it into
  20582. * the browser console.
  20583. *
  20584. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  20585. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  20586. *
  20587. * ## Example:
  20588. *
  20589. * ```js
  20590. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  20591. * return function(exception, cause) {
  20592. * exception.message += ' (caused by "' + cause + '")';
  20593. * throw exception;
  20594. * };
  20595. * });
  20596. * ```
  20597. *
  20598. * This example will override the normal action of `$exceptionHandler`, to make angular
  20599. * exceptions fail hard when they happen, instead of just logging to the console.
  20600. *
  20601. * <hr />
  20602. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  20603. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  20604. * (unless executed during a digest).
  20605. *
  20606. * If you wish, you can manually delegate exceptions, e.g.
  20607. * `try { ... } catch(e) { $exceptionHandler(e); }`
  20608. *
  20609. * @param {Error} exception Exception associated with the error.
  20610. * @param {string=} cause optional information about the context in which
  20611. * the error was thrown.
  20612. *
  20613. */
  20614. function $ExceptionHandlerProvider() {
  20615. this.$get = ['$log', function($log) {
  20616. return function(exception, cause) {
  20617. $log.error.apply($log, arguments);
  20618. };
  20619. }];
  20620. }
  20621. var $$ForceReflowProvider = function() {
  20622. this.$get = ['$document', function($document) {
  20623. return function(domNode) {
  20624. //the line below will force the browser to perform a repaint so
  20625. //that all the animated elements within the animation frame will
  20626. //be properly updated and drawn on screen. This is required to
  20627. //ensure that the preparation animation is properly flushed so that
  20628. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  20629. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  20630. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  20631. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  20632. if (domNode) {
  20633. if (!domNode.nodeType && domNode instanceof jqLite) {
  20634. domNode = domNode[0];
  20635. }
  20636. } else {
  20637. domNode = $document[0].body;
  20638. }
  20639. return domNode.offsetWidth + 1;
  20640. };
  20641. }];
  20642. };
  20643. var APPLICATION_JSON = 'application/json';
  20644. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  20645. var JSON_START = /^\[|^\{(?!\{)/;
  20646. var JSON_ENDS = {
  20647. '[': /]$/,
  20648. '{': /}$/
  20649. };
  20650. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  20651. var $httpMinErr = minErr('$http');
  20652. var $httpMinErrLegacyFn = function(method) {
  20653. return function() {
  20654. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  20655. };
  20656. };
  20657. function serializeValue(v) {
  20658. if (isObject(v)) {
  20659. return isDate(v) ? v.toISOString() : toJson(v);
  20660. }
  20661. return v;
  20662. }
  20663. function $HttpParamSerializerProvider() {
  20664. /**
  20665. * @ngdoc service
  20666. * @name $httpParamSerializer
  20667. * @description
  20668. *
  20669. * Default {@link $http `$http`} params serializer that converts objects to strings
  20670. * according to the following rules:
  20671. *
  20672. * * `{'foo': 'bar'}` results in `foo=bar`
  20673. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  20674. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  20675. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  20676. *
  20677. * Note that serializer will sort the request parameters alphabetically.
  20678. * */
  20679. this.$get = function() {
  20680. return function ngParamSerializer(params) {
  20681. if (!params) return '';
  20682. var parts = [];
  20683. forEachSorted(params, function(value, key) {
  20684. if (value === null || isUndefined(value)) return;
  20685. if (isArray(value)) {
  20686. forEach(value, function(v) {
  20687. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  20688. });
  20689. } else {
  20690. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  20691. }
  20692. });
  20693. return parts.join('&');
  20694. };
  20695. };
  20696. }
  20697. function $HttpParamSerializerJQLikeProvider() {
  20698. /**
  20699. * @ngdoc service
  20700. * @name $httpParamSerializerJQLike
  20701. * @description
  20702. *
  20703. * Alternative {@link $http `$http`} params serializer that follows
  20704. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  20705. * The serializer will also sort the params alphabetically.
  20706. *
  20707. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  20708. *
  20709. * ```js
  20710. * $http({
  20711. * url: myUrl,
  20712. * method: 'GET',
  20713. * params: myParams,
  20714. * paramSerializer: '$httpParamSerializerJQLike'
  20715. * });
  20716. * ```
  20717. *
  20718. * It is also possible to set it as the default `paramSerializer` in the
  20719. * {@link $httpProvider#defaults `$httpProvider`}.
  20720. *
  20721. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  20722. * form data for submission:
  20723. *
  20724. * ```js
  20725. * .controller(function($http, $httpParamSerializerJQLike) {
  20726. * //...
  20727. *
  20728. * $http({
  20729. * url: myUrl,
  20730. * method: 'POST',
  20731. * data: $httpParamSerializerJQLike(myData),
  20732. * headers: {
  20733. * 'Content-Type': 'application/x-www-form-urlencoded'
  20734. * }
  20735. * });
  20736. *
  20737. * });
  20738. * ```
  20739. *
  20740. * */
  20741. this.$get = function() {
  20742. return function jQueryLikeParamSerializer(params) {
  20743. if (!params) return '';
  20744. var parts = [];
  20745. serialize(params, '', true);
  20746. return parts.join('&');
  20747. function serialize(toSerialize, prefix, topLevel) {
  20748. if (toSerialize === null || isUndefined(toSerialize)) return;
  20749. if (isArray(toSerialize)) {
  20750. forEach(toSerialize, function(value, index) {
  20751. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  20752. });
  20753. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  20754. forEachSorted(toSerialize, function(value, key) {
  20755. serialize(value, prefix +
  20756. (topLevel ? '' : '[') +
  20757. key +
  20758. (topLevel ? '' : ']'));
  20759. });
  20760. } else {
  20761. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  20762. }
  20763. }
  20764. };
  20765. };
  20766. }
  20767. function defaultHttpResponseTransform(data, headers) {
  20768. if (isString(data)) {
  20769. // Strip json vulnerability protection prefix and trim whitespace
  20770. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  20771. if (tempData) {
  20772. var contentType = headers('Content-Type');
  20773. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  20774. data = fromJson(tempData);
  20775. }
  20776. }
  20777. }
  20778. return data;
  20779. }
  20780. function isJsonLike(str) {
  20781. var jsonStart = str.match(JSON_START);
  20782. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  20783. }
  20784. /**
  20785. * Parse headers into key value object
  20786. *
  20787. * @param {string} headers Raw headers as a string
  20788. * @returns {Object} Parsed headers as key value object
  20789. */
  20790. function parseHeaders(headers) {
  20791. var parsed = createMap(), i;
  20792. function fillInParsed(key, val) {
  20793. if (key) {
  20794. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  20795. }
  20796. }
  20797. if (isString(headers)) {
  20798. forEach(headers.split('\n'), function(line) {
  20799. i = line.indexOf(':');
  20800. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  20801. });
  20802. } else if (isObject(headers)) {
  20803. forEach(headers, function(headerVal, headerKey) {
  20804. fillInParsed(lowercase(headerKey), trim(headerVal));
  20805. });
  20806. }
  20807. return parsed;
  20808. }
  20809. /**
  20810. * Returns a function that provides access to parsed headers.
  20811. *
  20812. * Headers are lazy parsed when first requested.
  20813. * @see parseHeaders
  20814. *
  20815. * @param {(string|Object)} headers Headers to provide access to.
  20816. * @returns {function(string=)} Returns a getter function which if called with:
  20817. *
  20818. * - if called with single an argument returns a single header value or null
  20819. * - if called with no arguments returns an object containing all headers.
  20820. */
  20821. function headersGetter(headers) {
  20822. var headersObj;
  20823. return function(name) {
  20824. if (!headersObj) headersObj = parseHeaders(headers);
  20825. if (name) {
  20826. var value = headersObj[lowercase(name)];
  20827. if (value === void 0) {
  20828. value = null;
  20829. }
  20830. return value;
  20831. }
  20832. return headersObj;
  20833. };
  20834. }
  20835. /**
  20836. * Chain all given functions
  20837. *
  20838. * This function is used for both request and response transforming
  20839. *
  20840. * @param {*} data Data to transform.
  20841. * @param {function(string=)} headers HTTP headers getter fn.
  20842. * @param {number} status HTTP status code of the response.
  20843. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  20844. * @returns {*} Transformed data.
  20845. */
  20846. function transformData(data, headers, status, fns) {
  20847. if (isFunction(fns)) {
  20848. return fns(data, headers, status);
  20849. }
  20850. forEach(fns, function(fn) {
  20851. data = fn(data, headers, status);
  20852. });
  20853. return data;
  20854. }
  20855. function isSuccess(status) {
  20856. return 200 <= status && status < 300;
  20857. }
  20858. /**
  20859. * @ngdoc provider
  20860. * @name $httpProvider
  20861. * @description
  20862. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  20863. * */
  20864. function $HttpProvider() {
  20865. /**
  20866. * @ngdoc property
  20867. * @name $httpProvider#defaults
  20868. * @description
  20869. *
  20870. * Object containing default values for all {@link ng.$http $http} requests.
  20871. *
  20872. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  20873. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  20874. * by default. See {@link $http#caching $http Caching} for more information.
  20875. *
  20876. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  20877. * Defaults value is `'XSRF-TOKEN'`.
  20878. *
  20879. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  20880. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  20881. *
  20882. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  20883. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  20884. * setting default headers.
  20885. * - **`defaults.headers.common`**
  20886. * - **`defaults.headers.post`**
  20887. * - **`defaults.headers.put`**
  20888. * - **`defaults.headers.patch`**
  20889. *
  20890. *
  20891. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  20892. * used to the prepare string representation of request parameters (specified as an object).
  20893. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  20894. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  20895. *
  20896. **/
  20897. var defaults = this.defaults = {
  20898. // transform incoming response data
  20899. transformResponse: [defaultHttpResponseTransform],
  20900. // transform outgoing request data
  20901. transformRequest: [function(d) {
  20902. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  20903. }],
  20904. // default headers
  20905. headers: {
  20906. common: {
  20907. 'Accept': 'application/json, text/plain, */*'
  20908. },
  20909. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  20910. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  20911. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  20912. },
  20913. xsrfCookieName: 'XSRF-TOKEN',
  20914. xsrfHeaderName: 'X-XSRF-TOKEN',
  20915. paramSerializer: '$httpParamSerializer'
  20916. };
  20917. var useApplyAsync = false;
  20918. /**
  20919. * @ngdoc method
  20920. * @name $httpProvider#useApplyAsync
  20921. * @description
  20922. *
  20923. * Configure $http service to combine processing of multiple http responses received at around
  20924. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  20925. * significant performance improvement for bigger applications that make many HTTP requests
  20926. * concurrently (common during application bootstrap).
  20927. *
  20928. * Defaults to false. If no value is specified, returns the current configured value.
  20929. *
  20930. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  20931. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  20932. * to load and share the same digest cycle.
  20933. *
  20934. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  20935. * otherwise, returns the current configured value.
  20936. **/
  20937. this.useApplyAsync = function(value) {
  20938. if (isDefined(value)) {
  20939. useApplyAsync = !!value;
  20940. return this;
  20941. }
  20942. return useApplyAsync;
  20943. };
  20944. var useLegacyPromise = true;
  20945. /**
  20946. * @ngdoc method
  20947. * @name $httpProvider#useLegacyPromiseExtensions
  20948. * @description
  20949. *
  20950. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  20951. * This should be used to make sure that applications work without these methods.
  20952. *
  20953. * Defaults to true. If no value is specified, returns the current configured value.
  20954. *
  20955. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  20956. *
  20957. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  20958. * otherwise, returns the current configured value.
  20959. **/
  20960. this.useLegacyPromiseExtensions = function(value) {
  20961. if (isDefined(value)) {
  20962. useLegacyPromise = !!value;
  20963. return this;
  20964. }
  20965. return useLegacyPromise;
  20966. };
  20967. /**
  20968. * @ngdoc property
  20969. * @name $httpProvider#interceptors
  20970. * @description
  20971. *
  20972. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  20973. * pre-processing of request or postprocessing of responses.
  20974. *
  20975. * These service factories are ordered by request, i.e. they are applied in the same order as the
  20976. * array, on request, but reverse order, on response.
  20977. *
  20978. * {@link ng.$http#interceptors Interceptors detailed info}
  20979. **/
  20980. var interceptorFactories = this.interceptors = [];
  20981. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  20982. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  20983. var defaultCache = $cacheFactory('$http');
  20984. /**
  20985. * Make sure that default param serializer is exposed as a function
  20986. */
  20987. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  20988. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  20989. /**
  20990. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  20991. * The reversal is needed so that we can build up the interception chain around the
  20992. * server request.
  20993. */
  20994. var reversedInterceptors = [];
  20995. forEach(interceptorFactories, function(interceptorFactory) {
  20996. reversedInterceptors.unshift(isString(interceptorFactory)
  20997. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  20998. });
  20999. /**
  21000. * @ngdoc service
  21001. * @kind function
  21002. * @name $http
  21003. * @requires ng.$httpBackend
  21004. * @requires $cacheFactory
  21005. * @requires $rootScope
  21006. * @requires $q
  21007. * @requires $injector
  21008. *
  21009. * @description
  21010. * The `$http` service is a core Angular service that facilitates communication with the remote
  21011. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  21012. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  21013. *
  21014. * For unit testing applications that use `$http` service, see
  21015. * {@link ngMock.$httpBackend $httpBackend mock}.
  21016. *
  21017. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  21018. * $resource} service.
  21019. *
  21020. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  21021. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  21022. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  21023. *
  21024. *
  21025. * ## General usage
  21026. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  21027. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  21028. *
  21029. * ```js
  21030. * // Simple GET request example:
  21031. * $http({
  21032. * method: 'GET',
  21033. * url: '/someUrl'
  21034. * }).then(function successCallback(response) {
  21035. * // this callback will be called asynchronously
  21036. * // when the response is available
  21037. * }, function errorCallback(response) {
  21038. * // called asynchronously if an error occurs
  21039. * // or server returns response with an error status.
  21040. * });
  21041. * ```
  21042. *
  21043. * The response object has these properties:
  21044. *
  21045. * - **data** – `{string|Object}` – The response body transformed with the transform
  21046. * functions.
  21047. * - **status** – `{number}` – HTTP status code of the response.
  21048. * - **headers** – `{function([headerName])}` – Header getter function.
  21049. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  21050. * - **statusText** – `{string}` – HTTP status text of the response.
  21051. *
  21052. * A response status code between 200 and 299 is considered a success status and
  21053. * will result in the success callback being called. Note that if the response is a redirect,
  21054. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  21055. * called for such responses.
  21056. *
  21057. *
  21058. * ## Shortcut methods
  21059. *
  21060. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  21061. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  21062. * last argument.
  21063. *
  21064. * ```js
  21065. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  21066. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  21067. * ```
  21068. *
  21069. * Complete list of shortcut methods:
  21070. *
  21071. * - {@link ng.$http#get $http.get}
  21072. * - {@link ng.$http#head $http.head}
  21073. * - {@link ng.$http#post $http.post}
  21074. * - {@link ng.$http#put $http.put}
  21075. * - {@link ng.$http#delete $http.delete}
  21076. * - {@link ng.$http#jsonp $http.jsonp}
  21077. * - {@link ng.$http#patch $http.patch}
  21078. *
  21079. *
  21080. * ## Writing Unit Tests that use $http
  21081. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  21082. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  21083. * request using trained responses.
  21084. *
  21085. * ```
  21086. * $httpBackend.expectGET(...);
  21087. * $http.get(...);
  21088. * $httpBackend.flush();
  21089. * ```
  21090. *
  21091. * ## Deprecation Notice
  21092. * <div class="alert alert-danger">
  21093. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  21094. * Use the standard `then` method instead.
  21095. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  21096. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  21097. * </div>
  21098. *
  21099. * ## Setting HTTP Headers
  21100. *
  21101. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  21102. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  21103. * object, which currently contains this default configuration:
  21104. *
  21105. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  21106. * - `Accept: application/json, text/plain, * / *`
  21107. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  21108. * - `Content-Type: application/json`
  21109. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  21110. * - `Content-Type: application/json`
  21111. *
  21112. * To add or overwrite these defaults, simply add or remove a property from these configuration
  21113. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  21114. * with the lowercased HTTP method name as the key, e.g.
  21115. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  21116. *
  21117. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  21118. * fashion. For example:
  21119. *
  21120. * ```
  21121. * module.run(function($http) {
  21122. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  21123. * });
  21124. * ```
  21125. *
  21126. * In addition, you can supply a `headers` property in the config object passed when
  21127. * calling `$http(config)`, which overrides the defaults without changing them globally.
  21128. *
  21129. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  21130. * Use the `headers` property, setting the desired header to `undefined`. For example:
  21131. *
  21132. * ```js
  21133. * var req = {
  21134. * method: 'POST',
  21135. * url: 'http://example.com',
  21136. * headers: {
  21137. * 'Content-Type': undefined
  21138. * },
  21139. * data: { test: 'test' }
  21140. * }
  21141. *
  21142. * $http(req).then(function(){...}, function(){...});
  21143. * ```
  21144. *
  21145. * ## Transforming Requests and Responses
  21146. *
  21147. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  21148. * and `transformResponse`. These properties can be a single function that returns
  21149. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  21150. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  21151. *
  21152. * <div class="alert alert-warning">
  21153. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  21154. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  21155. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  21156. * function will be reflected on the scope and in any templates where the object is data-bound.
  21157. * To prevent his, transform functions should have no side-effects.
  21158. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  21159. * </div>
  21160. *
  21161. * ### Default Transformations
  21162. *
  21163. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  21164. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  21165. * then these will be applied.
  21166. *
  21167. * You can augment or replace the default transformations by modifying these properties by adding to or
  21168. * replacing the array.
  21169. *
  21170. * Angular provides the following default transformations:
  21171. *
  21172. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  21173. *
  21174. * - If the `data` property of the request configuration object contains an object, serialize it
  21175. * into JSON format.
  21176. *
  21177. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  21178. *
  21179. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  21180. * - If JSON response is detected, deserialize it using a JSON parser.
  21181. *
  21182. *
  21183. * ### Overriding the Default Transformations Per Request
  21184. *
  21185. * If you wish override the request/response transformations only for a single request then provide
  21186. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  21187. * into `$http`.
  21188. *
  21189. * Note that if you provide these properties on the config object the default transformations will be
  21190. * overwritten. If you wish to augment the default transformations then you must include them in your
  21191. * local transformation array.
  21192. *
  21193. * The following code demonstrates adding a new response transformation to be run after the default response
  21194. * transformations have been run.
  21195. *
  21196. * ```js
  21197. * function appendTransform(defaults, transform) {
  21198. *
  21199. * // We can't guarantee that the default transformation is an array
  21200. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  21201. *
  21202. * // Append the new transformation to the defaults
  21203. * return defaults.concat(transform);
  21204. * }
  21205. *
  21206. * $http({
  21207. * url: '...',
  21208. * method: 'GET',
  21209. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  21210. * return doTransform(value);
  21211. * })
  21212. * });
  21213. * ```
  21214. *
  21215. *
  21216. * ## Caching
  21217. *
  21218. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  21219. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  21220. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  21221. * precedence over the default cache value.
  21222. *
  21223. * In order to:
  21224. * * cache all responses - set the default cache value to TRUE or to a cache object
  21225. * * cache a specific response - set config.cache value to TRUE or to a cache object
  21226. *
  21227. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  21228. * then the default `$cacheFactory($http)` object is used.
  21229. *
  21230. * The default cache value can be set by updating the
  21231. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  21232. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  21233. *
  21234. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  21235. * the relevant cache object. The next time the same request is made, the response is returned
  21236. * from the cache without sending a request to the server.
  21237. *
  21238. * Take note that:
  21239. *
  21240. * * Only GET and JSONP requests are cached.
  21241. * * The cache key is the request URL including search parameters; headers are not considered.
  21242. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  21243. * * If multiple identical requests are made using the same cache, which is not yet populated,
  21244. * one request will be made to the server and remaining requests will return the same response.
  21245. * * A cache-control header on the response does not affect if or how responses are cached.
  21246. *
  21247. *
  21248. * ## Interceptors
  21249. *
  21250. * Before you start creating interceptors, be sure to understand the
  21251. * {@link ng.$q $q and deferred/promise APIs}.
  21252. *
  21253. * For purposes of global error handling, authentication, or any kind of synchronous or
  21254. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  21255. * able to intercept requests before they are handed to the server and
  21256. * responses before they are handed over to the application code that
  21257. * initiated these requests. The interceptors leverage the {@link ng.$q
  21258. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  21259. *
  21260. * The interceptors are service factories that are registered with the `$httpProvider` by
  21261. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  21262. * injected with dependencies (if specified) and returns the interceptor.
  21263. *
  21264. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  21265. *
  21266. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  21267. * modify the `config` object or create a new one. The function needs to return the `config`
  21268. * object directly, or a promise containing the `config` or a new `config` object.
  21269. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  21270. * resolved with a rejection.
  21271. * * `response`: interceptors get called with http `response` object. The function is free to
  21272. * modify the `response` object or create a new one. The function needs to return the `response`
  21273. * object directly, or as a promise containing the `response` or a new `response` object.
  21274. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  21275. * resolved with a rejection.
  21276. *
  21277. *
  21278. * ```js
  21279. * // register the interceptor as a service
  21280. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  21281. * return {
  21282. * // optional method
  21283. * 'request': function(config) {
  21284. * // do something on success
  21285. * return config;
  21286. * },
  21287. *
  21288. * // optional method
  21289. * 'requestError': function(rejection) {
  21290. * // do something on error
  21291. * if (canRecover(rejection)) {
  21292. * return responseOrNewPromise
  21293. * }
  21294. * return $q.reject(rejection);
  21295. * },
  21296. *
  21297. *
  21298. *
  21299. * // optional method
  21300. * 'response': function(response) {
  21301. * // do something on success
  21302. * return response;
  21303. * },
  21304. *
  21305. * // optional method
  21306. * 'responseError': function(rejection) {
  21307. * // do something on error
  21308. * if (canRecover(rejection)) {
  21309. * return responseOrNewPromise
  21310. * }
  21311. * return $q.reject(rejection);
  21312. * }
  21313. * };
  21314. * });
  21315. *
  21316. * $httpProvider.interceptors.push('myHttpInterceptor');
  21317. *
  21318. *
  21319. * // alternatively, register the interceptor via an anonymous factory
  21320. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  21321. * return {
  21322. * 'request': function(config) {
  21323. * // same as above
  21324. * },
  21325. *
  21326. * 'response': function(response) {
  21327. * // same as above
  21328. * }
  21329. * };
  21330. * });
  21331. * ```
  21332. *
  21333. * ## Security Considerations
  21334. *
  21335. * When designing web applications, consider security threats from:
  21336. *
  21337. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  21338. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  21339. *
  21340. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  21341. * pre-configured with strategies that address these issues, but for this to work backend server
  21342. * cooperation is required.
  21343. *
  21344. * ### JSON Vulnerability Protection
  21345. *
  21346. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  21347. * allows third party website to turn your JSON resource URL into
  21348. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  21349. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  21350. * Angular will automatically strip the prefix before processing it as JSON.
  21351. *
  21352. * For example if your server needs to return:
  21353. * ```js
  21354. * ['one','two']
  21355. * ```
  21356. *
  21357. * which is vulnerable to attack, your server can return:
  21358. * ```js
  21359. * )]}',
  21360. * ['one','two']
  21361. * ```
  21362. *
  21363. * Angular will strip the prefix, before processing the JSON.
  21364. *
  21365. *
  21366. * ### Cross Site Request Forgery (XSRF) Protection
  21367. *
  21368. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  21369. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  21370. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  21371. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  21372. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  21373. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  21374. * The header will not be set for cross-domain requests.
  21375. *
  21376. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  21377. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  21378. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  21379. * that only JavaScript running on your domain could have sent the request. The token must be
  21380. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  21381. * making up its own tokens). We recommend that the token is a digest of your site's
  21382. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  21383. * for added security.
  21384. *
  21385. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  21386. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  21387. * or the per-request config object.
  21388. *
  21389. * In order to prevent collisions in environments where multiple Angular apps share the
  21390. * same domain or subdomain, we recommend that each application uses unique cookie name.
  21391. *
  21392. * @param {object} config Object describing the request to be made and how it should be
  21393. * processed. The object has following properties:
  21394. *
  21395. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  21396. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  21397. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  21398. * with the `paramSerializer` and appended as GET parameters.
  21399. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  21400. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  21401. * HTTP headers to send to the server. If the return value of a function is null, the
  21402. * header will not be sent. Functions accept a config object as an argument.
  21403. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  21404. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  21405. * - **transformRequest** –
  21406. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  21407. * transform function or an array of such functions. The transform function takes the http
  21408. * request body and headers and returns its transformed (typically serialized) version.
  21409. * See {@link ng.$http#overriding-the-default-transformations-per-request
  21410. * Overriding the Default Transformations}
  21411. * - **transformResponse** –
  21412. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  21413. * transform function or an array of such functions. The transform function takes the http
  21414. * response body, headers and status and returns its transformed (typically deserialized) version.
  21415. * See {@link ng.$http#overriding-the-default-transformations-per-request
  21416. * Overriding the Default Transformations}
  21417. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  21418. * prepare the string representation of request parameters (specified as an object).
  21419. * If specified as string, it is interpreted as function registered with the
  21420. * {@link $injector $injector}, which means you can create your own serializer
  21421. * by registering it as a {@link auto.$provide#service service}.
  21422. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  21423. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  21424. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  21425. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  21426. * See {@link $http#caching $http Caching} for more information.
  21427. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  21428. * that should abort the request when resolved.
  21429. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  21430. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  21431. * for more information.
  21432. * - **responseType** - `{string}` - see
  21433. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  21434. *
  21435. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  21436. * when the request succeeds or fails.
  21437. *
  21438. *
  21439. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  21440. * requests. This is primarily meant to be used for debugging purposes.
  21441. *
  21442. *
  21443. * @example
  21444. <example module="httpExample">
  21445. <file name="index.html">
  21446. <div ng-controller="FetchController">
  21447. <select ng-model="method" aria-label="Request method">
  21448. <option>GET</option>
  21449. <option>JSONP</option>
  21450. </select>
  21451. <input type="text" ng-model="url" size="80" aria-label="URL" />
  21452. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  21453. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  21454. <button id="samplejsonpbtn"
  21455. ng-click="updateModel('JSONP',
  21456. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  21457. Sample JSONP
  21458. </button>
  21459. <button id="invalidjsonpbtn"
  21460. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  21461. Invalid JSONP
  21462. </button>
  21463. <pre>http status code: {{status}}</pre>
  21464. <pre>http response data: {{data}}</pre>
  21465. </div>
  21466. </file>
  21467. <file name="script.js">
  21468. angular.module('httpExample', [])
  21469. .controller('FetchController', ['$scope', '$http', '$templateCache',
  21470. function($scope, $http, $templateCache) {
  21471. $scope.method = 'GET';
  21472. $scope.url = 'http-hello.html';
  21473. $scope.fetch = function() {
  21474. $scope.code = null;
  21475. $scope.response = null;
  21476. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  21477. then(function(response) {
  21478. $scope.status = response.status;
  21479. $scope.data = response.data;
  21480. }, function(response) {
  21481. $scope.data = response.data || "Request failed";
  21482. $scope.status = response.status;
  21483. });
  21484. };
  21485. $scope.updateModel = function(method, url) {
  21486. $scope.method = method;
  21487. $scope.url = url;
  21488. };
  21489. }]);
  21490. </file>
  21491. <file name="http-hello.html">
  21492. Hello, $http!
  21493. </file>
  21494. <file name="protractor.js" type="protractor">
  21495. var status = element(by.binding('status'));
  21496. var data = element(by.binding('data'));
  21497. var fetchBtn = element(by.id('fetchbtn'));
  21498. var sampleGetBtn = element(by.id('samplegetbtn'));
  21499. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  21500. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  21501. it('should make an xhr GET request', function() {
  21502. sampleGetBtn.click();
  21503. fetchBtn.click();
  21504. expect(status.getText()).toMatch('200');
  21505. expect(data.getText()).toMatch(/Hello, \$http!/);
  21506. });
  21507. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  21508. // it('should make a JSONP request to angularjs.org', function() {
  21509. // sampleJsonpBtn.click();
  21510. // fetchBtn.click();
  21511. // expect(status.getText()).toMatch('200');
  21512. // expect(data.getText()).toMatch(/Super Hero!/);
  21513. // });
  21514. it('should make JSONP request to invalid URL and invoke the error handler',
  21515. function() {
  21516. invalidJsonpBtn.click();
  21517. fetchBtn.click();
  21518. expect(status.getText()).toMatch('0');
  21519. expect(data.getText()).toMatch('Request failed');
  21520. });
  21521. </file>
  21522. </example>
  21523. */
  21524. function $http(requestConfig) {
  21525. if (!isObject(requestConfig)) {
  21526. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  21527. }
  21528. if (!isString(requestConfig.url)) {
  21529. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  21530. }
  21531. var config = extend({
  21532. method: 'get',
  21533. transformRequest: defaults.transformRequest,
  21534. transformResponse: defaults.transformResponse,
  21535. paramSerializer: defaults.paramSerializer
  21536. }, requestConfig);
  21537. config.headers = mergeHeaders(requestConfig);
  21538. config.method = uppercase(config.method);
  21539. config.paramSerializer = isString(config.paramSerializer) ?
  21540. $injector.get(config.paramSerializer) : config.paramSerializer;
  21541. var serverRequest = function(config) {
  21542. var headers = config.headers;
  21543. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  21544. // strip content-type if data is undefined
  21545. if (isUndefined(reqData)) {
  21546. forEach(headers, function(value, header) {
  21547. if (lowercase(header) === 'content-type') {
  21548. delete headers[header];
  21549. }
  21550. });
  21551. }
  21552. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  21553. config.withCredentials = defaults.withCredentials;
  21554. }
  21555. // send request
  21556. return sendReq(config, reqData).then(transformResponse, transformResponse);
  21557. };
  21558. var chain = [serverRequest, undefined];
  21559. var promise = $q.when(config);
  21560. // apply interceptors
  21561. forEach(reversedInterceptors, function(interceptor) {
  21562. if (interceptor.request || interceptor.requestError) {
  21563. chain.unshift(interceptor.request, interceptor.requestError);
  21564. }
  21565. if (interceptor.response || interceptor.responseError) {
  21566. chain.push(interceptor.response, interceptor.responseError);
  21567. }
  21568. });
  21569. while (chain.length) {
  21570. var thenFn = chain.shift();
  21571. var rejectFn = chain.shift();
  21572. promise = promise.then(thenFn, rejectFn);
  21573. }
  21574. if (useLegacyPromise) {
  21575. promise.success = function(fn) {
  21576. assertArgFn(fn, 'fn');
  21577. promise.then(function(response) {
  21578. fn(response.data, response.status, response.headers, config);
  21579. });
  21580. return promise;
  21581. };
  21582. promise.error = function(fn) {
  21583. assertArgFn(fn, 'fn');
  21584. promise.then(null, function(response) {
  21585. fn(response.data, response.status, response.headers, config);
  21586. });
  21587. return promise;
  21588. };
  21589. } else {
  21590. promise.success = $httpMinErrLegacyFn('success');
  21591. promise.error = $httpMinErrLegacyFn('error');
  21592. }
  21593. return promise;
  21594. function transformResponse(response) {
  21595. // make a copy since the response must be cacheable
  21596. var resp = extend({}, response);
  21597. resp.data = transformData(response.data, response.headers, response.status,
  21598. config.transformResponse);
  21599. return (isSuccess(response.status))
  21600. ? resp
  21601. : $q.reject(resp);
  21602. }
  21603. function executeHeaderFns(headers, config) {
  21604. var headerContent, processedHeaders = {};
  21605. forEach(headers, function(headerFn, header) {
  21606. if (isFunction(headerFn)) {
  21607. headerContent = headerFn(config);
  21608. if (headerContent != null) {
  21609. processedHeaders[header] = headerContent;
  21610. }
  21611. } else {
  21612. processedHeaders[header] = headerFn;
  21613. }
  21614. });
  21615. return processedHeaders;
  21616. }
  21617. function mergeHeaders(config) {
  21618. var defHeaders = defaults.headers,
  21619. reqHeaders = extend({}, config.headers),
  21620. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  21621. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  21622. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  21623. defaultHeadersIteration:
  21624. for (defHeaderName in defHeaders) {
  21625. lowercaseDefHeaderName = lowercase(defHeaderName);
  21626. for (reqHeaderName in reqHeaders) {
  21627. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  21628. continue defaultHeadersIteration;
  21629. }
  21630. }
  21631. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  21632. }
  21633. // execute if header value is a function for merged headers
  21634. return executeHeaderFns(reqHeaders, shallowCopy(config));
  21635. }
  21636. }
  21637. $http.pendingRequests = [];
  21638. /**
  21639. * @ngdoc method
  21640. * @name $http#get
  21641. *
  21642. * @description
  21643. * Shortcut method to perform `GET` request.
  21644. *
  21645. * @param {string} url Relative or absolute URL specifying the destination of the request
  21646. * @param {Object=} config Optional configuration object
  21647. * @returns {HttpPromise} Future object
  21648. */
  21649. /**
  21650. * @ngdoc method
  21651. * @name $http#delete
  21652. *
  21653. * @description
  21654. * Shortcut method to perform `DELETE` request.
  21655. *
  21656. * @param {string} url Relative or absolute URL specifying the destination of the request
  21657. * @param {Object=} config Optional configuration object
  21658. * @returns {HttpPromise} Future object
  21659. */
  21660. /**
  21661. * @ngdoc method
  21662. * @name $http#head
  21663. *
  21664. * @description
  21665. * Shortcut method to perform `HEAD` request.
  21666. *
  21667. * @param {string} url Relative or absolute URL specifying the destination of the request
  21668. * @param {Object=} config Optional configuration object
  21669. * @returns {HttpPromise} Future object
  21670. */
  21671. /**
  21672. * @ngdoc method
  21673. * @name $http#jsonp
  21674. *
  21675. * @description
  21676. * Shortcut method to perform `JSONP` request.
  21677. *
  21678. * @param {string} url Relative or absolute URL specifying the destination of the request.
  21679. * The name of the callback should be the string `JSON_CALLBACK`.
  21680. * @param {Object=} config Optional configuration object
  21681. * @returns {HttpPromise} Future object
  21682. */
  21683. createShortMethods('get', 'delete', 'head', 'jsonp');
  21684. /**
  21685. * @ngdoc method
  21686. * @name $http#post
  21687. *
  21688. * @description
  21689. * Shortcut method to perform `POST` request.
  21690. *
  21691. * @param {string} url Relative or absolute URL specifying the destination of the request
  21692. * @param {*} data Request content
  21693. * @param {Object=} config Optional configuration object
  21694. * @returns {HttpPromise} Future object
  21695. */
  21696. /**
  21697. * @ngdoc method
  21698. * @name $http#put
  21699. *
  21700. * @description
  21701. * Shortcut method to perform `PUT` request.
  21702. *
  21703. * @param {string} url Relative or absolute URL specifying the destination of the request
  21704. * @param {*} data Request content
  21705. * @param {Object=} config Optional configuration object
  21706. * @returns {HttpPromise} Future object
  21707. */
  21708. /**
  21709. * @ngdoc method
  21710. * @name $http#patch
  21711. *
  21712. * @description
  21713. * Shortcut method to perform `PATCH` request.
  21714. *
  21715. * @param {string} url Relative or absolute URL specifying the destination of the request
  21716. * @param {*} data Request content
  21717. * @param {Object=} config Optional configuration object
  21718. * @returns {HttpPromise} Future object
  21719. */
  21720. createShortMethodsWithData('post', 'put', 'patch');
  21721. /**
  21722. * @ngdoc property
  21723. * @name $http#defaults
  21724. *
  21725. * @description
  21726. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  21727. * default headers, withCredentials as well as request and response transformations.
  21728. *
  21729. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  21730. */
  21731. $http.defaults = defaults;
  21732. return $http;
  21733. function createShortMethods(names) {
  21734. forEach(arguments, function(name) {
  21735. $http[name] = function(url, config) {
  21736. return $http(extend({}, config || {}, {
  21737. method: name,
  21738. url: url
  21739. }));
  21740. };
  21741. });
  21742. }
  21743. function createShortMethodsWithData(name) {
  21744. forEach(arguments, function(name) {
  21745. $http[name] = function(url, data, config) {
  21746. return $http(extend({}, config || {}, {
  21747. method: name,
  21748. url: url,
  21749. data: data
  21750. }));
  21751. };
  21752. });
  21753. }
  21754. /**
  21755. * Makes the request.
  21756. *
  21757. * !!! ACCESSES CLOSURE VARS:
  21758. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  21759. */
  21760. function sendReq(config, reqData) {
  21761. var deferred = $q.defer(),
  21762. promise = deferred.promise,
  21763. cache,
  21764. cachedResp,
  21765. reqHeaders = config.headers,
  21766. url = buildUrl(config.url, config.paramSerializer(config.params));
  21767. $http.pendingRequests.push(config);
  21768. promise.then(removePendingReq, removePendingReq);
  21769. if ((config.cache || defaults.cache) && config.cache !== false &&
  21770. (config.method === 'GET' || config.method === 'JSONP')) {
  21771. cache = isObject(config.cache) ? config.cache
  21772. : isObject(defaults.cache) ? defaults.cache
  21773. : defaultCache;
  21774. }
  21775. if (cache) {
  21776. cachedResp = cache.get(url);
  21777. if (isDefined(cachedResp)) {
  21778. if (isPromiseLike(cachedResp)) {
  21779. // cached request has already been sent, but there is no response yet
  21780. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  21781. } else {
  21782. // serving from cache
  21783. if (isArray(cachedResp)) {
  21784. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  21785. } else {
  21786. resolvePromise(cachedResp, 200, {}, 'OK');
  21787. }
  21788. }
  21789. } else {
  21790. // put the promise for the non-transformed response into cache as a placeholder
  21791. cache.put(url, promise);
  21792. }
  21793. }
  21794. // if we won't have the response in cache, set the xsrf headers and
  21795. // send the request to the backend
  21796. if (isUndefined(cachedResp)) {
  21797. var xsrfValue = urlIsSameOrigin(config.url)
  21798. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  21799. : undefined;
  21800. if (xsrfValue) {
  21801. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  21802. }
  21803. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  21804. config.withCredentials, config.responseType);
  21805. }
  21806. return promise;
  21807. /**
  21808. * Callback registered to $httpBackend():
  21809. * - caches the response if desired
  21810. * - resolves the raw $http promise
  21811. * - calls $apply
  21812. */
  21813. function done(status, response, headersString, statusText) {
  21814. if (cache) {
  21815. if (isSuccess(status)) {
  21816. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  21817. } else {
  21818. // remove promise from the cache
  21819. cache.remove(url);
  21820. }
  21821. }
  21822. function resolveHttpPromise() {
  21823. resolvePromise(response, status, headersString, statusText);
  21824. }
  21825. if (useApplyAsync) {
  21826. $rootScope.$applyAsync(resolveHttpPromise);
  21827. } else {
  21828. resolveHttpPromise();
  21829. if (!$rootScope.$$phase) $rootScope.$apply();
  21830. }
  21831. }
  21832. /**
  21833. * Resolves the raw $http promise.
  21834. */
  21835. function resolvePromise(response, status, headers, statusText) {
  21836. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  21837. status = status >= -1 ? status : 0;
  21838. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  21839. data: response,
  21840. status: status,
  21841. headers: headersGetter(headers),
  21842. config: config,
  21843. statusText: statusText
  21844. });
  21845. }
  21846. function resolvePromiseWithResult(result) {
  21847. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  21848. }
  21849. function removePendingReq() {
  21850. var idx = $http.pendingRequests.indexOf(config);
  21851. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  21852. }
  21853. }
  21854. function buildUrl(url, serializedParams) {
  21855. if (serializedParams.length > 0) {
  21856. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  21857. }
  21858. return url;
  21859. }
  21860. }];
  21861. }
  21862. /**
  21863. * @ngdoc service
  21864. * @name $xhrFactory
  21865. *
  21866. * @description
  21867. * Factory function used to create XMLHttpRequest objects.
  21868. *
  21869. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  21870. *
  21871. * ```
  21872. * angular.module('myApp', [])
  21873. * .factory('$xhrFactory', function() {
  21874. * return function createXhr(method, url) {
  21875. * return new window.XMLHttpRequest({mozSystem: true});
  21876. * };
  21877. * });
  21878. * ```
  21879. *
  21880. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  21881. * @param {string} url URL of the request.
  21882. */
  21883. function $xhrFactoryProvider() {
  21884. this.$get = function() {
  21885. return function createXhr() {
  21886. return new window.XMLHttpRequest();
  21887. };
  21888. };
  21889. }
  21890. /**
  21891. * @ngdoc service
  21892. * @name $httpBackend
  21893. * @requires $window
  21894. * @requires $document
  21895. * @requires $xhrFactory
  21896. *
  21897. * @description
  21898. * HTTP backend used by the {@link ng.$http service} that delegates to
  21899. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  21900. *
  21901. * You should never need to use this service directly, instead use the higher-level abstractions:
  21902. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  21903. *
  21904. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  21905. * $httpBackend} which can be trained with responses.
  21906. */
  21907. function $HttpBackendProvider() {
  21908. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  21909. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  21910. }];
  21911. }
  21912. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  21913. // TODO(vojta): fix the signature
  21914. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  21915. $browser.$$incOutstandingRequestCount();
  21916. url = url || $browser.url();
  21917. if (lowercase(method) == 'jsonp') {
  21918. var callbackId = '_' + (callbacks.counter++).toString(36);
  21919. callbacks[callbackId] = function(data) {
  21920. callbacks[callbackId].data = data;
  21921. callbacks[callbackId].called = true;
  21922. };
  21923. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  21924. callbackId, function(status, text) {
  21925. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  21926. callbacks[callbackId] = noop;
  21927. });
  21928. } else {
  21929. var xhr = createXhr(method, url);
  21930. xhr.open(method, url, true);
  21931. forEach(headers, function(value, key) {
  21932. if (isDefined(value)) {
  21933. xhr.setRequestHeader(key, value);
  21934. }
  21935. });
  21936. xhr.onload = function requestLoaded() {
  21937. var statusText = xhr.statusText || '';
  21938. // responseText is the old-school way of retrieving response (supported by IE9)
  21939. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  21940. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  21941. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  21942. var status = xhr.status === 1223 ? 204 : xhr.status;
  21943. // fix status code when it is 0 (0 status is undocumented).
  21944. // Occurs when accessing file resources or on Android 4.1 stock browser
  21945. // while retrieving files from application cache.
  21946. if (status === 0) {
  21947. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  21948. }
  21949. completeRequest(callback,
  21950. status,
  21951. response,
  21952. xhr.getAllResponseHeaders(),
  21953. statusText);
  21954. };
  21955. var requestError = function() {
  21956. // The response is always empty
  21957. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  21958. completeRequest(callback, -1, null, null, '');
  21959. };
  21960. xhr.onerror = requestError;
  21961. xhr.onabort = requestError;
  21962. if (withCredentials) {
  21963. xhr.withCredentials = true;
  21964. }
  21965. if (responseType) {
  21966. try {
  21967. xhr.responseType = responseType;
  21968. } catch (e) {
  21969. // WebKit added support for the json responseType value on 09/03/2013
  21970. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  21971. // known to throw when setting the value "json" as the response type. Other older
  21972. // browsers implementing the responseType
  21973. //
  21974. // The json response type can be ignored if not supported, because JSON payloads are
  21975. // parsed on the client-side regardless.
  21976. if (responseType !== 'json') {
  21977. throw e;
  21978. }
  21979. }
  21980. }
  21981. xhr.send(isUndefined(post) ? null : post);
  21982. }
  21983. if (timeout > 0) {
  21984. var timeoutId = $browserDefer(timeoutRequest, timeout);
  21985. } else if (isPromiseLike(timeout)) {
  21986. timeout.then(timeoutRequest);
  21987. }
  21988. function timeoutRequest() {
  21989. jsonpDone && jsonpDone();
  21990. xhr && xhr.abort();
  21991. }
  21992. function completeRequest(callback, status, response, headersString, statusText) {
  21993. // cancel timeout and subsequent timeout promise resolution
  21994. if (isDefined(timeoutId)) {
  21995. $browserDefer.cancel(timeoutId);
  21996. }
  21997. jsonpDone = xhr = null;
  21998. callback(status, response, headersString, statusText);
  21999. $browser.$$completeOutstandingRequest(noop);
  22000. }
  22001. };
  22002. function jsonpReq(url, callbackId, done) {
  22003. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  22004. // - fetches local scripts via XHR and evals them
  22005. // - adds and immediately removes script elements from the document
  22006. var script = rawDocument.createElement('script'), callback = null;
  22007. script.type = "text/javascript";
  22008. script.src = url;
  22009. script.async = true;
  22010. callback = function(event) {
  22011. removeEventListenerFn(script, "load", callback);
  22012. removeEventListenerFn(script, "error", callback);
  22013. rawDocument.body.removeChild(script);
  22014. script = null;
  22015. var status = -1;
  22016. var text = "unknown";
  22017. if (event) {
  22018. if (event.type === "load" && !callbacks[callbackId].called) {
  22019. event = { type: "error" };
  22020. }
  22021. text = event.type;
  22022. status = event.type === "error" ? 404 : 200;
  22023. }
  22024. if (done) {
  22025. done(status, text);
  22026. }
  22027. };
  22028. addEventListenerFn(script, "load", callback);
  22029. addEventListenerFn(script, "error", callback);
  22030. rawDocument.body.appendChild(script);
  22031. return callback;
  22032. }
  22033. }
  22034. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  22035. $interpolateMinErr.throwNoconcat = function(text) {
  22036. throw $interpolateMinErr('noconcat',
  22037. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  22038. "interpolations that concatenate multiple expressions when a trusted value is " +
  22039. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  22040. };
  22041. $interpolateMinErr.interr = function(text, err) {
  22042. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  22043. };
  22044. /**
  22045. * @ngdoc provider
  22046. * @name $interpolateProvider
  22047. *
  22048. * @description
  22049. *
  22050. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  22051. *
  22052. * <div class="alert alert-danger">
  22053. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  22054. * template within a Python Jinja template (or any other template language). Mixing templating
  22055. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  22056. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  22057. * security bugs!
  22058. * </div>
  22059. *
  22060. * @example
  22061. <example name="custom-interpolation-markup" module="customInterpolationApp">
  22062. <file name="index.html">
  22063. <script>
  22064. var customInterpolationApp = angular.module('customInterpolationApp', []);
  22065. customInterpolationApp.config(function($interpolateProvider) {
  22066. $interpolateProvider.startSymbol('//');
  22067. $interpolateProvider.endSymbol('//');
  22068. });
  22069. customInterpolationApp.controller('DemoController', function() {
  22070. this.label = "This binding is brought you by // interpolation symbols.";
  22071. });
  22072. </script>
  22073. <div ng-controller="DemoController as demo">
  22074. //demo.label//
  22075. </div>
  22076. </file>
  22077. <file name="protractor.js" type="protractor">
  22078. it('should interpolate binding with custom symbols', function() {
  22079. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  22080. });
  22081. </file>
  22082. </example>
  22083. */
  22084. function $InterpolateProvider() {
  22085. var startSymbol = '{{';
  22086. var endSymbol = '}}';
  22087. /**
  22088. * @ngdoc method
  22089. * @name $interpolateProvider#startSymbol
  22090. * @description
  22091. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  22092. *
  22093. * @param {string=} value new value to set the starting symbol to.
  22094. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  22095. */
  22096. this.startSymbol = function(value) {
  22097. if (value) {
  22098. startSymbol = value;
  22099. return this;
  22100. } else {
  22101. return startSymbol;
  22102. }
  22103. };
  22104. /**
  22105. * @ngdoc method
  22106. * @name $interpolateProvider#endSymbol
  22107. * @description
  22108. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  22109. *
  22110. * @param {string=} value new value to set the ending symbol to.
  22111. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  22112. */
  22113. this.endSymbol = function(value) {
  22114. if (value) {
  22115. endSymbol = value;
  22116. return this;
  22117. } else {
  22118. return endSymbol;
  22119. }
  22120. };
  22121. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  22122. var startSymbolLength = startSymbol.length,
  22123. endSymbolLength = endSymbol.length,
  22124. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  22125. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  22126. function escape(ch) {
  22127. return '\\\\\\' + ch;
  22128. }
  22129. function unescapeText(text) {
  22130. return text.replace(escapedStartRegexp, startSymbol).
  22131. replace(escapedEndRegexp, endSymbol);
  22132. }
  22133. function stringify(value) {
  22134. if (value == null) { // null || undefined
  22135. return '';
  22136. }
  22137. switch (typeof value) {
  22138. case 'string':
  22139. break;
  22140. case 'number':
  22141. value = '' + value;
  22142. break;
  22143. default:
  22144. value = toJson(value);
  22145. }
  22146. return value;
  22147. }
  22148. //TODO: this is the same as the constantWatchDelegate in parse.js
  22149. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  22150. var unwatch;
  22151. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  22152. unwatch();
  22153. return constantInterp(scope);
  22154. }, listener, objectEquality);
  22155. }
  22156. /**
  22157. * @ngdoc service
  22158. * @name $interpolate
  22159. * @kind function
  22160. *
  22161. * @requires $parse
  22162. * @requires $sce
  22163. *
  22164. * @description
  22165. *
  22166. * Compiles a string with markup into an interpolation function. This service is used by the
  22167. * HTML {@link ng.$compile $compile} service for data binding. See
  22168. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  22169. * interpolation markup.
  22170. *
  22171. *
  22172. * ```js
  22173. * var $interpolate = ...; // injected
  22174. * var exp = $interpolate('Hello {{name | uppercase}}!');
  22175. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  22176. * ```
  22177. *
  22178. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  22179. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  22180. * evaluate to a value other than `undefined`.
  22181. *
  22182. * ```js
  22183. * var $interpolate = ...; // injected
  22184. * var context = {greeting: 'Hello', name: undefined };
  22185. *
  22186. * // default "forgiving" mode
  22187. * var exp = $interpolate('{{greeting}} {{name}}!');
  22188. * expect(exp(context)).toEqual('Hello !');
  22189. *
  22190. * // "allOrNothing" mode
  22191. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  22192. * expect(exp(context)).toBeUndefined();
  22193. * context.name = 'Angular';
  22194. * expect(exp(context)).toEqual('Hello Angular!');
  22195. * ```
  22196. *
  22197. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  22198. *
  22199. * ####Escaped Interpolation
  22200. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  22201. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  22202. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  22203. * or binding.
  22204. *
  22205. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  22206. * degree, while also enabling code examples to work without relying on the
  22207. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  22208. *
  22209. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  22210. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  22211. * interpolation start/end markers with their escaped counterparts.**
  22212. *
  22213. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  22214. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  22215. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  22216. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  22217. * this is typically useful only when user-data is used in rendering a template from the server, or
  22218. * when otherwise untrusted data is used by a directive.
  22219. *
  22220. * <example>
  22221. * <file name="index.html">
  22222. * <div ng-init="username='A user'">
  22223. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  22224. * </p>
  22225. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  22226. * application, but fails to accomplish their task, because the server has correctly
  22227. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  22228. * characters.</p>
  22229. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  22230. * from the database by an administrator.</p>
  22231. * </div>
  22232. * </file>
  22233. * </example>
  22234. *
  22235. * @param {string} text The text with markup to interpolate.
  22236. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  22237. * embedded expression in order to return an interpolation function. Strings with no
  22238. * embedded expression will return null for the interpolation function.
  22239. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  22240. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  22241. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  22242. * provides Strict Contextual Escaping for details.
  22243. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  22244. * unless all embedded expressions evaluate to a value other than `undefined`.
  22245. * @returns {function(context)} an interpolation function which is used to compute the
  22246. * interpolated string. The function has these parameters:
  22247. *
  22248. * - `context`: evaluation context for all expressions embedded in the interpolated text
  22249. */
  22250. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  22251. // Provide a quick exit and simplified result function for text with no interpolation
  22252. if (!text.length || text.indexOf(startSymbol) === -1) {
  22253. var constantInterp;
  22254. if (!mustHaveExpression) {
  22255. var unescapedText = unescapeText(text);
  22256. constantInterp = valueFn(unescapedText);
  22257. constantInterp.exp = text;
  22258. constantInterp.expressions = [];
  22259. constantInterp.$$watchDelegate = constantWatchDelegate;
  22260. }
  22261. return constantInterp;
  22262. }
  22263. allOrNothing = !!allOrNothing;
  22264. var startIndex,
  22265. endIndex,
  22266. index = 0,
  22267. expressions = [],
  22268. parseFns = [],
  22269. textLength = text.length,
  22270. exp,
  22271. concat = [],
  22272. expressionPositions = [];
  22273. while (index < textLength) {
  22274. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  22275. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  22276. if (index !== startIndex) {
  22277. concat.push(unescapeText(text.substring(index, startIndex)));
  22278. }
  22279. exp = text.substring(startIndex + startSymbolLength, endIndex);
  22280. expressions.push(exp);
  22281. parseFns.push($parse(exp, parseStringifyInterceptor));
  22282. index = endIndex + endSymbolLength;
  22283. expressionPositions.push(concat.length);
  22284. concat.push('');
  22285. } else {
  22286. // we did not find an interpolation, so we have to add the remainder to the separators array
  22287. if (index !== textLength) {
  22288. concat.push(unescapeText(text.substring(index)));
  22289. }
  22290. break;
  22291. }
  22292. }
  22293. // Concatenating expressions makes it hard to reason about whether some combination of
  22294. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  22295. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  22296. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  22297. // make it obvious that you bound the value to some user controlled value. This helps reduce
  22298. // the load when auditing for XSS issues.
  22299. if (trustedContext && concat.length > 1) {
  22300. $interpolateMinErr.throwNoconcat(text);
  22301. }
  22302. if (!mustHaveExpression || expressions.length) {
  22303. var compute = function(values) {
  22304. for (var i = 0, ii = expressions.length; i < ii; i++) {
  22305. if (allOrNothing && isUndefined(values[i])) return;
  22306. concat[expressionPositions[i]] = values[i];
  22307. }
  22308. return concat.join('');
  22309. };
  22310. var getValue = function(value) {
  22311. return trustedContext ?
  22312. $sce.getTrusted(trustedContext, value) :
  22313. $sce.valueOf(value);
  22314. };
  22315. return extend(function interpolationFn(context) {
  22316. var i = 0;
  22317. var ii = expressions.length;
  22318. var values = new Array(ii);
  22319. try {
  22320. for (; i < ii; i++) {
  22321. values[i] = parseFns[i](context);
  22322. }
  22323. return compute(values);
  22324. } catch (err) {
  22325. $exceptionHandler($interpolateMinErr.interr(text, err));
  22326. }
  22327. }, {
  22328. // all of these properties are undocumented for now
  22329. exp: text, //just for compatibility with regular watchers created via $watch
  22330. expressions: expressions,
  22331. $$watchDelegate: function(scope, listener) {
  22332. var lastValue;
  22333. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  22334. var currValue = compute(values);
  22335. if (isFunction(listener)) {
  22336. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  22337. }
  22338. lastValue = currValue;
  22339. });
  22340. }
  22341. });
  22342. }
  22343. function parseStringifyInterceptor(value) {
  22344. try {
  22345. value = getValue(value);
  22346. return allOrNothing && !isDefined(value) ? value : stringify(value);
  22347. } catch (err) {
  22348. $exceptionHandler($interpolateMinErr.interr(text, err));
  22349. }
  22350. }
  22351. }
  22352. /**
  22353. * @ngdoc method
  22354. * @name $interpolate#startSymbol
  22355. * @description
  22356. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  22357. *
  22358. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  22359. * the symbol.
  22360. *
  22361. * @returns {string} start symbol.
  22362. */
  22363. $interpolate.startSymbol = function() {
  22364. return startSymbol;
  22365. };
  22366. /**
  22367. * @ngdoc method
  22368. * @name $interpolate#endSymbol
  22369. * @description
  22370. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  22371. *
  22372. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  22373. * the symbol.
  22374. *
  22375. * @returns {string} end symbol.
  22376. */
  22377. $interpolate.endSymbol = function() {
  22378. return endSymbol;
  22379. };
  22380. return $interpolate;
  22381. }];
  22382. }
  22383. function $IntervalProvider() {
  22384. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  22385. function($rootScope, $window, $q, $$q, $browser) {
  22386. var intervals = {};
  22387. /**
  22388. * @ngdoc service
  22389. * @name $interval
  22390. *
  22391. * @description
  22392. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  22393. * milliseconds.
  22394. *
  22395. * The return value of registering an interval function is a promise. This promise will be
  22396. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  22397. * run indefinitely if `count` is not defined. The value of the notification will be the
  22398. * number of iterations that have run.
  22399. * To cancel an interval, call `$interval.cancel(promise)`.
  22400. *
  22401. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  22402. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  22403. * time.
  22404. *
  22405. * <div class="alert alert-warning">
  22406. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  22407. * with them. In particular they are not automatically destroyed when a controller's scope or a
  22408. * directive's element are destroyed.
  22409. * You should take this into consideration and make sure to always cancel the interval at the
  22410. * appropriate moment. See the example below for more details on how and when to do this.
  22411. * </div>
  22412. *
  22413. * @param {function()} fn A function that should be called repeatedly.
  22414. * @param {number} delay Number of milliseconds between each function call.
  22415. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  22416. * indefinitely.
  22417. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  22418. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  22419. * @param {...*=} Pass additional parameters to the executed function.
  22420. * @returns {promise} A promise which will be notified on each iteration.
  22421. *
  22422. * @example
  22423. * <example module="intervalExample">
  22424. * <file name="index.html">
  22425. * <script>
  22426. * angular.module('intervalExample', [])
  22427. * .controller('ExampleController', ['$scope', '$interval',
  22428. * function($scope, $interval) {
  22429. * $scope.format = 'M/d/yy h:mm:ss a';
  22430. * $scope.blood_1 = 100;
  22431. * $scope.blood_2 = 120;
  22432. *
  22433. * var stop;
  22434. * $scope.fight = function() {
  22435. * // Don't start a new fight if we are already fighting
  22436. * if ( angular.isDefined(stop) ) return;
  22437. *
  22438. * stop = $interval(function() {
  22439. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  22440. * $scope.blood_1 = $scope.blood_1 - 3;
  22441. * $scope.blood_2 = $scope.blood_2 - 4;
  22442. * } else {
  22443. * $scope.stopFight();
  22444. * }
  22445. * }, 100);
  22446. * };
  22447. *
  22448. * $scope.stopFight = function() {
  22449. * if (angular.isDefined(stop)) {
  22450. * $interval.cancel(stop);
  22451. * stop = undefined;
  22452. * }
  22453. * };
  22454. *
  22455. * $scope.resetFight = function() {
  22456. * $scope.blood_1 = 100;
  22457. * $scope.blood_2 = 120;
  22458. * };
  22459. *
  22460. * $scope.$on('$destroy', function() {
  22461. * // Make sure that the interval is destroyed too
  22462. * $scope.stopFight();
  22463. * });
  22464. * }])
  22465. * // Register the 'myCurrentTime' directive factory method.
  22466. * // We inject $interval and dateFilter service since the factory method is DI.
  22467. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  22468. * function($interval, dateFilter) {
  22469. * // return the directive link function. (compile function not needed)
  22470. * return function(scope, element, attrs) {
  22471. * var format, // date format
  22472. * stopTime; // so that we can cancel the time updates
  22473. *
  22474. * // used to update the UI
  22475. * function updateTime() {
  22476. * element.text(dateFilter(new Date(), format));
  22477. * }
  22478. *
  22479. * // watch the expression, and update the UI on change.
  22480. * scope.$watch(attrs.myCurrentTime, function(value) {
  22481. * format = value;
  22482. * updateTime();
  22483. * });
  22484. *
  22485. * stopTime = $interval(updateTime, 1000);
  22486. *
  22487. * // listen on DOM destroy (removal) event, and cancel the next UI update
  22488. * // to prevent updating time after the DOM element was removed.
  22489. * element.on('$destroy', function() {
  22490. * $interval.cancel(stopTime);
  22491. * });
  22492. * }
  22493. * }]);
  22494. * </script>
  22495. *
  22496. * <div>
  22497. * <div ng-controller="ExampleController">
  22498. * <label>Date format: <input ng-model="format"></label> <hr/>
  22499. * Current time is: <span my-current-time="format"></span>
  22500. * <hr/>
  22501. * Blood 1 : <font color='red'>{{blood_1}}</font>
  22502. * Blood 2 : <font color='red'>{{blood_2}}</font>
  22503. * <button type="button" data-ng-click="fight()">Fight</button>
  22504. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  22505. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  22506. * </div>
  22507. * </div>
  22508. *
  22509. * </file>
  22510. * </example>
  22511. */
  22512. function interval(fn, delay, count, invokeApply) {
  22513. var hasParams = arguments.length > 4,
  22514. args = hasParams ? sliceArgs(arguments, 4) : [],
  22515. setInterval = $window.setInterval,
  22516. clearInterval = $window.clearInterval,
  22517. iteration = 0,
  22518. skipApply = (isDefined(invokeApply) && !invokeApply),
  22519. deferred = (skipApply ? $$q : $q).defer(),
  22520. promise = deferred.promise;
  22521. count = isDefined(count) ? count : 0;
  22522. promise.$$intervalId = setInterval(function tick() {
  22523. if (skipApply) {
  22524. $browser.defer(callback);
  22525. } else {
  22526. $rootScope.$evalAsync(callback);
  22527. }
  22528. deferred.notify(iteration++);
  22529. if (count > 0 && iteration >= count) {
  22530. deferred.resolve(iteration);
  22531. clearInterval(promise.$$intervalId);
  22532. delete intervals[promise.$$intervalId];
  22533. }
  22534. if (!skipApply) $rootScope.$apply();
  22535. }, delay);
  22536. intervals[promise.$$intervalId] = deferred;
  22537. return promise;
  22538. function callback() {
  22539. if (!hasParams) {
  22540. fn(iteration);
  22541. } else {
  22542. fn.apply(null, args);
  22543. }
  22544. }
  22545. }
  22546. /**
  22547. * @ngdoc method
  22548. * @name $interval#cancel
  22549. *
  22550. * @description
  22551. * Cancels a task associated with the `promise`.
  22552. *
  22553. * @param {Promise=} promise returned by the `$interval` function.
  22554. * @returns {boolean} Returns `true` if the task was successfully canceled.
  22555. */
  22556. interval.cancel = function(promise) {
  22557. if (promise && promise.$$intervalId in intervals) {
  22558. intervals[promise.$$intervalId].reject('canceled');
  22559. $window.clearInterval(promise.$$intervalId);
  22560. delete intervals[promise.$$intervalId];
  22561. return true;
  22562. }
  22563. return false;
  22564. };
  22565. return interval;
  22566. }];
  22567. }
  22568. /**
  22569. * @ngdoc service
  22570. * @name $locale
  22571. *
  22572. * @description
  22573. * $locale service provides localization rules for various Angular components. As of right now the
  22574. * only public api is:
  22575. *
  22576. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  22577. */
  22578. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  22579. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  22580. var $locationMinErr = minErr('$location');
  22581. /**
  22582. * Encode path using encodeUriSegment, ignoring forward slashes
  22583. *
  22584. * @param {string} path Path to encode
  22585. * @returns {string}
  22586. */
  22587. function encodePath(path) {
  22588. var segments = path.split('/'),
  22589. i = segments.length;
  22590. while (i--) {
  22591. segments[i] = encodeUriSegment(segments[i]);
  22592. }
  22593. return segments.join('/');
  22594. }
  22595. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  22596. var parsedUrl = urlResolve(absoluteUrl);
  22597. locationObj.$$protocol = parsedUrl.protocol;
  22598. locationObj.$$host = parsedUrl.hostname;
  22599. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  22600. }
  22601. function parseAppUrl(relativeUrl, locationObj) {
  22602. var prefixed = (relativeUrl.charAt(0) !== '/');
  22603. if (prefixed) {
  22604. relativeUrl = '/' + relativeUrl;
  22605. }
  22606. var match = urlResolve(relativeUrl);
  22607. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  22608. match.pathname.substring(1) : match.pathname);
  22609. locationObj.$$search = parseKeyValue(match.search);
  22610. locationObj.$$hash = decodeURIComponent(match.hash);
  22611. // make sure path starts with '/';
  22612. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  22613. locationObj.$$path = '/' + locationObj.$$path;
  22614. }
  22615. }
  22616. /**
  22617. *
  22618. * @param {string} begin
  22619. * @param {string} whole
  22620. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  22621. * expected string.
  22622. */
  22623. function beginsWith(begin, whole) {
  22624. if (whole.indexOf(begin) === 0) {
  22625. return whole.substr(begin.length);
  22626. }
  22627. }
  22628. function stripHash(url) {
  22629. var index = url.indexOf('#');
  22630. return index == -1 ? url : url.substr(0, index);
  22631. }
  22632. function trimEmptyHash(url) {
  22633. return url.replace(/(#.+)|#$/, '$1');
  22634. }
  22635. function stripFile(url) {
  22636. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  22637. }
  22638. /* return the server only (scheme://host:port) */
  22639. function serverBase(url) {
  22640. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  22641. }
  22642. /**
  22643. * LocationHtml5Url represents an url
  22644. * This object is exposed as $location service when HTML5 mode is enabled and supported
  22645. *
  22646. * @constructor
  22647. * @param {string} appBase application base URL
  22648. * @param {string} appBaseNoFile application base URL stripped of any filename
  22649. * @param {string} basePrefix url path prefix
  22650. */
  22651. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  22652. this.$$html5 = true;
  22653. basePrefix = basePrefix || '';
  22654. parseAbsoluteUrl(appBase, this);
  22655. /**
  22656. * Parse given html5 (regular) url string into properties
  22657. * @param {string} url HTML5 url
  22658. * @private
  22659. */
  22660. this.$$parse = function(url) {
  22661. var pathUrl = beginsWith(appBaseNoFile, url);
  22662. if (!isString(pathUrl)) {
  22663. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  22664. appBaseNoFile);
  22665. }
  22666. parseAppUrl(pathUrl, this);
  22667. if (!this.$$path) {
  22668. this.$$path = '/';
  22669. }
  22670. this.$$compose();
  22671. };
  22672. /**
  22673. * Compose url and update `absUrl` property
  22674. * @private
  22675. */
  22676. this.$$compose = function() {
  22677. var search = toKeyValue(this.$$search),
  22678. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22679. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22680. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  22681. };
  22682. this.$$parseLinkUrl = function(url, relHref) {
  22683. if (relHref && relHref[0] === '#') {
  22684. // special case for links to hash fragments:
  22685. // keep the old url and only replace the hash fragment
  22686. this.hash(relHref.slice(1));
  22687. return true;
  22688. }
  22689. var appUrl, prevAppUrl;
  22690. var rewrittenUrl;
  22691. if (isDefined(appUrl = beginsWith(appBase, url))) {
  22692. prevAppUrl = appUrl;
  22693. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  22694. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  22695. } else {
  22696. rewrittenUrl = appBase + prevAppUrl;
  22697. }
  22698. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  22699. rewrittenUrl = appBaseNoFile + appUrl;
  22700. } else if (appBaseNoFile == url + '/') {
  22701. rewrittenUrl = appBaseNoFile;
  22702. }
  22703. if (rewrittenUrl) {
  22704. this.$$parse(rewrittenUrl);
  22705. }
  22706. return !!rewrittenUrl;
  22707. };
  22708. }
  22709. /**
  22710. * LocationHashbangUrl represents url
  22711. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  22712. * It also serves as the base class for html5 mode fallback on legacy browsers.
  22713. *
  22714. * @constructor
  22715. * @param {string} appBase application base URL
  22716. * @param {string} appBaseNoFile application base URL stripped of any filename
  22717. * @param {string} hashPrefix hashbang prefix
  22718. */
  22719. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  22720. parseAbsoluteUrl(appBase, this);
  22721. /**
  22722. * Parse given hashbang url into properties
  22723. * @param {string} url Hashbang url
  22724. * @private
  22725. */
  22726. this.$$parse = function(url) {
  22727. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  22728. var withoutHashUrl;
  22729. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  22730. // The rest of the url starts with a hash so we have
  22731. // got either a hashbang path or a plain hash fragment
  22732. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  22733. if (isUndefined(withoutHashUrl)) {
  22734. // There was no hashbang prefix so we just have a hash fragment
  22735. withoutHashUrl = withoutBaseUrl;
  22736. }
  22737. } else {
  22738. // There was no hashbang path nor hash fragment:
  22739. // If we are in HTML5 mode we use what is left as the path;
  22740. // Otherwise we ignore what is left
  22741. if (this.$$html5) {
  22742. withoutHashUrl = withoutBaseUrl;
  22743. } else {
  22744. withoutHashUrl = '';
  22745. if (isUndefined(withoutBaseUrl)) {
  22746. appBase = url;
  22747. this.replace();
  22748. }
  22749. }
  22750. }
  22751. parseAppUrl(withoutHashUrl, this);
  22752. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  22753. this.$$compose();
  22754. /*
  22755. * In Windows, on an anchor node on documents loaded from
  22756. * the filesystem, the browser will return a pathname
  22757. * prefixed with the drive name ('/C:/path') when a
  22758. * pathname without a drive is set:
  22759. * * a.setAttribute('href', '/foo')
  22760. * * a.pathname === '/C:/foo' //true
  22761. *
  22762. * Inside of Angular, we're always using pathnames that
  22763. * do not include drive names for routing.
  22764. */
  22765. function removeWindowsDriveName(path, url, base) {
  22766. /*
  22767. Matches paths for file protocol on windows,
  22768. such as /C:/foo/bar, and captures only /foo/bar.
  22769. */
  22770. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  22771. var firstPathSegmentMatch;
  22772. //Get the relative path from the input URL.
  22773. if (url.indexOf(base) === 0) {
  22774. url = url.replace(base, '');
  22775. }
  22776. // The input URL intentionally contains a first path segment that ends with a colon.
  22777. if (windowsFilePathExp.exec(url)) {
  22778. return path;
  22779. }
  22780. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  22781. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  22782. }
  22783. };
  22784. /**
  22785. * Compose hashbang url and update `absUrl` property
  22786. * @private
  22787. */
  22788. this.$$compose = function() {
  22789. var search = toKeyValue(this.$$search),
  22790. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22791. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22792. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  22793. };
  22794. this.$$parseLinkUrl = function(url, relHref) {
  22795. if (stripHash(appBase) == stripHash(url)) {
  22796. this.$$parse(url);
  22797. return true;
  22798. }
  22799. return false;
  22800. };
  22801. }
  22802. /**
  22803. * LocationHashbangUrl represents url
  22804. * This object is exposed as $location service when html5 history api is enabled but the browser
  22805. * does not support it.
  22806. *
  22807. * @constructor
  22808. * @param {string} appBase application base URL
  22809. * @param {string} appBaseNoFile application base URL stripped of any filename
  22810. * @param {string} hashPrefix hashbang prefix
  22811. */
  22812. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  22813. this.$$html5 = true;
  22814. LocationHashbangUrl.apply(this, arguments);
  22815. this.$$parseLinkUrl = function(url, relHref) {
  22816. if (relHref && relHref[0] === '#') {
  22817. // special case for links to hash fragments:
  22818. // keep the old url and only replace the hash fragment
  22819. this.hash(relHref.slice(1));
  22820. return true;
  22821. }
  22822. var rewrittenUrl;
  22823. var appUrl;
  22824. if (appBase == stripHash(url)) {
  22825. rewrittenUrl = url;
  22826. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  22827. rewrittenUrl = appBase + hashPrefix + appUrl;
  22828. } else if (appBaseNoFile === url + '/') {
  22829. rewrittenUrl = appBaseNoFile;
  22830. }
  22831. if (rewrittenUrl) {
  22832. this.$$parse(rewrittenUrl);
  22833. }
  22834. return !!rewrittenUrl;
  22835. };
  22836. this.$$compose = function() {
  22837. var search = toKeyValue(this.$$search),
  22838. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22839. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22840. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  22841. this.$$absUrl = appBase + hashPrefix + this.$$url;
  22842. };
  22843. }
  22844. var locationPrototype = {
  22845. /**
  22846. * Are we in html5 mode?
  22847. * @private
  22848. */
  22849. $$html5: false,
  22850. /**
  22851. * Has any change been replacing?
  22852. * @private
  22853. */
  22854. $$replace: false,
  22855. /**
  22856. * @ngdoc method
  22857. * @name $location#absUrl
  22858. *
  22859. * @description
  22860. * This method is getter only.
  22861. *
  22862. * Return full url representation with all segments encoded according to rules specified in
  22863. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  22864. *
  22865. *
  22866. * ```js
  22867. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22868. * var absUrl = $location.absUrl();
  22869. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  22870. * ```
  22871. *
  22872. * @return {string} full url
  22873. */
  22874. absUrl: locationGetter('$$absUrl'),
  22875. /**
  22876. * @ngdoc method
  22877. * @name $location#url
  22878. *
  22879. * @description
  22880. * This method is getter / setter.
  22881. *
  22882. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  22883. *
  22884. * Change path, search and hash, when called with parameter and return `$location`.
  22885. *
  22886. *
  22887. * ```js
  22888. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22889. * var url = $location.url();
  22890. * // => "/some/path?foo=bar&baz=xoxo"
  22891. * ```
  22892. *
  22893. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  22894. * @return {string} url
  22895. */
  22896. url: function(url) {
  22897. if (isUndefined(url)) {
  22898. return this.$$url;
  22899. }
  22900. var match = PATH_MATCH.exec(url);
  22901. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  22902. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  22903. this.hash(match[5] || '');
  22904. return this;
  22905. },
  22906. /**
  22907. * @ngdoc method
  22908. * @name $location#protocol
  22909. *
  22910. * @description
  22911. * This method is getter only.
  22912. *
  22913. * Return protocol of current url.
  22914. *
  22915. *
  22916. * ```js
  22917. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22918. * var protocol = $location.protocol();
  22919. * // => "http"
  22920. * ```
  22921. *
  22922. * @return {string} protocol of current url
  22923. */
  22924. protocol: locationGetter('$$protocol'),
  22925. /**
  22926. * @ngdoc method
  22927. * @name $location#host
  22928. *
  22929. * @description
  22930. * This method is getter only.
  22931. *
  22932. * Return host of current url.
  22933. *
  22934. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  22935. *
  22936. *
  22937. * ```js
  22938. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22939. * var host = $location.host();
  22940. * // => "example.com"
  22941. *
  22942. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  22943. * host = $location.host();
  22944. * // => "example.com"
  22945. * host = location.host;
  22946. * // => "example.com:8080"
  22947. * ```
  22948. *
  22949. * @return {string} host of current url.
  22950. */
  22951. host: locationGetter('$$host'),
  22952. /**
  22953. * @ngdoc method
  22954. * @name $location#port
  22955. *
  22956. * @description
  22957. * This method is getter only.
  22958. *
  22959. * Return port of current url.
  22960. *
  22961. *
  22962. * ```js
  22963. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22964. * var port = $location.port();
  22965. * // => 80
  22966. * ```
  22967. *
  22968. * @return {Number} port
  22969. */
  22970. port: locationGetter('$$port'),
  22971. /**
  22972. * @ngdoc method
  22973. * @name $location#path
  22974. *
  22975. * @description
  22976. * This method is getter / setter.
  22977. *
  22978. * Return path of current url when called without any parameter.
  22979. *
  22980. * Change path when called with parameter and return `$location`.
  22981. *
  22982. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  22983. * if it is missing.
  22984. *
  22985. *
  22986. * ```js
  22987. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22988. * var path = $location.path();
  22989. * // => "/some/path"
  22990. * ```
  22991. *
  22992. * @param {(string|number)=} path New path
  22993. * @return {string} path
  22994. */
  22995. path: locationGetterSetter('$$path', function(path) {
  22996. path = path !== null ? path.toString() : '';
  22997. return path.charAt(0) == '/' ? path : '/' + path;
  22998. }),
  22999. /**
  23000. * @ngdoc method
  23001. * @name $location#search
  23002. *
  23003. * @description
  23004. * This method is getter / setter.
  23005. *
  23006. * Return search part (as object) of current url when called without any parameter.
  23007. *
  23008. * Change search part when called with parameter and return `$location`.
  23009. *
  23010. *
  23011. * ```js
  23012. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  23013. * var searchObject = $location.search();
  23014. * // => {foo: 'bar', baz: 'xoxo'}
  23015. *
  23016. * // set foo to 'yipee'
  23017. * $location.search('foo', 'yipee');
  23018. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  23019. * ```
  23020. *
  23021. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  23022. * hash object.
  23023. *
  23024. * When called with a single argument the method acts as a setter, setting the `search` component
  23025. * of `$location` to the specified value.
  23026. *
  23027. * If the argument is a hash object containing an array of values, these values will be encoded
  23028. * as duplicate search parameters in the url.
  23029. *
  23030. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  23031. * will override only a single search property.
  23032. *
  23033. * If `paramValue` is an array, it will override the property of the `search` component of
  23034. * `$location` specified via the first argument.
  23035. *
  23036. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  23037. *
  23038. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  23039. * value nor trailing equal sign.
  23040. *
  23041. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  23042. * one or more arguments returns `$location` object itself.
  23043. */
  23044. search: function(search, paramValue) {
  23045. switch (arguments.length) {
  23046. case 0:
  23047. return this.$$search;
  23048. case 1:
  23049. if (isString(search) || isNumber(search)) {
  23050. search = search.toString();
  23051. this.$$search = parseKeyValue(search);
  23052. } else if (isObject(search)) {
  23053. search = copy(search, {});
  23054. // remove object undefined or null properties
  23055. forEach(search, function(value, key) {
  23056. if (value == null) delete search[key];
  23057. });
  23058. this.$$search = search;
  23059. } else {
  23060. throw $locationMinErr('isrcharg',
  23061. 'The first argument of the `$location#search()` call must be a string or an object.');
  23062. }
  23063. break;
  23064. default:
  23065. if (isUndefined(paramValue) || paramValue === null) {
  23066. delete this.$$search[search];
  23067. } else {
  23068. this.$$search[search] = paramValue;
  23069. }
  23070. }
  23071. this.$$compose();
  23072. return this;
  23073. },
  23074. /**
  23075. * @ngdoc method
  23076. * @name $location#hash
  23077. *
  23078. * @description
  23079. * This method is getter / setter.
  23080. *
  23081. * Returns the hash fragment when called without any parameters.
  23082. *
  23083. * Changes the hash fragment when called with a parameter and returns `$location`.
  23084. *
  23085. *
  23086. * ```js
  23087. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  23088. * var hash = $location.hash();
  23089. * // => "hashValue"
  23090. * ```
  23091. *
  23092. * @param {(string|number)=} hash New hash fragment
  23093. * @return {string} hash
  23094. */
  23095. hash: locationGetterSetter('$$hash', function(hash) {
  23096. return hash !== null ? hash.toString() : '';
  23097. }),
  23098. /**
  23099. * @ngdoc method
  23100. * @name $location#replace
  23101. *
  23102. * @description
  23103. * If called, all changes to $location during the current `$digest` will replace the current history
  23104. * record, instead of adding a new one.
  23105. */
  23106. replace: function() {
  23107. this.$$replace = true;
  23108. return this;
  23109. }
  23110. };
  23111. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  23112. Location.prototype = Object.create(locationPrototype);
  23113. /**
  23114. * @ngdoc method
  23115. * @name $location#state
  23116. *
  23117. * @description
  23118. * This method is getter / setter.
  23119. *
  23120. * Return the history state object when called without any parameter.
  23121. *
  23122. * Change the history state object when called with one parameter and return `$location`.
  23123. * The state object is later passed to `pushState` or `replaceState`.
  23124. *
  23125. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  23126. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  23127. * older browsers (like IE9 or Android < 4.0), don't use this method.
  23128. *
  23129. * @param {object=} state State object for pushState or replaceState
  23130. * @return {object} state
  23131. */
  23132. Location.prototype.state = function(state) {
  23133. if (!arguments.length) {
  23134. return this.$$state;
  23135. }
  23136. if (Location !== LocationHtml5Url || !this.$$html5) {
  23137. throw $locationMinErr('nostate', 'History API state support is available only ' +
  23138. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  23139. }
  23140. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  23141. // but we're changing the $$state reference to $browser.state() during the $digest
  23142. // so the modification window is narrow.
  23143. this.$$state = isUndefined(state) ? null : state;
  23144. return this;
  23145. };
  23146. });
  23147. function locationGetter(property) {
  23148. return function() {
  23149. return this[property];
  23150. };
  23151. }
  23152. function locationGetterSetter(property, preprocess) {
  23153. return function(value) {
  23154. if (isUndefined(value)) {
  23155. return this[property];
  23156. }
  23157. this[property] = preprocess(value);
  23158. this.$$compose();
  23159. return this;
  23160. };
  23161. }
  23162. /**
  23163. * @ngdoc service
  23164. * @name $location
  23165. *
  23166. * @requires $rootElement
  23167. *
  23168. * @description
  23169. * The $location service parses the URL in the browser address bar (based on the
  23170. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  23171. * available to your application. Changes to the URL in the address bar are reflected into
  23172. * $location service and changes to $location are reflected into the browser address bar.
  23173. *
  23174. * **The $location service:**
  23175. *
  23176. * - Exposes the current URL in the browser address bar, so you can
  23177. * - Watch and observe the URL.
  23178. * - Change the URL.
  23179. * - Synchronizes the URL with the browser when the user
  23180. * - Changes the address bar.
  23181. * - Clicks the back or forward button (or clicks a History link).
  23182. * - Clicks on a link.
  23183. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  23184. *
  23185. * For more information see {@link guide/$location Developer Guide: Using $location}
  23186. */
  23187. /**
  23188. * @ngdoc provider
  23189. * @name $locationProvider
  23190. * @description
  23191. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  23192. */
  23193. function $LocationProvider() {
  23194. var hashPrefix = '',
  23195. html5Mode = {
  23196. enabled: false,
  23197. requireBase: true,
  23198. rewriteLinks: true
  23199. };
  23200. /**
  23201. * @ngdoc method
  23202. * @name $locationProvider#hashPrefix
  23203. * @description
  23204. * @param {string=} prefix Prefix for hash part (containing path and search)
  23205. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  23206. */
  23207. this.hashPrefix = function(prefix) {
  23208. if (isDefined(prefix)) {
  23209. hashPrefix = prefix;
  23210. return this;
  23211. } else {
  23212. return hashPrefix;
  23213. }
  23214. };
  23215. /**
  23216. * @ngdoc method
  23217. * @name $locationProvider#html5Mode
  23218. * @description
  23219. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  23220. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  23221. * properties:
  23222. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  23223. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  23224. * support `pushState`.
  23225. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  23226. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  23227. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  23228. * See the {@link guide/$location $location guide for more information}
  23229. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  23230. * enables/disables url rewriting for relative links.
  23231. *
  23232. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  23233. */
  23234. this.html5Mode = function(mode) {
  23235. if (isBoolean(mode)) {
  23236. html5Mode.enabled = mode;
  23237. return this;
  23238. } else if (isObject(mode)) {
  23239. if (isBoolean(mode.enabled)) {
  23240. html5Mode.enabled = mode.enabled;
  23241. }
  23242. if (isBoolean(mode.requireBase)) {
  23243. html5Mode.requireBase = mode.requireBase;
  23244. }
  23245. if (isBoolean(mode.rewriteLinks)) {
  23246. html5Mode.rewriteLinks = mode.rewriteLinks;
  23247. }
  23248. return this;
  23249. } else {
  23250. return html5Mode;
  23251. }
  23252. };
  23253. /**
  23254. * @ngdoc event
  23255. * @name $location#$locationChangeStart
  23256. * @eventType broadcast on root scope
  23257. * @description
  23258. * Broadcasted before a URL will change.
  23259. *
  23260. * This change can be prevented by calling
  23261. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  23262. * details about event object. Upon successful change
  23263. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  23264. *
  23265. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  23266. * the browser supports the HTML5 History API.
  23267. *
  23268. * @param {Object} angularEvent Synthetic event object.
  23269. * @param {string} newUrl New URL
  23270. * @param {string=} oldUrl URL that was before it was changed.
  23271. * @param {string=} newState New history state object
  23272. * @param {string=} oldState History state object that was before it was changed.
  23273. */
  23274. /**
  23275. * @ngdoc event
  23276. * @name $location#$locationChangeSuccess
  23277. * @eventType broadcast on root scope
  23278. * @description
  23279. * Broadcasted after a URL was changed.
  23280. *
  23281. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  23282. * the browser supports the HTML5 History API.
  23283. *
  23284. * @param {Object} angularEvent Synthetic event object.
  23285. * @param {string} newUrl New URL
  23286. * @param {string=} oldUrl URL that was before it was changed.
  23287. * @param {string=} newState New history state object
  23288. * @param {string=} oldState History state object that was before it was changed.
  23289. */
  23290. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  23291. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  23292. var $location,
  23293. LocationMode,
  23294. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  23295. initialUrl = $browser.url(),
  23296. appBase;
  23297. if (html5Mode.enabled) {
  23298. if (!baseHref && html5Mode.requireBase) {
  23299. throw $locationMinErr('nobase',
  23300. "$location in HTML5 mode requires a <base> tag to be present!");
  23301. }
  23302. appBase = serverBase(initialUrl) + (baseHref || '/');
  23303. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  23304. } else {
  23305. appBase = stripHash(initialUrl);
  23306. LocationMode = LocationHashbangUrl;
  23307. }
  23308. var appBaseNoFile = stripFile(appBase);
  23309. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  23310. $location.$$parseLinkUrl(initialUrl, initialUrl);
  23311. $location.$$state = $browser.state();
  23312. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  23313. function setBrowserUrlWithFallback(url, replace, state) {
  23314. var oldUrl = $location.url();
  23315. var oldState = $location.$$state;
  23316. try {
  23317. $browser.url(url, replace, state);
  23318. // Make sure $location.state() returns referentially identical (not just deeply equal)
  23319. // state object; this makes possible quick checking if the state changed in the digest
  23320. // loop. Checking deep equality would be too expensive.
  23321. $location.$$state = $browser.state();
  23322. } catch (e) {
  23323. // Restore old values if pushState fails
  23324. $location.url(oldUrl);
  23325. $location.$$state = oldState;
  23326. throw e;
  23327. }
  23328. }
  23329. $rootElement.on('click', function(event) {
  23330. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  23331. // currently we open nice url link and redirect then
  23332. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  23333. var elm = jqLite(event.target);
  23334. // traverse the DOM up to find first A tag
  23335. while (nodeName_(elm[0]) !== 'a') {
  23336. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  23337. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  23338. }
  23339. var absHref = elm.prop('href');
  23340. // get the actual href attribute - see
  23341. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  23342. var relHref = elm.attr('href') || elm.attr('xlink:href');
  23343. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  23344. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  23345. // an animation.
  23346. absHref = urlResolve(absHref.animVal).href;
  23347. }
  23348. // Ignore when url is started with javascript: or mailto:
  23349. if (IGNORE_URI_REGEXP.test(absHref)) return;
  23350. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  23351. if ($location.$$parseLinkUrl(absHref, relHref)) {
  23352. // We do a preventDefault for all urls that are part of the angular application,
  23353. // in html5mode and also without, so that we are able to abort navigation without
  23354. // getting double entries in the location history.
  23355. event.preventDefault();
  23356. // update location manually
  23357. if ($location.absUrl() != $browser.url()) {
  23358. $rootScope.$apply();
  23359. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  23360. $window.angular['ff-684208-preventDefault'] = true;
  23361. }
  23362. }
  23363. }
  23364. });
  23365. // rewrite hashbang url <> html5 url
  23366. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  23367. $browser.url($location.absUrl(), true);
  23368. }
  23369. var initializing = true;
  23370. // update $location when $browser url changes
  23371. $browser.onUrlChange(function(newUrl, newState) {
  23372. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  23373. // If we are navigating outside of the app then force a reload
  23374. $window.location.href = newUrl;
  23375. return;
  23376. }
  23377. $rootScope.$evalAsync(function() {
  23378. var oldUrl = $location.absUrl();
  23379. var oldState = $location.$$state;
  23380. var defaultPrevented;
  23381. newUrl = trimEmptyHash(newUrl);
  23382. $location.$$parse(newUrl);
  23383. $location.$$state = newState;
  23384. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  23385. newState, oldState).defaultPrevented;
  23386. // if the location was changed by a `$locationChangeStart` handler then stop
  23387. // processing this location change
  23388. if ($location.absUrl() !== newUrl) return;
  23389. if (defaultPrevented) {
  23390. $location.$$parse(oldUrl);
  23391. $location.$$state = oldState;
  23392. setBrowserUrlWithFallback(oldUrl, false, oldState);
  23393. } else {
  23394. initializing = false;
  23395. afterLocationChange(oldUrl, oldState);
  23396. }
  23397. });
  23398. if (!$rootScope.$$phase) $rootScope.$digest();
  23399. });
  23400. // update browser
  23401. $rootScope.$watch(function $locationWatch() {
  23402. var oldUrl = trimEmptyHash($browser.url());
  23403. var newUrl = trimEmptyHash($location.absUrl());
  23404. var oldState = $browser.state();
  23405. var currentReplace = $location.$$replace;
  23406. var urlOrStateChanged = oldUrl !== newUrl ||
  23407. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  23408. if (initializing || urlOrStateChanged) {
  23409. initializing = false;
  23410. $rootScope.$evalAsync(function() {
  23411. var newUrl = $location.absUrl();
  23412. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  23413. $location.$$state, oldState).defaultPrevented;
  23414. // if the location was changed by a `$locationChangeStart` handler then stop
  23415. // processing this location change
  23416. if ($location.absUrl() !== newUrl) return;
  23417. if (defaultPrevented) {
  23418. $location.$$parse(oldUrl);
  23419. $location.$$state = oldState;
  23420. } else {
  23421. if (urlOrStateChanged) {
  23422. setBrowserUrlWithFallback(newUrl, currentReplace,
  23423. oldState === $location.$$state ? null : $location.$$state);
  23424. }
  23425. afterLocationChange(oldUrl, oldState);
  23426. }
  23427. });
  23428. }
  23429. $location.$$replace = false;
  23430. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  23431. // there is a change
  23432. });
  23433. return $location;
  23434. function afterLocationChange(oldUrl, oldState) {
  23435. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  23436. $location.$$state, oldState);
  23437. }
  23438. }];
  23439. }
  23440. /**
  23441. * @ngdoc service
  23442. * @name $log
  23443. * @requires $window
  23444. *
  23445. * @description
  23446. * Simple service for logging. Default implementation safely writes the message
  23447. * into the browser's console (if present).
  23448. *
  23449. * The main purpose of this service is to simplify debugging and troubleshooting.
  23450. *
  23451. * The default is to log `debug` messages. You can use
  23452. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  23453. *
  23454. * @example
  23455. <example module="logExample">
  23456. <file name="script.js">
  23457. angular.module('logExample', [])
  23458. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  23459. $scope.$log = $log;
  23460. $scope.message = 'Hello World!';
  23461. }]);
  23462. </file>
  23463. <file name="index.html">
  23464. <div ng-controller="LogController">
  23465. <p>Reload this page with open console, enter text and hit the log button...</p>
  23466. <label>Message:
  23467. <input type="text" ng-model="message" /></label>
  23468. <button ng-click="$log.log(message)">log</button>
  23469. <button ng-click="$log.warn(message)">warn</button>
  23470. <button ng-click="$log.info(message)">info</button>
  23471. <button ng-click="$log.error(message)">error</button>
  23472. <button ng-click="$log.debug(message)">debug</button>
  23473. </div>
  23474. </file>
  23475. </example>
  23476. */
  23477. /**
  23478. * @ngdoc provider
  23479. * @name $logProvider
  23480. * @description
  23481. * Use the `$logProvider` to configure how the application logs messages
  23482. */
  23483. function $LogProvider() {
  23484. var debug = true,
  23485. self = this;
  23486. /**
  23487. * @ngdoc method
  23488. * @name $logProvider#debugEnabled
  23489. * @description
  23490. * @param {boolean=} flag enable or disable debug level messages
  23491. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  23492. */
  23493. this.debugEnabled = function(flag) {
  23494. if (isDefined(flag)) {
  23495. debug = flag;
  23496. return this;
  23497. } else {
  23498. return debug;
  23499. }
  23500. };
  23501. this.$get = ['$window', function($window) {
  23502. return {
  23503. /**
  23504. * @ngdoc method
  23505. * @name $log#log
  23506. *
  23507. * @description
  23508. * Write a log message
  23509. */
  23510. log: consoleLog('log'),
  23511. /**
  23512. * @ngdoc method
  23513. * @name $log#info
  23514. *
  23515. * @description
  23516. * Write an information message
  23517. */
  23518. info: consoleLog('info'),
  23519. /**
  23520. * @ngdoc method
  23521. * @name $log#warn
  23522. *
  23523. * @description
  23524. * Write a warning message
  23525. */
  23526. warn: consoleLog('warn'),
  23527. /**
  23528. * @ngdoc method
  23529. * @name $log#error
  23530. *
  23531. * @description
  23532. * Write an error message
  23533. */
  23534. error: consoleLog('error'),
  23535. /**
  23536. * @ngdoc method
  23537. * @name $log#debug
  23538. *
  23539. * @description
  23540. * Write a debug message
  23541. */
  23542. debug: (function() {
  23543. var fn = consoleLog('debug');
  23544. return function() {
  23545. if (debug) {
  23546. fn.apply(self, arguments);
  23547. }
  23548. };
  23549. }())
  23550. };
  23551. function formatError(arg) {
  23552. if (arg instanceof Error) {
  23553. if (arg.stack) {
  23554. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  23555. ? 'Error: ' + arg.message + '\n' + arg.stack
  23556. : arg.stack;
  23557. } else if (arg.sourceURL) {
  23558. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  23559. }
  23560. }
  23561. return arg;
  23562. }
  23563. function consoleLog(type) {
  23564. var console = $window.console || {},
  23565. logFn = console[type] || console.log || noop,
  23566. hasApply = false;
  23567. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  23568. // The reason behind this is that console.log has type "object" in IE8...
  23569. try {
  23570. hasApply = !!logFn.apply;
  23571. } catch (e) {}
  23572. if (hasApply) {
  23573. return function() {
  23574. var args = [];
  23575. forEach(arguments, function(arg) {
  23576. args.push(formatError(arg));
  23577. });
  23578. return logFn.apply(console, args);
  23579. };
  23580. }
  23581. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  23582. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  23583. return function(arg1, arg2) {
  23584. logFn(arg1, arg2 == null ? '' : arg2);
  23585. };
  23586. }
  23587. }];
  23588. }
  23589. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  23590. * Any commits to this file should be reviewed with security in mind. *
  23591. * Changes to this file can potentially create security vulnerabilities. *
  23592. * An approval from 2 Core members with history of modifying *
  23593. * this file is required. *
  23594. * *
  23595. * Does the change somehow allow for arbitrary javascript to be executed? *
  23596. * Or allows for someone to change the prototype of built-in objects? *
  23597. * Or gives undesired access to variables likes document or window? *
  23598. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  23599. var $parseMinErr = minErr('$parse');
  23600. // Sandboxing Angular Expressions
  23601. // ------------------------------
  23602. // Angular expressions are generally considered safe because these expressions only have direct
  23603. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  23604. // obtaining a reference to native JS functions such as the Function constructor.
  23605. //
  23606. // As an example, consider the following Angular expression:
  23607. //
  23608. // {}.toString.constructor('alert("evil JS code")')
  23609. //
  23610. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  23611. // against the expression language, but not to prevent exploits that were enabled by exposing
  23612. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  23613. // practice and therefore we are not even trying to protect against interaction with an object
  23614. // explicitly exposed in this way.
  23615. //
  23616. // In general, it is not possible to access a Window object from an angular expression unless a
  23617. // window or some DOM object that has a reference to window is published onto a Scope.
  23618. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  23619. // native objects.
  23620. //
  23621. // See https://docs.angularjs.org/guide/security
  23622. function ensureSafeMemberName(name, fullExpression) {
  23623. if (name === "__defineGetter__" || name === "__defineSetter__"
  23624. || name === "__lookupGetter__" || name === "__lookupSetter__"
  23625. || name === "__proto__") {
  23626. throw $parseMinErr('isecfld',
  23627. 'Attempting to access a disallowed field in Angular expressions! '
  23628. + 'Expression: {0}', fullExpression);
  23629. }
  23630. return name;
  23631. }
  23632. function getStringValue(name) {
  23633. // Property names must be strings. This means that non-string objects cannot be used
  23634. // as keys in an object. Any non-string object, including a number, is typecasted
  23635. // into a string via the toString method.
  23636. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  23637. //
  23638. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  23639. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  23640. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  23641. //
  23642. // TypeError: Cannot convert object to primitive value
  23643. //
  23644. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  23645. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  23646. // such a 'broken' object as a key.
  23647. return name + '';
  23648. }
  23649. function ensureSafeObject(obj, fullExpression) {
  23650. // nifty check if obj is Function that is fast and works across iframes and other contexts
  23651. if (obj) {
  23652. if (obj.constructor === obj) {
  23653. throw $parseMinErr('isecfn',
  23654. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  23655. fullExpression);
  23656. } else if (// isWindow(obj)
  23657. obj.window === obj) {
  23658. throw $parseMinErr('isecwindow',
  23659. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  23660. fullExpression);
  23661. } else if (// isElement(obj)
  23662. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  23663. throw $parseMinErr('isecdom',
  23664. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  23665. fullExpression);
  23666. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  23667. obj === Object) {
  23668. throw $parseMinErr('isecobj',
  23669. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  23670. fullExpression);
  23671. }
  23672. }
  23673. return obj;
  23674. }
  23675. var CALL = Function.prototype.call;
  23676. var APPLY = Function.prototype.apply;
  23677. var BIND = Function.prototype.bind;
  23678. function ensureSafeFunction(obj, fullExpression) {
  23679. if (obj) {
  23680. if (obj.constructor === obj) {
  23681. throw $parseMinErr('isecfn',
  23682. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  23683. fullExpression);
  23684. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  23685. throw $parseMinErr('isecff',
  23686. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  23687. fullExpression);
  23688. }
  23689. }
  23690. }
  23691. function ensureSafeAssignContext(obj, fullExpression) {
  23692. if (obj) {
  23693. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  23694. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  23695. throw $parseMinErr('isecaf',
  23696. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  23697. }
  23698. }
  23699. }
  23700. var OPERATORS = createMap();
  23701. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  23702. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  23703. /////////////////////////////////////////
  23704. /**
  23705. * @constructor
  23706. */
  23707. var Lexer = function(options) {
  23708. this.options = options;
  23709. };
  23710. Lexer.prototype = {
  23711. constructor: Lexer,
  23712. lex: function(text) {
  23713. this.text = text;
  23714. this.index = 0;
  23715. this.tokens = [];
  23716. while (this.index < this.text.length) {
  23717. var ch = this.text.charAt(this.index);
  23718. if (ch === '"' || ch === "'") {
  23719. this.readString(ch);
  23720. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  23721. this.readNumber();
  23722. } else if (this.isIdent(ch)) {
  23723. this.readIdent();
  23724. } else if (this.is(ch, '(){}[].,;:?')) {
  23725. this.tokens.push({index: this.index, text: ch});
  23726. this.index++;
  23727. } else if (this.isWhitespace(ch)) {
  23728. this.index++;
  23729. } else {
  23730. var ch2 = ch + this.peek();
  23731. var ch3 = ch2 + this.peek(2);
  23732. var op1 = OPERATORS[ch];
  23733. var op2 = OPERATORS[ch2];
  23734. var op3 = OPERATORS[ch3];
  23735. if (op1 || op2 || op3) {
  23736. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  23737. this.tokens.push({index: this.index, text: token, operator: true});
  23738. this.index += token.length;
  23739. } else {
  23740. this.throwError('Unexpected next character ', this.index, this.index + 1);
  23741. }
  23742. }
  23743. }
  23744. return this.tokens;
  23745. },
  23746. is: function(ch, chars) {
  23747. return chars.indexOf(ch) !== -1;
  23748. },
  23749. peek: function(i) {
  23750. var num = i || 1;
  23751. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  23752. },
  23753. isNumber: function(ch) {
  23754. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  23755. },
  23756. isWhitespace: function(ch) {
  23757. // IE treats non-breaking space as \u00A0
  23758. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  23759. ch === '\n' || ch === '\v' || ch === '\u00A0');
  23760. },
  23761. isIdent: function(ch) {
  23762. return ('a' <= ch && ch <= 'z' ||
  23763. 'A' <= ch && ch <= 'Z' ||
  23764. '_' === ch || ch === '$');
  23765. },
  23766. isExpOperator: function(ch) {
  23767. return (ch === '-' || ch === '+' || this.isNumber(ch));
  23768. },
  23769. throwError: function(error, start, end) {
  23770. end = end || this.index;
  23771. var colStr = (isDefined(start)
  23772. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  23773. : ' ' + end);
  23774. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  23775. error, colStr, this.text);
  23776. },
  23777. readNumber: function() {
  23778. var number = '';
  23779. var start = this.index;
  23780. while (this.index < this.text.length) {
  23781. var ch = lowercase(this.text.charAt(this.index));
  23782. if (ch == '.' || this.isNumber(ch)) {
  23783. number += ch;
  23784. } else {
  23785. var peekCh = this.peek();
  23786. if (ch == 'e' && this.isExpOperator(peekCh)) {
  23787. number += ch;
  23788. } else if (this.isExpOperator(ch) &&
  23789. peekCh && this.isNumber(peekCh) &&
  23790. number.charAt(number.length - 1) == 'e') {
  23791. number += ch;
  23792. } else if (this.isExpOperator(ch) &&
  23793. (!peekCh || !this.isNumber(peekCh)) &&
  23794. number.charAt(number.length - 1) == 'e') {
  23795. this.throwError('Invalid exponent');
  23796. } else {
  23797. break;
  23798. }
  23799. }
  23800. this.index++;
  23801. }
  23802. this.tokens.push({
  23803. index: start,
  23804. text: number,
  23805. constant: true,
  23806. value: Number(number)
  23807. });
  23808. },
  23809. readIdent: function() {
  23810. var start = this.index;
  23811. while (this.index < this.text.length) {
  23812. var ch = this.text.charAt(this.index);
  23813. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  23814. break;
  23815. }
  23816. this.index++;
  23817. }
  23818. this.tokens.push({
  23819. index: start,
  23820. text: this.text.slice(start, this.index),
  23821. identifier: true
  23822. });
  23823. },
  23824. readString: function(quote) {
  23825. var start = this.index;
  23826. this.index++;
  23827. var string = '';
  23828. var rawString = quote;
  23829. var escape = false;
  23830. while (this.index < this.text.length) {
  23831. var ch = this.text.charAt(this.index);
  23832. rawString += ch;
  23833. if (escape) {
  23834. if (ch === 'u') {
  23835. var hex = this.text.substring(this.index + 1, this.index + 5);
  23836. if (!hex.match(/[\da-f]{4}/i)) {
  23837. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  23838. }
  23839. this.index += 4;
  23840. string += String.fromCharCode(parseInt(hex, 16));
  23841. } else {
  23842. var rep = ESCAPE[ch];
  23843. string = string + (rep || ch);
  23844. }
  23845. escape = false;
  23846. } else if (ch === '\\') {
  23847. escape = true;
  23848. } else if (ch === quote) {
  23849. this.index++;
  23850. this.tokens.push({
  23851. index: start,
  23852. text: rawString,
  23853. constant: true,
  23854. value: string
  23855. });
  23856. return;
  23857. } else {
  23858. string += ch;
  23859. }
  23860. this.index++;
  23861. }
  23862. this.throwError('Unterminated quote', start);
  23863. }
  23864. };
  23865. var AST = function(lexer, options) {
  23866. this.lexer = lexer;
  23867. this.options = options;
  23868. };
  23869. AST.Program = 'Program';
  23870. AST.ExpressionStatement = 'ExpressionStatement';
  23871. AST.AssignmentExpression = 'AssignmentExpression';
  23872. AST.ConditionalExpression = 'ConditionalExpression';
  23873. AST.LogicalExpression = 'LogicalExpression';
  23874. AST.BinaryExpression = 'BinaryExpression';
  23875. AST.UnaryExpression = 'UnaryExpression';
  23876. AST.CallExpression = 'CallExpression';
  23877. AST.MemberExpression = 'MemberExpression';
  23878. AST.Identifier = 'Identifier';
  23879. AST.Literal = 'Literal';
  23880. AST.ArrayExpression = 'ArrayExpression';
  23881. AST.Property = 'Property';
  23882. AST.ObjectExpression = 'ObjectExpression';
  23883. AST.ThisExpression = 'ThisExpression';
  23884. AST.LocalsExpression = 'LocalsExpression';
  23885. // Internal use only
  23886. AST.NGValueParameter = 'NGValueParameter';
  23887. AST.prototype = {
  23888. ast: function(text) {
  23889. this.text = text;
  23890. this.tokens = this.lexer.lex(text);
  23891. var value = this.program();
  23892. if (this.tokens.length !== 0) {
  23893. this.throwError('is an unexpected token', this.tokens[0]);
  23894. }
  23895. return value;
  23896. },
  23897. program: function() {
  23898. var body = [];
  23899. while (true) {
  23900. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  23901. body.push(this.expressionStatement());
  23902. if (!this.expect(';')) {
  23903. return { type: AST.Program, body: body};
  23904. }
  23905. }
  23906. },
  23907. expressionStatement: function() {
  23908. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  23909. },
  23910. filterChain: function() {
  23911. var left = this.expression();
  23912. var token;
  23913. while ((token = this.expect('|'))) {
  23914. left = this.filter(left);
  23915. }
  23916. return left;
  23917. },
  23918. expression: function() {
  23919. return this.assignment();
  23920. },
  23921. assignment: function() {
  23922. var result = this.ternary();
  23923. if (this.expect('=')) {
  23924. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  23925. }
  23926. return result;
  23927. },
  23928. ternary: function() {
  23929. var test = this.logicalOR();
  23930. var alternate;
  23931. var consequent;
  23932. if (this.expect('?')) {
  23933. alternate = this.expression();
  23934. if (this.consume(':')) {
  23935. consequent = this.expression();
  23936. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  23937. }
  23938. }
  23939. return test;
  23940. },
  23941. logicalOR: function() {
  23942. var left = this.logicalAND();
  23943. while (this.expect('||')) {
  23944. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  23945. }
  23946. return left;
  23947. },
  23948. logicalAND: function() {
  23949. var left = this.equality();
  23950. while (this.expect('&&')) {
  23951. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  23952. }
  23953. return left;
  23954. },
  23955. equality: function() {
  23956. var left = this.relational();
  23957. var token;
  23958. while ((token = this.expect('==','!=','===','!=='))) {
  23959. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  23960. }
  23961. return left;
  23962. },
  23963. relational: function() {
  23964. var left = this.additive();
  23965. var token;
  23966. while ((token = this.expect('<', '>', '<=', '>='))) {
  23967. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  23968. }
  23969. return left;
  23970. },
  23971. additive: function() {
  23972. var left = this.multiplicative();
  23973. var token;
  23974. while ((token = this.expect('+','-'))) {
  23975. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  23976. }
  23977. return left;
  23978. },
  23979. multiplicative: function() {
  23980. var left = this.unary();
  23981. var token;
  23982. while ((token = this.expect('*','/','%'))) {
  23983. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  23984. }
  23985. return left;
  23986. },
  23987. unary: function() {
  23988. var token;
  23989. if ((token = this.expect('+', '-', '!'))) {
  23990. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  23991. } else {
  23992. return this.primary();
  23993. }
  23994. },
  23995. primary: function() {
  23996. var primary;
  23997. if (this.expect('(')) {
  23998. primary = this.filterChain();
  23999. this.consume(')');
  24000. } else if (this.expect('[')) {
  24001. primary = this.arrayDeclaration();
  24002. } else if (this.expect('{')) {
  24003. primary = this.object();
  24004. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  24005. primary = copy(this.selfReferential[this.consume().text]);
  24006. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  24007. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  24008. } else if (this.peek().identifier) {
  24009. primary = this.identifier();
  24010. } else if (this.peek().constant) {
  24011. primary = this.constant();
  24012. } else {
  24013. this.throwError('not a primary expression', this.peek());
  24014. }
  24015. var next;
  24016. while ((next = this.expect('(', '[', '.'))) {
  24017. if (next.text === '(') {
  24018. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  24019. this.consume(')');
  24020. } else if (next.text === '[') {
  24021. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  24022. this.consume(']');
  24023. } else if (next.text === '.') {
  24024. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  24025. } else {
  24026. this.throwError('IMPOSSIBLE');
  24027. }
  24028. }
  24029. return primary;
  24030. },
  24031. filter: function(baseExpression) {
  24032. var args = [baseExpression];
  24033. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  24034. while (this.expect(':')) {
  24035. args.push(this.expression());
  24036. }
  24037. return result;
  24038. },
  24039. parseArguments: function() {
  24040. var args = [];
  24041. if (this.peekToken().text !== ')') {
  24042. do {
  24043. args.push(this.expression());
  24044. } while (this.expect(','));
  24045. }
  24046. return args;
  24047. },
  24048. identifier: function() {
  24049. var token = this.consume();
  24050. if (!token.identifier) {
  24051. this.throwError('is not a valid identifier', token);
  24052. }
  24053. return { type: AST.Identifier, name: token.text };
  24054. },
  24055. constant: function() {
  24056. // TODO check that it is a constant
  24057. return { type: AST.Literal, value: this.consume().value };
  24058. },
  24059. arrayDeclaration: function() {
  24060. var elements = [];
  24061. if (this.peekToken().text !== ']') {
  24062. do {
  24063. if (this.peek(']')) {
  24064. // Support trailing commas per ES5.1.
  24065. break;
  24066. }
  24067. elements.push(this.expression());
  24068. } while (this.expect(','));
  24069. }
  24070. this.consume(']');
  24071. return { type: AST.ArrayExpression, elements: elements };
  24072. },
  24073. object: function() {
  24074. var properties = [], property;
  24075. if (this.peekToken().text !== '}') {
  24076. do {
  24077. if (this.peek('}')) {
  24078. // Support trailing commas per ES5.1.
  24079. break;
  24080. }
  24081. property = {type: AST.Property, kind: 'init'};
  24082. if (this.peek().constant) {
  24083. property.key = this.constant();
  24084. } else if (this.peek().identifier) {
  24085. property.key = this.identifier();
  24086. } else {
  24087. this.throwError("invalid key", this.peek());
  24088. }
  24089. this.consume(':');
  24090. property.value = this.expression();
  24091. properties.push(property);
  24092. } while (this.expect(','));
  24093. }
  24094. this.consume('}');
  24095. return {type: AST.ObjectExpression, properties: properties };
  24096. },
  24097. throwError: function(msg, token) {
  24098. throw $parseMinErr('syntax',
  24099. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  24100. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  24101. },
  24102. consume: function(e1) {
  24103. if (this.tokens.length === 0) {
  24104. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  24105. }
  24106. var token = this.expect(e1);
  24107. if (!token) {
  24108. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  24109. }
  24110. return token;
  24111. },
  24112. peekToken: function() {
  24113. if (this.tokens.length === 0) {
  24114. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  24115. }
  24116. return this.tokens[0];
  24117. },
  24118. peek: function(e1, e2, e3, e4) {
  24119. return this.peekAhead(0, e1, e2, e3, e4);
  24120. },
  24121. peekAhead: function(i, e1, e2, e3, e4) {
  24122. if (this.tokens.length > i) {
  24123. var token = this.tokens[i];
  24124. var t = token.text;
  24125. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  24126. (!e1 && !e2 && !e3 && !e4)) {
  24127. return token;
  24128. }
  24129. }
  24130. return false;
  24131. },
  24132. expect: function(e1, e2, e3, e4) {
  24133. var token = this.peek(e1, e2, e3, e4);
  24134. if (token) {
  24135. this.tokens.shift();
  24136. return token;
  24137. }
  24138. return false;
  24139. },
  24140. selfReferential: {
  24141. 'this': {type: AST.ThisExpression },
  24142. '$locals': {type: AST.LocalsExpression }
  24143. }
  24144. };
  24145. function ifDefined(v, d) {
  24146. return typeof v !== 'undefined' ? v : d;
  24147. }
  24148. function plusFn(l, r) {
  24149. if (typeof l === 'undefined') return r;
  24150. if (typeof r === 'undefined') return l;
  24151. return l + r;
  24152. }
  24153. function isStateless($filter, filterName) {
  24154. var fn = $filter(filterName);
  24155. return !fn.$stateful;
  24156. }
  24157. function findConstantAndWatchExpressions(ast, $filter) {
  24158. var allConstants;
  24159. var argsToWatch;
  24160. switch (ast.type) {
  24161. case AST.Program:
  24162. allConstants = true;
  24163. forEach(ast.body, function(expr) {
  24164. findConstantAndWatchExpressions(expr.expression, $filter);
  24165. allConstants = allConstants && expr.expression.constant;
  24166. });
  24167. ast.constant = allConstants;
  24168. break;
  24169. case AST.Literal:
  24170. ast.constant = true;
  24171. ast.toWatch = [];
  24172. break;
  24173. case AST.UnaryExpression:
  24174. findConstantAndWatchExpressions(ast.argument, $filter);
  24175. ast.constant = ast.argument.constant;
  24176. ast.toWatch = ast.argument.toWatch;
  24177. break;
  24178. case AST.BinaryExpression:
  24179. findConstantAndWatchExpressions(ast.left, $filter);
  24180. findConstantAndWatchExpressions(ast.right, $filter);
  24181. ast.constant = ast.left.constant && ast.right.constant;
  24182. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  24183. break;
  24184. case AST.LogicalExpression:
  24185. findConstantAndWatchExpressions(ast.left, $filter);
  24186. findConstantAndWatchExpressions(ast.right, $filter);
  24187. ast.constant = ast.left.constant && ast.right.constant;
  24188. ast.toWatch = ast.constant ? [] : [ast];
  24189. break;
  24190. case AST.ConditionalExpression:
  24191. findConstantAndWatchExpressions(ast.test, $filter);
  24192. findConstantAndWatchExpressions(ast.alternate, $filter);
  24193. findConstantAndWatchExpressions(ast.consequent, $filter);
  24194. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  24195. ast.toWatch = ast.constant ? [] : [ast];
  24196. break;
  24197. case AST.Identifier:
  24198. ast.constant = false;
  24199. ast.toWatch = [ast];
  24200. break;
  24201. case AST.MemberExpression:
  24202. findConstantAndWatchExpressions(ast.object, $filter);
  24203. if (ast.computed) {
  24204. findConstantAndWatchExpressions(ast.property, $filter);
  24205. }
  24206. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  24207. ast.toWatch = [ast];
  24208. break;
  24209. case AST.CallExpression:
  24210. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  24211. argsToWatch = [];
  24212. forEach(ast.arguments, function(expr) {
  24213. findConstantAndWatchExpressions(expr, $filter);
  24214. allConstants = allConstants && expr.constant;
  24215. if (!expr.constant) {
  24216. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  24217. }
  24218. });
  24219. ast.constant = allConstants;
  24220. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  24221. break;
  24222. case AST.AssignmentExpression:
  24223. findConstantAndWatchExpressions(ast.left, $filter);
  24224. findConstantAndWatchExpressions(ast.right, $filter);
  24225. ast.constant = ast.left.constant && ast.right.constant;
  24226. ast.toWatch = [ast];
  24227. break;
  24228. case AST.ArrayExpression:
  24229. allConstants = true;
  24230. argsToWatch = [];
  24231. forEach(ast.elements, function(expr) {
  24232. findConstantAndWatchExpressions(expr, $filter);
  24233. allConstants = allConstants && expr.constant;
  24234. if (!expr.constant) {
  24235. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  24236. }
  24237. });
  24238. ast.constant = allConstants;
  24239. ast.toWatch = argsToWatch;
  24240. break;
  24241. case AST.ObjectExpression:
  24242. allConstants = true;
  24243. argsToWatch = [];
  24244. forEach(ast.properties, function(property) {
  24245. findConstantAndWatchExpressions(property.value, $filter);
  24246. allConstants = allConstants && property.value.constant;
  24247. if (!property.value.constant) {
  24248. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  24249. }
  24250. });
  24251. ast.constant = allConstants;
  24252. ast.toWatch = argsToWatch;
  24253. break;
  24254. case AST.ThisExpression:
  24255. ast.constant = false;
  24256. ast.toWatch = [];
  24257. break;
  24258. case AST.LocalsExpression:
  24259. ast.constant = false;
  24260. ast.toWatch = [];
  24261. break;
  24262. }
  24263. }
  24264. function getInputs(body) {
  24265. if (body.length != 1) return;
  24266. var lastExpression = body[0].expression;
  24267. var candidate = lastExpression.toWatch;
  24268. if (candidate.length !== 1) return candidate;
  24269. return candidate[0] !== lastExpression ? candidate : undefined;
  24270. }
  24271. function isAssignable(ast) {
  24272. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  24273. }
  24274. function assignableAST(ast) {
  24275. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  24276. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  24277. }
  24278. }
  24279. function isLiteral(ast) {
  24280. return ast.body.length === 0 ||
  24281. ast.body.length === 1 && (
  24282. ast.body[0].expression.type === AST.Literal ||
  24283. ast.body[0].expression.type === AST.ArrayExpression ||
  24284. ast.body[0].expression.type === AST.ObjectExpression);
  24285. }
  24286. function isConstant(ast) {
  24287. return ast.constant;
  24288. }
  24289. function ASTCompiler(astBuilder, $filter) {
  24290. this.astBuilder = astBuilder;
  24291. this.$filter = $filter;
  24292. }
  24293. ASTCompiler.prototype = {
  24294. compile: function(expression, expensiveChecks) {
  24295. var self = this;
  24296. var ast = this.astBuilder.ast(expression);
  24297. this.state = {
  24298. nextId: 0,
  24299. filters: {},
  24300. expensiveChecks: expensiveChecks,
  24301. fn: {vars: [], body: [], own: {}},
  24302. assign: {vars: [], body: [], own: {}},
  24303. inputs: []
  24304. };
  24305. findConstantAndWatchExpressions(ast, self.$filter);
  24306. var extra = '';
  24307. var assignable;
  24308. this.stage = 'assign';
  24309. if ((assignable = assignableAST(ast))) {
  24310. this.state.computing = 'assign';
  24311. var result = this.nextId();
  24312. this.recurse(assignable, result);
  24313. this.return_(result);
  24314. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  24315. }
  24316. var toWatch = getInputs(ast.body);
  24317. self.stage = 'inputs';
  24318. forEach(toWatch, function(watch, key) {
  24319. var fnKey = 'fn' + key;
  24320. self.state[fnKey] = {vars: [], body: [], own: {}};
  24321. self.state.computing = fnKey;
  24322. var intoId = self.nextId();
  24323. self.recurse(watch, intoId);
  24324. self.return_(intoId);
  24325. self.state.inputs.push(fnKey);
  24326. watch.watchId = key;
  24327. });
  24328. this.state.computing = 'fn';
  24329. this.stage = 'main';
  24330. this.recurse(ast);
  24331. var fnString =
  24332. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  24333. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  24334. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  24335. this.filterPrefix() +
  24336. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  24337. extra +
  24338. this.watchFns() +
  24339. 'return fn;';
  24340. /* jshint -W054 */
  24341. var fn = (new Function('$filter',
  24342. 'ensureSafeMemberName',
  24343. 'ensureSafeObject',
  24344. 'ensureSafeFunction',
  24345. 'getStringValue',
  24346. 'ensureSafeAssignContext',
  24347. 'ifDefined',
  24348. 'plus',
  24349. 'text',
  24350. fnString))(
  24351. this.$filter,
  24352. ensureSafeMemberName,
  24353. ensureSafeObject,
  24354. ensureSafeFunction,
  24355. getStringValue,
  24356. ensureSafeAssignContext,
  24357. ifDefined,
  24358. plusFn,
  24359. expression);
  24360. /* jshint +W054 */
  24361. this.state = this.stage = undefined;
  24362. fn.literal = isLiteral(ast);
  24363. fn.constant = isConstant(ast);
  24364. return fn;
  24365. },
  24366. USE: 'use',
  24367. STRICT: 'strict',
  24368. watchFns: function() {
  24369. var result = [];
  24370. var fns = this.state.inputs;
  24371. var self = this;
  24372. forEach(fns, function(name) {
  24373. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  24374. });
  24375. if (fns.length) {
  24376. result.push('fn.inputs=[' + fns.join(',') + '];');
  24377. }
  24378. return result.join('');
  24379. },
  24380. generateFunction: function(name, params) {
  24381. return 'function(' + params + '){' +
  24382. this.varsPrefix(name) +
  24383. this.body(name) +
  24384. '};';
  24385. },
  24386. filterPrefix: function() {
  24387. var parts = [];
  24388. var self = this;
  24389. forEach(this.state.filters, function(id, filter) {
  24390. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  24391. });
  24392. if (parts.length) return 'var ' + parts.join(',') + ';';
  24393. return '';
  24394. },
  24395. varsPrefix: function(section) {
  24396. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  24397. },
  24398. body: function(section) {
  24399. return this.state[section].body.join('');
  24400. },
  24401. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  24402. var left, right, self = this, args, expression;
  24403. recursionFn = recursionFn || noop;
  24404. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  24405. intoId = intoId || this.nextId();
  24406. this.if_('i',
  24407. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  24408. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  24409. );
  24410. return;
  24411. }
  24412. switch (ast.type) {
  24413. case AST.Program:
  24414. forEach(ast.body, function(expression, pos) {
  24415. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  24416. if (pos !== ast.body.length - 1) {
  24417. self.current().body.push(right, ';');
  24418. } else {
  24419. self.return_(right);
  24420. }
  24421. });
  24422. break;
  24423. case AST.Literal:
  24424. expression = this.escape(ast.value);
  24425. this.assign(intoId, expression);
  24426. recursionFn(expression);
  24427. break;
  24428. case AST.UnaryExpression:
  24429. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  24430. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  24431. this.assign(intoId, expression);
  24432. recursionFn(expression);
  24433. break;
  24434. case AST.BinaryExpression:
  24435. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  24436. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  24437. if (ast.operator === '+') {
  24438. expression = this.plus(left, right);
  24439. } else if (ast.operator === '-') {
  24440. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  24441. } else {
  24442. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  24443. }
  24444. this.assign(intoId, expression);
  24445. recursionFn(expression);
  24446. break;
  24447. case AST.LogicalExpression:
  24448. intoId = intoId || this.nextId();
  24449. self.recurse(ast.left, intoId);
  24450. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  24451. recursionFn(intoId);
  24452. break;
  24453. case AST.ConditionalExpression:
  24454. intoId = intoId || this.nextId();
  24455. self.recurse(ast.test, intoId);
  24456. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  24457. recursionFn(intoId);
  24458. break;
  24459. case AST.Identifier:
  24460. intoId = intoId || this.nextId();
  24461. if (nameId) {
  24462. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  24463. nameId.computed = false;
  24464. nameId.name = ast.name;
  24465. }
  24466. ensureSafeMemberName(ast.name);
  24467. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  24468. function() {
  24469. self.if_(self.stage === 'inputs' || 's', function() {
  24470. if (create && create !== 1) {
  24471. self.if_(
  24472. self.not(self.nonComputedMember('s', ast.name)),
  24473. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  24474. }
  24475. self.assign(intoId, self.nonComputedMember('s', ast.name));
  24476. });
  24477. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  24478. );
  24479. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  24480. self.addEnsureSafeObject(intoId);
  24481. }
  24482. recursionFn(intoId);
  24483. break;
  24484. case AST.MemberExpression:
  24485. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  24486. intoId = intoId || this.nextId();
  24487. self.recurse(ast.object, left, undefined, function() {
  24488. self.if_(self.notNull(left), function() {
  24489. if (create && create !== 1) {
  24490. self.addEnsureSafeAssignContext(left);
  24491. }
  24492. if (ast.computed) {
  24493. right = self.nextId();
  24494. self.recurse(ast.property, right);
  24495. self.getStringValue(right);
  24496. self.addEnsureSafeMemberName(right);
  24497. if (create && create !== 1) {
  24498. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  24499. }
  24500. expression = self.ensureSafeObject(self.computedMember(left, right));
  24501. self.assign(intoId, expression);
  24502. if (nameId) {
  24503. nameId.computed = true;
  24504. nameId.name = right;
  24505. }
  24506. } else {
  24507. ensureSafeMemberName(ast.property.name);
  24508. if (create && create !== 1) {
  24509. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  24510. }
  24511. expression = self.nonComputedMember(left, ast.property.name);
  24512. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  24513. expression = self.ensureSafeObject(expression);
  24514. }
  24515. self.assign(intoId, expression);
  24516. if (nameId) {
  24517. nameId.computed = false;
  24518. nameId.name = ast.property.name;
  24519. }
  24520. }
  24521. }, function() {
  24522. self.assign(intoId, 'undefined');
  24523. });
  24524. recursionFn(intoId);
  24525. }, !!create);
  24526. break;
  24527. case AST.CallExpression:
  24528. intoId = intoId || this.nextId();
  24529. if (ast.filter) {
  24530. right = self.filter(ast.callee.name);
  24531. args = [];
  24532. forEach(ast.arguments, function(expr) {
  24533. var argument = self.nextId();
  24534. self.recurse(expr, argument);
  24535. args.push(argument);
  24536. });
  24537. expression = right + '(' + args.join(',') + ')';
  24538. self.assign(intoId, expression);
  24539. recursionFn(intoId);
  24540. } else {
  24541. right = self.nextId();
  24542. left = {};
  24543. args = [];
  24544. self.recurse(ast.callee, right, left, function() {
  24545. self.if_(self.notNull(right), function() {
  24546. self.addEnsureSafeFunction(right);
  24547. forEach(ast.arguments, function(expr) {
  24548. self.recurse(expr, self.nextId(), undefined, function(argument) {
  24549. args.push(self.ensureSafeObject(argument));
  24550. });
  24551. });
  24552. if (left.name) {
  24553. if (!self.state.expensiveChecks) {
  24554. self.addEnsureSafeObject(left.context);
  24555. }
  24556. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  24557. } else {
  24558. expression = right + '(' + args.join(',') + ')';
  24559. }
  24560. expression = self.ensureSafeObject(expression);
  24561. self.assign(intoId, expression);
  24562. }, function() {
  24563. self.assign(intoId, 'undefined');
  24564. });
  24565. recursionFn(intoId);
  24566. });
  24567. }
  24568. break;
  24569. case AST.AssignmentExpression:
  24570. right = this.nextId();
  24571. left = {};
  24572. if (!isAssignable(ast.left)) {
  24573. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  24574. }
  24575. this.recurse(ast.left, undefined, left, function() {
  24576. self.if_(self.notNull(left.context), function() {
  24577. self.recurse(ast.right, right);
  24578. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  24579. self.addEnsureSafeAssignContext(left.context);
  24580. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  24581. self.assign(intoId, expression);
  24582. recursionFn(intoId || expression);
  24583. });
  24584. }, 1);
  24585. break;
  24586. case AST.ArrayExpression:
  24587. args = [];
  24588. forEach(ast.elements, function(expr) {
  24589. self.recurse(expr, self.nextId(), undefined, function(argument) {
  24590. args.push(argument);
  24591. });
  24592. });
  24593. expression = '[' + args.join(',') + ']';
  24594. this.assign(intoId, expression);
  24595. recursionFn(expression);
  24596. break;
  24597. case AST.ObjectExpression:
  24598. args = [];
  24599. forEach(ast.properties, function(property) {
  24600. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  24601. args.push(self.escape(
  24602. property.key.type === AST.Identifier ? property.key.name :
  24603. ('' + property.key.value)) +
  24604. ':' + expr);
  24605. });
  24606. });
  24607. expression = '{' + args.join(',') + '}';
  24608. this.assign(intoId, expression);
  24609. recursionFn(expression);
  24610. break;
  24611. case AST.ThisExpression:
  24612. this.assign(intoId, 's');
  24613. recursionFn('s');
  24614. break;
  24615. case AST.LocalsExpression:
  24616. this.assign(intoId, 'l');
  24617. recursionFn('l');
  24618. break;
  24619. case AST.NGValueParameter:
  24620. this.assign(intoId, 'v');
  24621. recursionFn('v');
  24622. break;
  24623. }
  24624. },
  24625. getHasOwnProperty: function(element, property) {
  24626. var key = element + '.' + property;
  24627. var own = this.current().own;
  24628. if (!own.hasOwnProperty(key)) {
  24629. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  24630. }
  24631. return own[key];
  24632. },
  24633. assign: function(id, value) {
  24634. if (!id) return;
  24635. this.current().body.push(id, '=', value, ';');
  24636. return id;
  24637. },
  24638. filter: function(filterName) {
  24639. if (!this.state.filters.hasOwnProperty(filterName)) {
  24640. this.state.filters[filterName] = this.nextId(true);
  24641. }
  24642. return this.state.filters[filterName];
  24643. },
  24644. ifDefined: function(id, defaultValue) {
  24645. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  24646. },
  24647. plus: function(left, right) {
  24648. return 'plus(' + left + ',' + right + ')';
  24649. },
  24650. return_: function(id) {
  24651. this.current().body.push('return ', id, ';');
  24652. },
  24653. if_: function(test, alternate, consequent) {
  24654. if (test === true) {
  24655. alternate();
  24656. } else {
  24657. var body = this.current().body;
  24658. body.push('if(', test, '){');
  24659. alternate();
  24660. body.push('}');
  24661. if (consequent) {
  24662. body.push('else{');
  24663. consequent();
  24664. body.push('}');
  24665. }
  24666. }
  24667. },
  24668. not: function(expression) {
  24669. return '!(' + expression + ')';
  24670. },
  24671. notNull: function(expression) {
  24672. return expression + '!=null';
  24673. },
  24674. nonComputedMember: function(left, right) {
  24675. return left + '.' + right;
  24676. },
  24677. computedMember: function(left, right) {
  24678. return left + '[' + right + ']';
  24679. },
  24680. member: function(left, right, computed) {
  24681. if (computed) return this.computedMember(left, right);
  24682. return this.nonComputedMember(left, right);
  24683. },
  24684. addEnsureSafeObject: function(item) {
  24685. this.current().body.push(this.ensureSafeObject(item), ';');
  24686. },
  24687. addEnsureSafeMemberName: function(item) {
  24688. this.current().body.push(this.ensureSafeMemberName(item), ';');
  24689. },
  24690. addEnsureSafeFunction: function(item) {
  24691. this.current().body.push(this.ensureSafeFunction(item), ';');
  24692. },
  24693. addEnsureSafeAssignContext: function(item) {
  24694. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  24695. },
  24696. ensureSafeObject: function(item) {
  24697. return 'ensureSafeObject(' + item + ',text)';
  24698. },
  24699. ensureSafeMemberName: function(item) {
  24700. return 'ensureSafeMemberName(' + item + ',text)';
  24701. },
  24702. ensureSafeFunction: function(item) {
  24703. return 'ensureSafeFunction(' + item + ',text)';
  24704. },
  24705. getStringValue: function(item) {
  24706. this.assign(item, 'getStringValue(' + item + ')');
  24707. },
  24708. ensureSafeAssignContext: function(item) {
  24709. return 'ensureSafeAssignContext(' + item + ',text)';
  24710. },
  24711. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  24712. var self = this;
  24713. return function() {
  24714. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  24715. };
  24716. },
  24717. lazyAssign: function(id, value) {
  24718. var self = this;
  24719. return function() {
  24720. self.assign(id, value);
  24721. };
  24722. },
  24723. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  24724. stringEscapeFn: function(c) {
  24725. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  24726. },
  24727. escape: function(value) {
  24728. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  24729. if (isNumber(value)) return value.toString();
  24730. if (value === true) return 'true';
  24731. if (value === false) return 'false';
  24732. if (value === null) return 'null';
  24733. if (typeof value === 'undefined') return 'undefined';
  24734. throw $parseMinErr('esc', 'IMPOSSIBLE');
  24735. },
  24736. nextId: function(skip, init) {
  24737. var id = 'v' + (this.state.nextId++);
  24738. if (!skip) {
  24739. this.current().vars.push(id + (init ? '=' + init : ''));
  24740. }
  24741. return id;
  24742. },
  24743. current: function() {
  24744. return this.state[this.state.computing];
  24745. }
  24746. };
  24747. function ASTInterpreter(astBuilder, $filter) {
  24748. this.astBuilder = astBuilder;
  24749. this.$filter = $filter;
  24750. }
  24751. ASTInterpreter.prototype = {
  24752. compile: function(expression, expensiveChecks) {
  24753. var self = this;
  24754. var ast = this.astBuilder.ast(expression);
  24755. this.expression = expression;
  24756. this.expensiveChecks = expensiveChecks;
  24757. findConstantAndWatchExpressions(ast, self.$filter);
  24758. var assignable;
  24759. var assign;
  24760. if ((assignable = assignableAST(ast))) {
  24761. assign = this.recurse(assignable);
  24762. }
  24763. var toWatch = getInputs(ast.body);
  24764. var inputs;
  24765. if (toWatch) {
  24766. inputs = [];
  24767. forEach(toWatch, function(watch, key) {
  24768. var input = self.recurse(watch);
  24769. watch.input = input;
  24770. inputs.push(input);
  24771. watch.watchId = key;
  24772. });
  24773. }
  24774. var expressions = [];
  24775. forEach(ast.body, function(expression) {
  24776. expressions.push(self.recurse(expression.expression));
  24777. });
  24778. var fn = ast.body.length === 0 ? noop :
  24779. ast.body.length === 1 ? expressions[0] :
  24780. function(scope, locals) {
  24781. var lastValue;
  24782. forEach(expressions, function(exp) {
  24783. lastValue = exp(scope, locals);
  24784. });
  24785. return lastValue;
  24786. };
  24787. if (assign) {
  24788. fn.assign = function(scope, value, locals) {
  24789. return assign(scope, locals, value);
  24790. };
  24791. }
  24792. if (inputs) {
  24793. fn.inputs = inputs;
  24794. }
  24795. fn.literal = isLiteral(ast);
  24796. fn.constant = isConstant(ast);
  24797. return fn;
  24798. },
  24799. recurse: function(ast, context, create) {
  24800. var left, right, self = this, args, expression;
  24801. if (ast.input) {
  24802. return this.inputs(ast.input, ast.watchId);
  24803. }
  24804. switch (ast.type) {
  24805. case AST.Literal:
  24806. return this.value(ast.value, context);
  24807. case AST.UnaryExpression:
  24808. right = this.recurse(ast.argument);
  24809. return this['unary' + ast.operator](right, context);
  24810. case AST.BinaryExpression:
  24811. left = this.recurse(ast.left);
  24812. right = this.recurse(ast.right);
  24813. return this['binary' + ast.operator](left, right, context);
  24814. case AST.LogicalExpression:
  24815. left = this.recurse(ast.left);
  24816. right = this.recurse(ast.right);
  24817. return this['binary' + ast.operator](left, right, context);
  24818. case AST.ConditionalExpression:
  24819. return this['ternary?:'](
  24820. this.recurse(ast.test),
  24821. this.recurse(ast.alternate),
  24822. this.recurse(ast.consequent),
  24823. context
  24824. );
  24825. case AST.Identifier:
  24826. ensureSafeMemberName(ast.name, self.expression);
  24827. return self.identifier(ast.name,
  24828. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  24829. context, create, self.expression);
  24830. case AST.MemberExpression:
  24831. left = this.recurse(ast.object, false, !!create);
  24832. if (!ast.computed) {
  24833. ensureSafeMemberName(ast.property.name, self.expression);
  24834. right = ast.property.name;
  24835. }
  24836. if (ast.computed) right = this.recurse(ast.property);
  24837. return ast.computed ?
  24838. this.computedMember(left, right, context, create, self.expression) :
  24839. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  24840. case AST.CallExpression:
  24841. args = [];
  24842. forEach(ast.arguments, function(expr) {
  24843. args.push(self.recurse(expr));
  24844. });
  24845. if (ast.filter) right = this.$filter(ast.callee.name);
  24846. if (!ast.filter) right = this.recurse(ast.callee, true);
  24847. return ast.filter ?
  24848. function(scope, locals, assign, inputs) {
  24849. var values = [];
  24850. for (var i = 0; i < args.length; ++i) {
  24851. values.push(args[i](scope, locals, assign, inputs));
  24852. }
  24853. var value = right.apply(undefined, values, inputs);
  24854. return context ? {context: undefined, name: undefined, value: value} : value;
  24855. } :
  24856. function(scope, locals, assign, inputs) {
  24857. var rhs = right(scope, locals, assign, inputs);
  24858. var value;
  24859. if (rhs.value != null) {
  24860. ensureSafeObject(rhs.context, self.expression);
  24861. ensureSafeFunction(rhs.value, self.expression);
  24862. var values = [];
  24863. for (var i = 0; i < args.length; ++i) {
  24864. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  24865. }
  24866. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  24867. }
  24868. return context ? {value: value} : value;
  24869. };
  24870. case AST.AssignmentExpression:
  24871. left = this.recurse(ast.left, true, 1);
  24872. right = this.recurse(ast.right);
  24873. return function(scope, locals, assign, inputs) {
  24874. var lhs = left(scope, locals, assign, inputs);
  24875. var rhs = right(scope, locals, assign, inputs);
  24876. ensureSafeObject(lhs.value, self.expression);
  24877. ensureSafeAssignContext(lhs.context);
  24878. lhs.context[lhs.name] = rhs;
  24879. return context ? {value: rhs} : rhs;
  24880. };
  24881. case AST.ArrayExpression:
  24882. args = [];
  24883. forEach(ast.elements, function(expr) {
  24884. args.push(self.recurse(expr));
  24885. });
  24886. return function(scope, locals, assign, inputs) {
  24887. var value = [];
  24888. for (var i = 0; i < args.length; ++i) {
  24889. value.push(args[i](scope, locals, assign, inputs));
  24890. }
  24891. return context ? {value: value} : value;
  24892. };
  24893. case AST.ObjectExpression:
  24894. args = [];
  24895. forEach(ast.properties, function(property) {
  24896. args.push({key: property.key.type === AST.Identifier ?
  24897. property.key.name :
  24898. ('' + property.key.value),
  24899. value: self.recurse(property.value)
  24900. });
  24901. });
  24902. return function(scope, locals, assign, inputs) {
  24903. var value = {};
  24904. for (var i = 0; i < args.length; ++i) {
  24905. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  24906. }
  24907. return context ? {value: value} : value;
  24908. };
  24909. case AST.ThisExpression:
  24910. return function(scope) {
  24911. return context ? {value: scope} : scope;
  24912. };
  24913. case AST.LocalsExpression:
  24914. return function(scope, locals) {
  24915. return context ? {value: locals} : locals;
  24916. };
  24917. case AST.NGValueParameter:
  24918. return function(scope, locals, assign) {
  24919. return context ? {value: assign} : assign;
  24920. };
  24921. }
  24922. },
  24923. 'unary+': function(argument, context) {
  24924. return function(scope, locals, assign, inputs) {
  24925. var arg = argument(scope, locals, assign, inputs);
  24926. if (isDefined(arg)) {
  24927. arg = +arg;
  24928. } else {
  24929. arg = 0;
  24930. }
  24931. return context ? {value: arg} : arg;
  24932. };
  24933. },
  24934. 'unary-': function(argument, context) {
  24935. return function(scope, locals, assign, inputs) {
  24936. var arg = argument(scope, locals, assign, inputs);
  24937. if (isDefined(arg)) {
  24938. arg = -arg;
  24939. } else {
  24940. arg = 0;
  24941. }
  24942. return context ? {value: arg} : arg;
  24943. };
  24944. },
  24945. 'unary!': function(argument, context) {
  24946. return function(scope, locals, assign, inputs) {
  24947. var arg = !argument(scope, locals, assign, inputs);
  24948. return context ? {value: arg} : arg;
  24949. };
  24950. },
  24951. 'binary+': function(left, right, context) {
  24952. return function(scope, locals, assign, inputs) {
  24953. var lhs = left(scope, locals, assign, inputs);
  24954. var rhs = right(scope, locals, assign, inputs);
  24955. var arg = plusFn(lhs, rhs);
  24956. return context ? {value: arg} : arg;
  24957. };
  24958. },
  24959. 'binary-': function(left, right, context) {
  24960. return function(scope, locals, assign, inputs) {
  24961. var lhs = left(scope, locals, assign, inputs);
  24962. var rhs = right(scope, locals, assign, inputs);
  24963. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  24964. return context ? {value: arg} : arg;
  24965. };
  24966. },
  24967. 'binary*': function(left, right, context) {
  24968. return function(scope, locals, assign, inputs) {
  24969. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  24970. return context ? {value: arg} : arg;
  24971. };
  24972. },
  24973. 'binary/': function(left, right, context) {
  24974. return function(scope, locals, assign, inputs) {
  24975. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  24976. return context ? {value: arg} : arg;
  24977. };
  24978. },
  24979. 'binary%': function(left, right, context) {
  24980. return function(scope, locals, assign, inputs) {
  24981. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  24982. return context ? {value: arg} : arg;
  24983. };
  24984. },
  24985. 'binary===': function(left, right, context) {
  24986. return function(scope, locals, assign, inputs) {
  24987. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  24988. return context ? {value: arg} : arg;
  24989. };
  24990. },
  24991. 'binary!==': function(left, right, context) {
  24992. return function(scope, locals, assign, inputs) {
  24993. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  24994. return context ? {value: arg} : arg;
  24995. };
  24996. },
  24997. 'binary==': function(left, right, context) {
  24998. return function(scope, locals, assign, inputs) {
  24999. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  25000. return context ? {value: arg} : arg;
  25001. };
  25002. },
  25003. 'binary!=': function(left, right, context) {
  25004. return function(scope, locals, assign, inputs) {
  25005. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  25006. return context ? {value: arg} : arg;
  25007. };
  25008. },
  25009. 'binary<': function(left, right, context) {
  25010. return function(scope, locals, assign, inputs) {
  25011. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  25012. return context ? {value: arg} : arg;
  25013. };
  25014. },
  25015. 'binary>': function(left, right, context) {
  25016. return function(scope, locals, assign, inputs) {
  25017. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  25018. return context ? {value: arg} : arg;
  25019. };
  25020. },
  25021. 'binary<=': function(left, right, context) {
  25022. return function(scope, locals, assign, inputs) {
  25023. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  25024. return context ? {value: arg} : arg;
  25025. };
  25026. },
  25027. 'binary>=': function(left, right, context) {
  25028. return function(scope, locals, assign, inputs) {
  25029. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  25030. return context ? {value: arg} : arg;
  25031. };
  25032. },
  25033. 'binary&&': function(left, right, context) {
  25034. return function(scope, locals, assign, inputs) {
  25035. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  25036. return context ? {value: arg} : arg;
  25037. };
  25038. },
  25039. 'binary||': function(left, right, context) {
  25040. return function(scope, locals, assign, inputs) {
  25041. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  25042. return context ? {value: arg} : arg;
  25043. };
  25044. },
  25045. 'ternary?:': function(test, alternate, consequent, context) {
  25046. return function(scope, locals, assign, inputs) {
  25047. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  25048. return context ? {value: arg} : arg;
  25049. };
  25050. },
  25051. value: function(value, context) {
  25052. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  25053. },
  25054. identifier: function(name, expensiveChecks, context, create, expression) {
  25055. return function(scope, locals, assign, inputs) {
  25056. var base = locals && (name in locals) ? locals : scope;
  25057. if (create && create !== 1 && base && !(base[name])) {
  25058. base[name] = {};
  25059. }
  25060. var value = base ? base[name] : undefined;
  25061. if (expensiveChecks) {
  25062. ensureSafeObject(value, expression);
  25063. }
  25064. if (context) {
  25065. return {context: base, name: name, value: value};
  25066. } else {
  25067. return value;
  25068. }
  25069. };
  25070. },
  25071. computedMember: function(left, right, context, create, expression) {
  25072. return function(scope, locals, assign, inputs) {
  25073. var lhs = left(scope, locals, assign, inputs);
  25074. var rhs;
  25075. var value;
  25076. if (lhs != null) {
  25077. rhs = right(scope, locals, assign, inputs);
  25078. rhs = getStringValue(rhs);
  25079. ensureSafeMemberName(rhs, expression);
  25080. if (create && create !== 1) {
  25081. ensureSafeAssignContext(lhs);
  25082. if (lhs && !(lhs[rhs])) {
  25083. lhs[rhs] = {};
  25084. }
  25085. }
  25086. value = lhs[rhs];
  25087. ensureSafeObject(value, expression);
  25088. }
  25089. if (context) {
  25090. return {context: lhs, name: rhs, value: value};
  25091. } else {
  25092. return value;
  25093. }
  25094. };
  25095. },
  25096. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  25097. return function(scope, locals, assign, inputs) {
  25098. var lhs = left(scope, locals, assign, inputs);
  25099. if (create && create !== 1) {
  25100. ensureSafeAssignContext(lhs);
  25101. if (lhs && !(lhs[right])) {
  25102. lhs[right] = {};
  25103. }
  25104. }
  25105. var value = lhs != null ? lhs[right] : undefined;
  25106. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  25107. ensureSafeObject(value, expression);
  25108. }
  25109. if (context) {
  25110. return {context: lhs, name: right, value: value};
  25111. } else {
  25112. return value;
  25113. }
  25114. };
  25115. },
  25116. inputs: function(input, watchId) {
  25117. return function(scope, value, locals, inputs) {
  25118. if (inputs) return inputs[watchId];
  25119. return input(scope, value, locals);
  25120. };
  25121. }
  25122. };
  25123. /**
  25124. * @constructor
  25125. */
  25126. var Parser = function(lexer, $filter, options) {
  25127. this.lexer = lexer;
  25128. this.$filter = $filter;
  25129. this.options = options;
  25130. this.ast = new AST(lexer, options);
  25131. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  25132. new ASTCompiler(this.ast, $filter);
  25133. };
  25134. Parser.prototype = {
  25135. constructor: Parser,
  25136. parse: function(text) {
  25137. return this.astCompiler.compile(text, this.options.expensiveChecks);
  25138. }
  25139. };
  25140. function isPossiblyDangerousMemberName(name) {
  25141. return name == 'constructor';
  25142. }
  25143. var objectValueOf = Object.prototype.valueOf;
  25144. function getValueOf(value) {
  25145. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  25146. }
  25147. ///////////////////////////////////
  25148. /**
  25149. * @ngdoc service
  25150. * @name $parse
  25151. * @kind function
  25152. *
  25153. * @description
  25154. *
  25155. * Converts Angular {@link guide/expression expression} into a function.
  25156. *
  25157. * ```js
  25158. * var getter = $parse('user.name');
  25159. * var setter = getter.assign;
  25160. * var context = {user:{name:'angular'}};
  25161. * var locals = {user:{name:'local'}};
  25162. *
  25163. * expect(getter(context)).toEqual('angular');
  25164. * setter(context, 'newValue');
  25165. * expect(context.user.name).toEqual('newValue');
  25166. * expect(getter(context, locals)).toEqual('local');
  25167. * ```
  25168. *
  25169. *
  25170. * @param {string} expression String expression to compile.
  25171. * @returns {function(context, locals)} a function which represents the compiled expression:
  25172. *
  25173. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  25174. * are evaluated against (typically a scope object).
  25175. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  25176. * `context`.
  25177. *
  25178. * The returned function also has the following properties:
  25179. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  25180. * literal.
  25181. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  25182. * constant literals.
  25183. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  25184. * set to a function to change its value on the given context.
  25185. *
  25186. */
  25187. /**
  25188. * @ngdoc provider
  25189. * @name $parseProvider
  25190. *
  25191. * @description
  25192. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  25193. * service.
  25194. */
  25195. function $ParseProvider() {
  25196. var cacheDefault = createMap();
  25197. var cacheExpensive = createMap();
  25198. var literals = {
  25199. 'true': true,
  25200. 'false': false,
  25201. 'null': null,
  25202. 'undefined': undefined
  25203. };
  25204. /**
  25205. * @ngdoc method
  25206. * @name $parseProvider#addLiteral
  25207. * @description
  25208. *
  25209. * Configure $parse service to add literal values that will be present as literal at expressions.
  25210. *
  25211. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  25212. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  25213. *
  25214. **/
  25215. this.addLiteral = function(literalName, literalValue) {
  25216. literals[literalName] = literalValue;
  25217. };
  25218. this.$get = ['$filter', function($filter) {
  25219. var noUnsafeEval = csp().noUnsafeEval;
  25220. var $parseOptions = {
  25221. csp: noUnsafeEval,
  25222. expensiveChecks: false,
  25223. literals: copy(literals)
  25224. },
  25225. $parseOptionsExpensive = {
  25226. csp: noUnsafeEval,
  25227. expensiveChecks: true,
  25228. literals: copy(literals)
  25229. };
  25230. var runningChecksEnabled = false;
  25231. $parse.$$runningExpensiveChecks = function() {
  25232. return runningChecksEnabled;
  25233. };
  25234. return $parse;
  25235. function $parse(exp, interceptorFn, expensiveChecks) {
  25236. var parsedExpression, oneTime, cacheKey;
  25237. expensiveChecks = expensiveChecks || runningChecksEnabled;
  25238. switch (typeof exp) {
  25239. case 'string':
  25240. exp = exp.trim();
  25241. cacheKey = exp;
  25242. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  25243. parsedExpression = cache[cacheKey];
  25244. if (!parsedExpression) {
  25245. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  25246. oneTime = true;
  25247. exp = exp.substring(2);
  25248. }
  25249. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  25250. var lexer = new Lexer(parseOptions);
  25251. var parser = new Parser(lexer, $filter, parseOptions);
  25252. parsedExpression = parser.parse(exp);
  25253. if (parsedExpression.constant) {
  25254. parsedExpression.$$watchDelegate = constantWatchDelegate;
  25255. } else if (oneTime) {
  25256. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  25257. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  25258. } else if (parsedExpression.inputs) {
  25259. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  25260. }
  25261. if (expensiveChecks) {
  25262. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  25263. }
  25264. cache[cacheKey] = parsedExpression;
  25265. }
  25266. return addInterceptor(parsedExpression, interceptorFn);
  25267. case 'function':
  25268. return addInterceptor(exp, interceptorFn);
  25269. default:
  25270. return addInterceptor(noop, interceptorFn);
  25271. }
  25272. }
  25273. function expensiveChecksInterceptor(fn) {
  25274. if (!fn) return fn;
  25275. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  25276. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  25277. expensiveCheckFn.constant = fn.constant;
  25278. expensiveCheckFn.literal = fn.literal;
  25279. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  25280. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  25281. }
  25282. expensiveCheckFn.inputs = fn.inputs;
  25283. return expensiveCheckFn;
  25284. function expensiveCheckFn(scope, locals, assign, inputs) {
  25285. var expensiveCheckOldValue = runningChecksEnabled;
  25286. runningChecksEnabled = true;
  25287. try {
  25288. return fn(scope, locals, assign, inputs);
  25289. } finally {
  25290. runningChecksEnabled = expensiveCheckOldValue;
  25291. }
  25292. }
  25293. }
  25294. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  25295. if (newValue == null || oldValueOfValue == null) { // null/undefined
  25296. return newValue === oldValueOfValue;
  25297. }
  25298. if (typeof newValue === 'object') {
  25299. // attempt to convert the value to a primitive type
  25300. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  25301. // be cheaply dirty-checked
  25302. newValue = getValueOf(newValue);
  25303. if (typeof newValue === 'object') {
  25304. // objects/arrays are not supported - deep-watching them would be too expensive
  25305. return false;
  25306. }
  25307. // fall-through to the primitive equality check
  25308. }
  25309. //Primitive or NaN
  25310. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  25311. }
  25312. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  25313. var inputExpressions = parsedExpression.inputs;
  25314. var lastResult;
  25315. if (inputExpressions.length === 1) {
  25316. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  25317. inputExpressions = inputExpressions[0];
  25318. return scope.$watch(function expressionInputWatch(scope) {
  25319. var newInputValue = inputExpressions(scope);
  25320. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  25321. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  25322. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  25323. }
  25324. return lastResult;
  25325. }, listener, objectEquality, prettyPrintExpression);
  25326. }
  25327. var oldInputValueOfValues = [];
  25328. var oldInputValues = [];
  25329. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  25330. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  25331. oldInputValues[i] = null;
  25332. }
  25333. return scope.$watch(function expressionInputsWatch(scope) {
  25334. var changed = false;
  25335. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  25336. var newInputValue = inputExpressions[i](scope);
  25337. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  25338. oldInputValues[i] = newInputValue;
  25339. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  25340. }
  25341. }
  25342. if (changed) {
  25343. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  25344. }
  25345. return lastResult;
  25346. }, listener, objectEquality, prettyPrintExpression);
  25347. }
  25348. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25349. var unwatch, lastValue;
  25350. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  25351. return parsedExpression(scope);
  25352. }, function oneTimeListener(value, old, scope) {
  25353. lastValue = value;
  25354. if (isFunction(listener)) {
  25355. listener.apply(this, arguments);
  25356. }
  25357. if (isDefined(value)) {
  25358. scope.$$postDigest(function() {
  25359. if (isDefined(lastValue)) {
  25360. unwatch();
  25361. }
  25362. });
  25363. }
  25364. }, objectEquality);
  25365. }
  25366. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25367. var unwatch, lastValue;
  25368. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  25369. return parsedExpression(scope);
  25370. }, function oneTimeListener(value, old, scope) {
  25371. lastValue = value;
  25372. if (isFunction(listener)) {
  25373. listener.call(this, value, old, scope);
  25374. }
  25375. if (isAllDefined(value)) {
  25376. scope.$$postDigest(function() {
  25377. if (isAllDefined(lastValue)) unwatch();
  25378. });
  25379. }
  25380. }, objectEquality);
  25381. function isAllDefined(value) {
  25382. var allDefined = true;
  25383. forEach(value, function(val) {
  25384. if (!isDefined(val)) allDefined = false;
  25385. });
  25386. return allDefined;
  25387. }
  25388. }
  25389. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25390. var unwatch;
  25391. return unwatch = scope.$watch(function constantWatch(scope) {
  25392. unwatch();
  25393. return parsedExpression(scope);
  25394. }, listener, objectEquality);
  25395. }
  25396. function addInterceptor(parsedExpression, interceptorFn) {
  25397. if (!interceptorFn) return parsedExpression;
  25398. var watchDelegate = parsedExpression.$$watchDelegate;
  25399. var useInputs = false;
  25400. var regularWatch =
  25401. watchDelegate !== oneTimeLiteralWatchDelegate &&
  25402. watchDelegate !== oneTimeWatchDelegate;
  25403. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  25404. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  25405. return interceptorFn(value, scope, locals);
  25406. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  25407. var value = parsedExpression(scope, locals, assign, inputs);
  25408. var result = interceptorFn(value, scope, locals);
  25409. // we only return the interceptor's result if the
  25410. // initial value is defined (for bind-once)
  25411. return isDefined(value) ? result : value;
  25412. };
  25413. // Propagate $$watchDelegates other then inputsWatchDelegate
  25414. if (parsedExpression.$$watchDelegate &&
  25415. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  25416. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  25417. } else if (!interceptorFn.$stateful) {
  25418. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  25419. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  25420. fn.$$watchDelegate = inputsWatchDelegate;
  25421. useInputs = !parsedExpression.inputs;
  25422. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  25423. }
  25424. return fn;
  25425. }
  25426. }];
  25427. }
  25428. /**
  25429. * @ngdoc service
  25430. * @name $q
  25431. * @requires $rootScope
  25432. *
  25433. * @description
  25434. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  25435. * when they are done processing.
  25436. *
  25437. * This is an implementation of promises/deferred objects inspired by
  25438. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  25439. *
  25440. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  25441. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  25442. *
  25443. * # $q constructor
  25444. *
  25445. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  25446. * function as the first argument. This is similar to the native Promise implementation from ES6,
  25447. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  25448. *
  25449. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  25450. * available yet.
  25451. *
  25452. * It can be used like so:
  25453. *
  25454. * ```js
  25455. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  25456. * // are available in the current lexical scope (they could have been injected or passed in).
  25457. *
  25458. * function asyncGreet(name) {
  25459. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  25460. * return $q(function(resolve, reject) {
  25461. * setTimeout(function() {
  25462. * if (okToGreet(name)) {
  25463. * resolve('Hello, ' + name + '!');
  25464. * } else {
  25465. * reject('Greeting ' + name + ' is not allowed.');
  25466. * }
  25467. * }, 1000);
  25468. * });
  25469. * }
  25470. *
  25471. * var promise = asyncGreet('Robin Hood');
  25472. * promise.then(function(greeting) {
  25473. * alert('Success: ' + greeting);
  25474. * }, function(reason) {
  25475. * alert('Failed: ' + reason);
  25476. * });
  25477. * ```
  25478. *
  25479. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  25480. *
  25481. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  25482. *
  25483. * However, the more traditional CommonJS-style usage is still available, and documented below.
  25484. *
  25485. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  25486. * interface for interacting with an object that represents the result of an action that is
  25487. * performed asynchronously, and may or may not be finished at any given point in time.
  25488. *
  25489. * From the perspective of dealing with error handling, deferred and promise APIs are to
  25490. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  25491. *
  25492. * ```js
  25493. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  25494. * // are available in the current lexical scope (they could have been injected or passed in).
  25495. *
  25496. * function asyncGreet(name) {
  25497. * var deferred = $q.defer();
  25498. *
  25499. * setTimeout(function() {
  25500. * deferred.notify('About to greet ' + name + '.');
  25501. *
  25502. * if (okToGreet(name)) {
  25503. * deferred.resolve('Hello, ' + name + '!');
  25504. * } else {
  25505. * deferred.reject('Greeting ' + name + ' is not allowed.');
  25506. * }
  25507. * }, 1000);
  25508. *
  25509. * return deferred.promise;
  25510. * }
  25511. *
  25512. * var promise = asyncGreet('Robin Hood');
  25513. * promise.then(function(greeting) {
  25514. * alert('Success: ' + greeting);
  25515. * }, function(reason) {
  25516. * alert('Failed: ' + reason);
  25517. * }, function(update) {
  25518. * alert('Got notification: ' + update);
  25519. * });
  25520. * ```
  25521. *
  25522. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  25523. * comes in the way of guarantees that promise and deferred APIs make, see
  25524. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  25525. *
  25526. * Additionally the promise api allows for composition that is very hard to do with the
  25527. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  25528. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  25529. * section on serial or parallel joining of promises.
  25530. *
  25531. * # The Deferred API
  25532. *
  25533. * A new instance of deferred is constructed by calling `$q.defer()`.
  25534. *
  25535. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  25536. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  25537. * of the task.
  25538. *
  25539. * **Methods**
  25540. *
  25541. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  25542. * constructed via `$q.reject`, the promise will be rejected instead.
  25543. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  25544. * resolving it with a rejection constructed via `$q.reject`.
  25545. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  25546. * multiple times before the promise is either resolved or rejected.
  25547. *
  25548. * **Properties**
  25549. *
  25550. * - promise – `{Promise}` – promise object associated with this deferred.
  25551. *
  25552. *
  25553. * # The Promise API
  25554. *
  25555. * A new promise instance is created when a deferred instance is created and can be retrieved by
  25556. * calling `deferred.promise`.
  25557. *
  25558. * The purpose of the promise object is to allow for interested parties to get access to the result
  25559. * of the deferred task when it completes.
  25560. *
  25561. * **Methods**
  25562. *
  25563. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  25564. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  25565. * as soon as the result is available. The callbacks are called with a single argument: the result
  25566. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  25567. * provide a progress indication, before the promise is resolved or rejected.
  25568. *
  25569. * This method *returns a new promise* which is resolved or rejected via the return value of the
  25570. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  25571. * with the value which is resolved in that promise using
  25572. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  25573. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  25574. * resolved or rejected from the notifyCallback method.
  25575. *
  25576. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  25577. *
  25578. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  25579. * but to do so without modifying the final value. This is useful to release resources or do some
  25580. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  25581. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  25582. * more information.
  25583. *
  25584. * # Chaining promises
  25585. *
  25586. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  25587. * possible to create a chain of promises:
  25588. *
  25589. * ```js
  25590. * promiseB = promiseA.then(function(result) {
  25591. * return result + 1;
  25592. * });
  25593. *
  25594. * // promiseB will be resolved immediately after promiseA is resolved and its value
  25595. * // will be the result of promiseA incremented by 1
  25596. * ```
  25597. *
  25598. * It is possible to create chains of any length and since a promise can be resolved with another
  25599. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  25600. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  25601. * $http's response interceptors.
  25602. *
  25603. *
  25604. * # Differences between Kris Kowal's Q and $q
  25605. *
  25606. * There are two main differences:
  25607. *
  25608. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  25609. * mechanism in angular, which means faster propagation of resolution or rejection into your
  25610. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  25611. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  25612. * all the important functionality needed for common async tasks.
  25613. *
  25614. * # Testing
  25615. *
  25616. * ```js
  25617. * it('should simulate promise', inject(function($q, $rootScope) {
  25618. * var deferred = $q.defer();
  25619. * var promise = deferred.promise;
  25620. * var resolvedValue;
  25621. *
  25622. * promise.then(function(value) { resolvedValue = value; });
  25623. * expect(resolvedValue).toBeUndefined();
  25624. *
  25625. * // Simulate resolving of promise
  25626. * deferred.resolve(123);
  25627. * // Note that the 'then' function does not get called synchronously.
  25628. * // This is because we want the promise API to always be async, whether or not
  25629. * // it got called synchronously or asynchronously.
  25630. * expect(resolvedValue).toBeUndefined();
  25631. *
  25632. * // Propagate promise resolution to 'then' functions using $apply().
  25633. * $rootScope.$apply();
  25634. * expect(resolvedValue).toEqual(123);
  25635. * }));
  25636. * ```
  25637. *
  25638. * @param {function(function, function)} resolver Function which is responsible for resolving or
  25639. * rejecting the newly created promise. The first parameter is a function which resolves the
  25640. * promise, the second parameter is a function which rejects the promise.
  25641. *
  25642. * @returns {Promise} The newly created promise.
  25643. */
  25644. function $QProvider() {
  25645. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  25646. return qFactory(function(callback) {
  25647. $rootScope.$evalAsync(callback);
  25648. }, $exceptionHandler);
  25649. }];
  25650. }
  25651. function $$QProvider() {
  25652. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  25653. return qFactory(function(callback) {
  25654. $browser.defer(callback);
  25655. }, $exceptionHandler);
  25656. }];
  25657. }
  25658. /**
  25659. * Constructs a promise manager.
  25660. *
  25661. * @param {function(function)} nextTick Function for executing functions in the next turn.
  25662. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  25663. * debugging purposes.
  25664. * @returns {object} Promise manager.
  25665. */
  25666. function qFactory(nextTick, exceptionHandler) {
  25667. var $qMinErr = minErr('$q', TypeError);
  25668. /**
  25669. * @ngdoc method
  25670. * @name ng.$q#defer
  25671. * @kind function
  25672. *
  25673. * @description
  25674. * Creates a `Deferred` object which represents a task which will finish in the future.
  25675. *
  25676. * @returns {Deferred} Returns a new instance of deferred.
  25677. */
  25678. var defer = function() {
  25679. var d = new Deferred();
  25680. //Necessary to support unbound execution :/
  25681. d.resolve = simpleBind(d, d.resolve);
  25682. d.reject = simpleBind(d, d.reject);
  25683. d.notify = simpleBind(d, d.notify);
  25684. return d;
  25685. };
  25686. function Promise() {
  25687. this.$$state = { status: 0 };
  25688. }
  25689. extend(Promise.prototype, {
  25690. then: function(onFulfilled, onRejected, progressBack) {
  25691. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  25692. return this;
  25693. }
  25694. var result = new Deferred();
  25695. this.$$state.pending = this.$$state.pending || [];
  25696. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  25697. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  25698. return result.promise;
  25699. },
  25700. "catch": function(callback) {
  25701. return this.then(null, callback);
  25702. },
  25703. "finally": function(callback, progressBack) {
  25704. return this.then(function(value) {
  25705. return handleCallback(value, true, callback);
  25706. }, function(error) {
  25707. return handleCallback(error, false, callback);
  25708. }, progressBack);
  25709. }
  25710. });
  25711. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  25712. function simpleBind(context, fn) {
  25713. return function(value) {
  25714. fn.call(context, value);
  25715. };
  25716. }
  25717. function processQueue(state) {
  25718. var fn, deferred, pending;
  25719. pending = state.pending;
  25720. state.processScheduled = false;
  25721. state.pending = undefined;
  25722. for (var i = 0, ii = pending.length; i < ii; ++i) {
  25723. deferred = pending[i][0];
  25724. fn = pending[i][state.status];
  25725. try {
  25726. if (isFunction(fn)) {
  25727. deferred.resolve(fn(state.value));
  25728. } else if (state.status === 1) {
  25729. deferred.resolve(state.value);
  25730. } else {
  25731. deferred.reject(state.value);
  25732. }
  25733. } catch (e) {
  25734. deferred.reject(e);
  25735. exceptionHandler(e);
  25736. }
  25737. }
  25738. }
  25739. function scheduleProcessQueue(state) {
  25740. if (state.processScheduled || !state.pending) return;
  25741. state.processScheduled = true;
  25742. nextTick(function() { processQueue(state); });
  25743. }
  25744. function Deferred() {
  25745. this.promise = new Promise();
  25746. }
  25747. extend(Deferred.prototype, {
  25748. resolve: function(val) {
  25749. if (this.promise.$$state.status) return;
  25750. if (val === this.promise) {
  25751. this.$$reject($qMinErr(
  25752. 'qcycle',
  25753. "Expected promise to be resolved with value other than itself '{0}'",
  25754. val));
  25755. } else {
  25756. this.$$resolve(val);
  25757. }
  25758. },
  25759. $$resolve: function(val) {
  25760. var then;
  25761. var that = this;
  25762. var done = false;
  25763. try {
  25764. if ((isObject(val) || isFunction(val))) then = val && val.then;
  25765. if (isFunction(then)) {
  25766. this.promise.$$state.status = -1;
  25767. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  25768. } else {
  25769. this.promise.$$state.value = val;
  25770. this.promise.$$state.status = 1;
  25771. scheduleProcessQueue(this.promise.$$state);
  25772. }
  25773. } catch (e) {
  25774. rejectPromise(e);
  25775. exceptionHandler(e);
  25776. }
  25777. function resolvePromise(val) {
  25778. if (done) return;
  25779. done = true;
  25780. that.$$resolve(val);
  25781. }
  25782. function rejectPromise(val) {
  25783. if (done) return;
  25784. done = true;
  25785. that.$$reject(val);
  25786. }
  25787. },
  25788. reject: function(reason) {
  25789. if (this.promise.$$state.status) return;
  25790. this.$$reject(reason);
  25791. },
  25792. $$reject: function(reason) {
  25793. this.promise.$$state.value = reason;
  25794. this.promise.$$state.status = 2;
  25795. scheduleProcessQueue(this.promise.$$state);
  25796. },
  25797. notify: function(progress) {
  25798. var callbacks = this.promise.$$state.pending;
  25799. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  25800. nextTick(function() {
  25801. var callback, result;
  25802. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  25803. result = callbacks[i][0];
  25804. callback = callbacks[i][3];
  25805. try {
  25806. result.notify(isFunction(callback) ? callback(progress) : progress);
  25807. } catch (e) {
  25808. exceptionHandler(e);
  25809. }
  25810. }
  25811. });
  25812. }
  25813. }
  25814. });
  25815. /**
  25816. * @ngdoc method
  25817. * @name $q#reject
  25818. * @kind function
  25819. *
  25820. * @description
  25821. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  25822. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  25823. * a promise chain, you don't need to worry about it.
  25824. *
  25825. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  25826. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  25827. * a promise error callback and you want to forward the error to the promise derived from the
  25828. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  25829. * `reject`.
  25830. *
  25831. * ```js
  25832. * promiseB = promiseA.then(function(result) {
  25833. * // success: do something and resolve promiseB
  25834. * // with the old or a new result
  25835. * return result;
  25836. * }, function(reason) {
  25837. * // error: handle the error if possible and
  25838. * // resolve promiseB with newPromiseOrValue,
  25839. * // otherwise forward the rejection to promiseB
  25840. * if (canHandle(reason)) {
  25841. * // handle the error and recover
  25842. * return newPromiseOrValue;
  25843. * }
  25844. * return $q.reject(reason);
  25845. * });
  25846. * ```
  25847. *
  25848. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  25849. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  25850. */
  25851. var reject = function(reason) {
  25852. var result = new Deferred();
  25853. result.reject(reason);
  25854. return result.promise;
  25855. };
  25856. var makePromise = function makePromise(value, resolved) {
  25857. var result = new Deferred();
  25858. if (resolved) {
  25859. result.resolve(value);
  25860. } else {
  25861. result.reject(value);
  25862. }
  25863. return result.promise;
  25864. };
  25865. var handleCallback = function handleCallback(value, isResolved, callback) {
  25866. var callbackOutput = null;
  25867. try {
  25868. if (isFunction(callback)) callbackOutput = callback();
  25869. } catch (e) {
  25870. return makePromise(e, false);
  25871. }
  25872. if (isPromiseLike(callbackOutput)) {
  25873. return callbackOutput.then(function() {
  25874. return makePromise(value, isResolved);
  25875. }, function(error) {
  25876. return makePromise(error, false);
  25877. });
  25878. } else {
  25879. return makePromise(value, isResolved);
  25880. }
  25881. };
  25882. /**
  25883. * @ngdoc method
  25884. * @name $q#when
  25885. * @kind function
  25886. *
  25887. * @description
  25888. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  25889. * This is useful when you are dealing with an object that might or might not be a promise, or if
  25890. * the promise comes from a source that can't be trusted.
  25891. *
  25892. * @param {*} value Value or a promise
  25893. * @param {Function=} successCallback
  25894. * @param {Function=} errorCallback
  25895. * @param {Function=} progressCallback
  25896. * @returns {Promise} Returns a promise of the passed value or promise
  25897. */
  25898. var when = function(value, callback, errback, progressBack) {
  25899. var result = new Deferred();
  25900. result.resolve(value);
  25901. return result.promise.then(callback, errback, progressBack);
  25902. };
  25903. /**
  25904. * @ngdoc method
  25905. * @name $q#resolve
  25906. * @kind function
  25907. *
  25908. * @description
  25909. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  25910. *
  25911. * @param {*} value Value or a promise
  25912. * @param {Function=} successCallback
  25913. * @param {Function=} errorCallback
  25914. * @param {Function=} progressCallback
  25915. * @returns {Promise} Returns a promise of the passed value or promise
  25916. */
  25917. var resolve = when;
  25918. /**
  25919. * @ngdoc method
  25920. * @name $q#all
  25921. * @kind function
  25922. *
  25923. * @description
  25924. * Combines multiple promises into a single promise that is resolved when all of the input
  25925. * promises are resolved.
  25926. *
  25927. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  25928. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  25929. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  25930. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  25931. * with the same rejection value.
  25932. */
  25933. function all(promises) {
  25934. var deferred = new Deferred(),
  25935. counter = 0,
  25936. results = isArray(promises) ? [] : {};
  25937. forEach(promises, function(promise, key) {
  25938. counter++;
  25939. when(promise).then(function(value) {
  25940. if (results.hasOwnProperty(key)) return;
  25941. results[key] = value;
  25942. if (!(--counter)) deferred.resolve(results);
  25943. }, function(reason) {
  25944. if (results.hasOwnProperty(key)) return;
  25945. deferred.reject(reason);
  25946. });
  25947. });
  25948. if (counter === 0) {
  25949. deferred.resolve(results);
  25950. }
  25951. return deferred.promise;
  25952. }
  25953. var $Q = function Q(resolver) {
  25954. if (!isFunction(resolver)) {
  25955. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  25956. }
  25957. var deferred = new Deferred();
  25958. function resolveFn(value) {
  25959. deferred.resolve(value);
  25960. }
  25961. function rejectFn(reason) {
  25962. deferred.reject(reason);
  25963. }
  25964. resolver(resolveFn, rejectFn);
  25965. return deferred.promise;
  25966. };
  25967. // Let's make the instanceof operator work for promises, so that
  25968. // `new $q(fn) instanceof $q` would evaluate to true.
  25969. $Q.prototype = Promise.prototype;
  25970. $Q.defer = defer;
  25971. $Q.reject = reject;
  25972. $Q.when = when;
  25973. $Q.resolve = resolve;
  25974. $Q.all = all;
  25975. return $Q;
  25976. }
  25977. function $$RAFProvider() { //rAF
  25978. this.$get = ['$window', '$timeout', function($window, $timeout) {
  25979. var requestAnimationFrame = $window.requestAnimationFrame ||
  25980. $window.webkitRequestAnimationFrame;
  25981. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  25982. $window.webkitCancelAnimationFrame ||
  25983. $window.webkitCancelRequestAnimationFrame;
  25984. var rafSupported = !!requestAnimationFrame;
  25985. var raf = rafSupported
  25986. ? function(fn) {
  25987. var id = requestAnimationFrame(fn);
  25988. return function() {
  25989. cancelAnimationFrame(id);
  25990. };
  25991. }
  25992. : function(fn) {
  25993. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  25994. return function() {
  25995. $timeout.cancel(timer);
  25996. };
  25997. };
  25998. raf.supported = rafSupported;
  25999. return raf;
  26000. }];
  26001. }
  26002. /**
  26003. * DESIGN NOTES
  26004. *
  26005. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  26006. *
  26007. * The typical use of scope is to watch the expressions, which most of the time return the same
  26008. * value as last time so we optimize the operation.
  26009. *
  26010. * Closures construction is expensive in terms of speed as well as memory:
  26011. * - No closures, instead use prototypical inheritance for API
  26012. * - Internal state needs to be stored on scope directly, which means that private state is
  26013. * exposed as $$____ properties
  26014. *
  26015. * Loop operations are optimized by using while(count--) { ... }
  26016. * - This means that in order to keep the same order of execution as addition we have to add
  26017. * items to the array at the beginning (unshift) instead of at the end (push)
  26018. *
  26019. * Child scopes are created and removed often
  26020. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  26021. *
  26022. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  26023. * in the same way as watch. Watch requires return of the initialization function which is expensive
  26024. * to construct.
  26025. */
  26026. /**
  26027. * @ngdoc provider
  26028. * @name $rootScopeProvider
  26029. * @description
  26030. *
  26031. * Provider for the $rootScope service.
  26032. */
  26033. /**
  26034. * @ngdoc method
  26035. * @name $rootScopeProvider#digestTtl
  26036. * @description
  26037. *
  26038. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  26039. * assuming that the model is unstable.
  26040. *
  26041. * The current default is 10 iterations.
  26042. *
  26043. * In complex applications it's possible that the dependencies between `$watch`s will result in
  26044. * several digest iterations. However if an application needs more than the default 10 digest
  26045. * iterations for its model to stabilize then you should investigate what is causing the model to
  26046. * continuously change during the digest.
  26047. *
  26048. * Increasing the TTL could have performance implications, so you should not change it without
  26049. * proper justification.
  26050. *
  26051. * @param {number} limit The number of digest iterations.
  26052. */
  26053. /**
  26054. * @ngdoc service
  26055. * @name $rootScope
  26056. * @description
  26057. *
  26058. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  26059. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  26060. * between the model and the view, via a mechanism for watching the model for changes.
  26061. * They also provide event emission/broadcast and subscription facility. See the
  26062. * {@link guide/scope developer guide on scopes}.
  26063. */
  26064. function $RootScopeProvider() {
  26065. var TTL = 10;
  26066. var $rootScopeMinErr = minErr('$rootScope');
  26067. var lastDirtyWatch = null;
  26068. var applyAsyncId = null;
  26069. this.digestTtl = function(value) {
  26070. if (arguments.length) {
  26071. TTL = value;
  26072. }
  26073. return TTL;
  26074. };
  26075. function createChildScopeClass(parent) {
  26076. function ChildScope() {
  26077. this.$$watchers = this.$$nextSibling =
  26078. this.$$childHead = this.$$childTail = null;
  26079. this.$$listeners = {};
  26080. this.$$listenerCount = {};
  26081. this.$$watchersCount = 0;
  26082. this.$id = nextUid();
  26083. this.$$ChildScope = null;
  26084. }
  26085. ChildScope.prototype = parent;
  26086. return ChildScope;
  26087. }
  26088. this.$get = ['$exceptionHandler', '$parse', '$browser',
  26089. function($exceptionHandler, $parse, $browser) {
  26090. function destroyChildScope($event) {
  26091. $event.currentScope.$$destroyed = true;
  26092. }
  26093. function cleanUpScope($scope) {
  26094. if (msie === 9) {
  26095. // There is a memory leak in IE9 if all child scopes are not disconnected
  26096. // completely when a scope is destroyed. So this code will recurse up through
  26097. // all this scopes children
  26098. //
  26099. // See issue https://github.com/angular/angular.js/issues/10706
  26100. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  26101. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  26102. }
  26103. // The code below works around IE9 and V8's memory leaks
  26104. //
  26105. // See:
  26106. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  26107. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  26108. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  26109. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  26110. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  26111. }
  26112. /**
  26113. * @ngdoc type
  26114. * @name $rootScope.Scope
  26115. *
  26116. * @description
  26117. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  26118. * {@link auto.$injector $injector}. Child scopes are created using the
  26119. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  26120. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  26121. * an in-depth introduction and usage examples.
  26122. *
  26123. *
  26124. * # Inheritance
  26125. * A scope can inherit from a parent scope, as in this example:
  26126. * ```js
  26127. var parent = $rootScope;
  26128. var child = parent.$new();
  26129. parent.salutation = "Hello";
  26130. expect(child.salutation).toEqual('Hello');
  26131. child.salutation = "Welcome";
  26132. expect(child.salutation).toEqual('Welcome');
  26133. expect(parent.salutation).toEqual('Hello');
  26134. * ```
  26135. *
  26136. * When interacting with `Scope` in tests, additional helper methods are available on the
  26137. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  26138. * details.
  26139. *
  26140. *
  26141. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  26142. * provided for the current scope. Defaults to {@link ng}.
  26143. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  26144. * append/override services provided by `providers`. This is handy
  26145. * when unit-testing and having the need to override a default
  26146. * service.
  26147. * @returns {Object} Newly created scope.
  26148. *
  26149. */
  26150. function Scope() {
  26151. this.$id = nextUid();
  26152. this.$$phase = this.$parent = this.$$watchers =
  26153. this.$$nextSibling = this.$$prevSibling =
  26154. this.$$childHead = this.$$childTail = null;
  26155. this.$root = this;
  26156. this.$$destroyed = false;
  26157. this.$$listeners = {};
  26158. this.$$listenerCount = {};
  26159. this.$$watchersCount = 0;
  26160. this.$$isolateBindings = null;
  26161. }
  26162. /**
  26163. * @ngdoc property
  26164. * @name $rootScope.Scope#$id
  26165. *
  26166. * @description
  26167. * Unique scope ID (monotonically increasing) useful for debugging.
  26168. */
  26169. /**
  26170. * @ngdoc property
  26171. * @name $rootScope.Scope#$parent
  26172. *
  26173. * @description
  26174. * Reference to the parent scope.
  26175. */
  26176. /**
  26177. * @ngdoc property
  26178. * @name $rootScope.Scope#$root
  26179. *
  26180. * @description
  26181. * Reference to the root scope.
  26182. */
  26183. Scope.prototype = {
  26184. constructor: Scope,
  26185. /**
  26186. * @ngdoc method
  26187. * @name $rootScope.Scope#$new
  26188. * @kind function
  26189. *
  26190. * @description
  26191. * Creates a new child {@link ng.$rootScope.Scope scope}.
  26192. *
  26193. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  26194. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  26195. *
  26196. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  26197. * desired for the scope and its child scopes to be permanently detached from the parent and
  26198. * thus stop participating in model change detection and listener notification by invoking.
  26199. *
  26200. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  26201. * parent scope. The scope is isolated, as it can not see parent scope properties.
  26202. * When creating widgets, it is useful for the widget to not accidentally read parent
  26203. * state.
  26204. *
  26205. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  26206. * of the newly created scope. Defaults to `this` scope if not provided.
  26207. * This is used when creating a transclude scope to correctly place it
  26208. * in the scope hierarchy while maintaining the correct prototypical
  26209. * inheritance.
  26210. *
  26211. * @returns {Object} The newly created child scope.
  26212. *
  26213. */
  26214. $new: function(isolate, parent) {
  26215. var child;
  26216. parent = parent || this;
  26217. if (isolate) {
  26218. child = new Scope();
  26219. child.$root = this.$root;
  26220. } else {
  26221. // Only create a child scope class if somebody asks for one,
  26222. // but cache it to allow the VM to optimize lookups.
  26223. if (!this.$$ChildScope) {
  26224. this.$$ChildScope = createChildScopeClass(this);
  26225. }
  26226. child = new this.$$ChildScope();
  26227. }
  26228. child.$parent = parent;
  26229. child.$$prevSibling = parent.$$childTail;
  26230. if (parent.$$childHead) {
  26231. parent.$$childTail.$$nextSibling = child;
  26232. parent.$$childTail = child;
  26233. } else {
  26234. parent.$$childHead = parent.$$childTail = child;
  26235. }
  26236. // When the new scope is not isolated or we inherit from `this`, and
  26237. // the parent scope is destroyed, the property `$$destroyed` is inherited
  26238. // prototypically. In all other cases, this property needs to be set
  26239. // when the parent scope is destroyed.
  26240. // The listener needs to be added after the parent is set
  26241. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  26242. return child;
  26243. },
  26244. /**
  26245. * @ngdoc method
  26246. * @name $rootScope.Scope#$watch
  26247. * @kind function
  26248. *
  26249. * @description
  26250. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  26251. *
  26252. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  26253. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  26254. * its value when executed multiple times with the same input because it may be executed multiple
  26255. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  26256. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  26257. * - The `listener` is called only when the value from the current `watchExpression` and the
  26258. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  26259. * see below). Inequality is determined according to reference inequality,
  26260. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  26261. * via the `!==` Javascript operator, unless `objectEquality == true`
  26262. * (see next point)
  26263. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  26264. * according to the {@link angular.equals} function. To save the value of the object for
  26265. * later comparison, the {@link angular.copy} function is used. This therefore means that
  26266. * watching complex objects will have adverse memory and performance implications.
  26267. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  26268. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  26269. * iteration limit is 10 to prevent an infinite loop deadlock.
  26270. *
  26271. *
  26272. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  26273. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  26274. * multiple calls to your `watchExpression` because it will execute multiple times in a
  26275. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  26276. *
  26277. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  26278. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  26279. * watcher. In rare cases, this is undesirable because the listener is called when the result
  26280. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  26281. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  26282. * listener was called due to initialization.
  26283. *
  26284. *
  26285. *
  26286. * # Example
  26287. * ```js
  26288. // let's assume that scope was dependency injected as the $rootScope
  26289. var scope = $rootScope;
  26290. scope.name = 'misko';
  26291. scope.counter = 0;
  26292. expect(scope.counter).toEqual(0);
  26293. scope.$watch('name', function(newValue, oldValue) {
  26294. scope.counter = scope.counter + 1;
  26295. });
  26296. expect(scope.counter).toEqual(0);
  26297. scope.$digest();
  26298. // the listener is always called during the first $digest loop after it was registered
  26299. expect(scope.counter).toEqual(1);
  26300. scope.$digest();
  26301. // but now it will not be called unless the value changes
  26302. expect(scope.counter).toEqual(1);
  26303. scope.name = 'adam';
  26304. scope.$digest();
  26305. expect(scope.counter).toEqual(2);
  26306. // Using a function as a watchExpression
  26307. var food;
  26308. scope.foodCounter = 0;
  26309. expect(scope.foodCounter).toEqual(0);
  26310. scope.$watch(
  26311. // This function returns the value being watched. It is called for each turn of the $digest loop
  26312. function() { return food; },
  26313. // This is the change listener, called when the value returned from the above function changes
  26314. function(newValue, oldValue) {
  26315. if ( newValue !== oldValue ) {
  26316. // Only increment the counter if the value changed
  26317. scope.foodCounter = scope.foodCounter + 1;
  26318. }
  26319. }
  26320. );
  26321. // No digest has been run so the counter will be zero
  26322. expect(scope.foodCounter).toEqual(0);
  26323. // Run the digest but since food has not changed count will still be zero
  26324. scope.$digest();
  26325. expect(scope.foodCounter).toEqual(0);
  26326. // Update food and run digest. Now the counter will increment
  26327. food = 'cheeseburger';
  26328. scope.$digest();
  26329. expect(scope.foodCounter).toEqual(1);
  26330. * ```
  26331. *
  26332. *
  26333. *
  26334. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  26335. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  26336. * a call to the `listener`.
  26337. *
  26338. * - `string`: Evaluated as {@link guide/expression expression}
  26339. * - `function(scope)`: called with current `scope` as a parameter.
  26340. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  26341. * of `watchExpression` changes.
  26342. *
  26343. * - `newVal` contains the current value of the `watchExpression`
  26344. * - `oldVal` contains the previous value of the `watchExpression`
  26345. * - `scope` refers to the current scope
  26346. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  26347. * comparing for reference equality.
  26348. * @returns {function()} Returns a deregistration function for this listener.
  26349. */
  26350. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  26351. var get = $parse(watchExp);
  26352. if (get.$$watchDelegate) {
  26353. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  26354. }
  26355. var scope = this,
  26356. array = scope.$$watchers,
  26357. watcher = {
  26358. fn: listener,
  26359. last: initWatchVal,
  26360. get: get,
  26361. exp: prettyPrintExpression || watchExp,
  26362. eq: !!objectEquality
  26363. };
  26364. lastDirtyWatch = null;
  26365. if (!isFunction(listener)) {
  26366. watcher.fn = noop;
  26367. }
  26368. if (!array) {
  26369. array = scope.$$watchers = [];
  26370. }
  26371. // we use unshift since we use a while loop in $digest for speed.
  26372. // the while loop reads in reverse order.
  26373. array.unshift(watcher);
  26374. incrementWatchersCount(this, 1);
  26375. return function deregisterWatch() {
  26376. if (arrayRemove(array, watcher) >= 0) {
  26377. incrementWatchersCount(scope, -1);
  26378. }
  26379. lastDirtyWatch = null;
  26380. };
  26381. },
  26382. /**
  26383. * @ngdoc method
  26384. * @name $rootScope.Scope#$watchGroup
  26385. * @kind function
  26386. *
  26387. * @description
  26388. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  26389. * If any one expression in the collection changes the `listener` is executed.
  26390. *
  26391. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  26392. * call to $digest() to see if any items changes.
  26393. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  26394. *
  26395. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  26396. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  26397. *
  26398. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  26399. * expression in `watchExpressions` changes
  26400. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  26401. * those of `watchExpression`
  26402. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  26403. * those of `watchExpression`
  26404. * The `scope` refers to the current scope.
  26405. * @returns {function()} Returns a de-registration function for all listeners.
  26406. */
  26407. $watchGroup: function(watchExpressions, listener) {
  26408. var oldValues = new Array(watchExpressions.length);
  26409. var newValues = new Array(watchExpressions.length);
  26410. var deregisterFns = [];
  26411. var self = this;
  26412. var changeReactionScheduled = false;
  26413. var firstRun = true;
  26414. if (!watchExpressions.length) {
  26415. // No expressions means we call the listener ASAP
  26416. var shouldCall = true;
  26417. self.$evalAsync(function() {
  26418. if (shouldCall) listener(newValues, newValues, self);
  26419. });
  26420. return function deregisterWatchGroup() {
  26421. shouldCall = false;
  26422. };
  26423. }
  26424. if (watchExpressions.length === 1) {
  26425. // Special case size of one
  26426. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  26427. newValues[0] = value;
  26428. oldValues[0] = oldValue;
  26429. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  26430. });
  26431. }
  26432. forEach(watchExpressions, function(expr, i) {
  26433. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  26434. newValues[i] = value;
  26435. oldValues[i] = oldValue;
  26436. if (!changeReactionScheduled) {
  26437. changeReactionScheduled = true;
  26438. self.$evalAsync(watchGroupAction);
  26439. }
  26440. });
  26441. deregisterFns.push(unwatchFn);
  26442. });
  26443. function watchGroupAction() {
  26444. changeReactionScheduled = false;
  26445. if (firstRun) {
  26446. firstRun = false;
  26447. listener(newValues, newValues, self);
  26448. } else {
  26449. listener(newValues, oldValues, self);
  26450. }
  26451. }
  26452. return function deregisterWatchGroup() {
  26453. while (deregisterFns.length) {
  26454. deregisterFns.shift()();
  26455. }
  26456. };
  26457. },
  26458. /**
  26459. * @ngdoc method
  26460. * @name $rootScope.Scope#$watchCollection
  26461. * @kind function
  26462. *
  26463. * @description
  26464. * Shallow watches the properties of an object and fires whenever any of the properties change
  26465. * (for arrays, this implies watching the array items; for object maps, this implies watching
  26466. * the properties). If a change is detected, the `listener` callback is fired.
  26467. *
  26468. * - The `obj` collection is observed via standard $watch operation and is examined on every
  26469. * call to $digest() to see if any items have been added, removed, or moved.
  26470. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  26471. * adding, removing, and moving items belonging to an object or array.
  26472. *
  26473. *
  26474. * # Example
  26475. * ```js
  26476. $scope.names = ['igor', 'matias', 'misko', 'james'];
  26477. $scope.dataCount = 4;
  26478. $scope.$watchCollection('names', function(newNames, oldNames) {
  26479. $scope.dataCount = newNames.length;
  26480. });
  26481. expect($scope.dataCount).toEqual(4);
  26482. $scope.$digest();
  26483. //still at 4 ... no changes
  26484. expect($scope.dataCount).toEqual(4);
  26485. $scope.names.pop();
  26486. $scope.$digest();
  26487. //now there's been a change
  26488. expect($scope.dataCount).toEqual(3);
  26489. * ```
  26490. *
  26491. *
  26492. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  26493. * expression value should evaluate to an object or an array which is observed on each
  26494. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  26495. * collection will trigger a call to the `listener`.
  26496. *
  26497. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  26498. * when a change is detected.
  26499. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  26500. * - The `oldCollection` object is a copy of the former collection data.
  26501. * Due to performance considerations, the`oldCollection` value is computed only if the
  26502. * `listener` function declares two or more arguments.
  26503. * - The `scope` argument refers to the current scope.
  26504. *
  26505. * @returns {function()} Returns a de-registration function for this listener. When the
  26506. * de-registration function is executed, the internal watch operation is terminated.
  26507. */
  26508. $watchCollection: function(obj, listener) {
  26509. $watchCollectionInterceptor.$stateful = true;
  26510. var self = this;
  26511. // the current value, updated on each dirty-check run
  26512. var newValue;
  26513. // a shallow copy of the newValue from the last dirty-check run,
  26514. // updated to match newValue during dirty-check run
  26515. var oldValue;
  26516. // a shallow copy of the newValue from when the last change happened
  26517. var veryOldValue;
  26518. // only track veryOldValue if the listener is asking for it
  26519. var trackVeryOldValue = (listener.length > 1);
  26520. var changeDetected = 0;
  26521. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  26522. var internalArray = [];
  26523. var internalObject = {};
  26524. var initRun = true;
  26525. var oldLength = 0;
  26526. function $watchCollectionInterceptor(_value) {
  26527. newValue = _value;
  26528. var newLength, key, bothNaN, newItem, oldItem;
  26529. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  26530. if (isUndefined(newValue)) return;
  26531. if (!isObject(newValue)) { // if primitive
  26532. if (oldValue !== newValue) {
  26533. oldValue = newValue;
  26534. changeDetected++;
  26535. }
  26536. } else if (isArrayLike(newValue)) {
  26537. if (oldValue !== internalArray) {
  26538. // we are transitioning from something which was not an array into array.
  26539. oldValue = internalArray;
  26540. oldLength = oldValue.length = 0;
  26541. changeDetected++;
  26542. }
  26543. newLength = newValue.length;
  26544. if (oldLength !== newLength) {
  26545. // if lengths do not match we need to trigger change notification
  26546. changeDetected++;
  26547. oldValue.length = oldLength = newLength;
  26548. }
  26549. // copy the items to oldValue and look for changes.
  26550. for (var i = 0; i < newLength; i++) {
  26551. oldItem = oldValue[i];
  26552. newItem = newValue[i];
  26553. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  26554. if (!bothNaN && (oldItem !== newItem)) {
  26555. changeDetected++;
  26556. oldValue[i] = newItem;
  26557. }
  26558. }
  26559. } else {
  26560. if (oldValue !== internalObject) {
  26561. // we are transitioning from something which was not an object into object.
  26562. oldValue = internalObject = {};
  26563. oldLength = 0;
  26564. changeDetected++;
  26565. }
  26566. // copy the items to oldValue and look for changes.
  26567. newLength = 0;
  26568. for (key in newValue) {
  26569. if (hasOwnProperty.call(newValue, key)) {
  26570. newLength++;
  26571. newItem = newValue[key];
  26572. oldItem = oldValue[key];
  26573. if (key in oldValue) {
  26574. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  26575. if (!bothNaN && (oldItem !== newItem)) {
  26576. changeDetected++;
  26577. oldValue[key] = newItem;
  26578. }
  26579. } else {
  26580. oldLength++;
  26581. oldValue[key] = newItem;
  26582. changeDetected++;
  26583. }
  26584. }
  26585. }
  26586. if (oldLength > newLength) {
  26587. // we used to have more keys, need to find them and destroy them.
  26588. changeDetected++;
  26589. for (key in oldValue) {
  26590. if (!hasOwnProperty.call(newValue, key)) {
  26591. oldLength--;
  26592. delete oldValue[key];
  26593. }
  26594. }
  26595. }
  26596. }
  26597. return changeDetected;
  26598. }
  26599. function $watchCollectionAction() {
  26600. if (initRun) {
  26601. initRun = false;
  26602. listener(newValue, newValue, self);
  26603. } else {
  26604. listener(newValue, veryOldValue, self);
  26605. }
  26606. // make a copy for the next time a collection is changed
  26607. if (trackVeryOldValue) {
  26608. if (!isObject(newValue)) {
  26609. //primitive
  26610. veryOldValue = newValue;
  26611. } else if (isArrayLike(newValue)) {
  26612. veryOldValue = new Array(newValue.length);
  26613. for (var i = 0; i < newValue.length; i++) {
  26614. veryOldValue[i] = newValue[i];
  26615. }
  26616. } else { // if object
  26617. veryOldValue = {};
  26618. for (var key in newValue) {
  26619. if (hasOwnProperty.call(newValue, key)) {
  26620. veryOldValue[key] = newValue[key];
  26621. }
  26622. }
  26623. }
  26624. }
  26625. }
  26626. return this.$watch(changeDetector, $watchCollectionAction);
  26627. },
  26628. /**
  26629. * @ngdoc method
  26630. * @name $rootScope.Scope#$digest
  26631. * @kind function
  26632. *
  26633. * @description
  26634. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  26635. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  26636. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  26637. * until no more listeners are firing. This means that it is possible to get into an infinite
  26638. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  26639. * iterations exceeds 10.
  26640. *
  26641. * Usually, you don't call `$digest()` directly in
  26642. * {@link ng.directive:ngController controllers} or in
  26643. * {@link ng.$compileProvider#directive directives}.
  26644. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  26645. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  26646. *
  26647. * If you want to be notified whenever `$digest()` is called,
  26648. * you can register a `watchExpression` function with
  26649. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  26650. *
  26651. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  26652. *
  26653. * # Example
  26654. * ```js
  26655. var scope = ...;
  26656. scope.name = 'misko';
  26657. scope.counter = 0;
  26658. expect(scope.counter).toEqual(0);
  26659. scope.$watch('name', function(newValue, oldValue) {
  26660. scope.counter = scope.counter + 1;
  26661. });
  26662. expect(scope.counter).toEqual(0);
  26663. scope.$digest();
  26664. // the listener is always called during the first $digest loop after it was registered
  26665. expect(scope.counter).toEqual(1);
  26666. scope.$digest();
  26667. // but now it will not be called unless the value changes
  26668. expect(scope.counter).toEqual(1);
  26669. scope.name = 'adam';
  26670. scope.$digest();
  26671. expect(scope.counter).toEqual(2);
  26672. * ```
  26673. *
  26674. */
  26675. $digest: function() {
  26676. var watch, value, last, fn, get,
  26677. watchers,
  26678. length,
  26679. dirty, ttl = TTL,
  26680. next, current, target = this,
  26681. watchLog = [],
  26682. logIdx, asyncTask;
  26683. beginPhase('$digest');
  26684. // Check for changes to browser url that happened in sync before the call to $digest
  26685. $browser.$$checkUrlChange();
  26686. if (this === $rootScope && applyAsyncId !== null) {
  26687. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  26688. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  26689. $browser.defer.cancel(applyAsyncId);
  26690. flushApplyAsync();
  26691. }
  26692. lastDirtyWatch = null;
  26693. do { // "while dirty" loop
  26694. dirty = false;
  26695. current = target;
  26696. while (asyncQueue.length) {
  26697. try {
  26698. asyncTask = asyncQueue.shift();
  26699. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  26700. } catch (e) {
  26701. $exceptionHandler(e);
  26702. }
  26703. lastDirtyWatch = null;
  26704. }
  26705. traverseScopesLoop:
  26706. do { // "traverse the scopes" loop
  26707. if ((watchers = current.$$watchers)) {
  26708. // process our watches
  26709. length = watchers.length;
  26710. while (length--) {
  26711. try {
  26712. watch = watchers[length];
  26713. // Most common watches are on primitives, in which case we can short
  26714. // circuit it with === operator, only when === fails do we use .equals
  26715. if (watch) {
  26716. get = watch.get;
  26717. if ((value = get(current)) !== (last = watch.last) &&
  26718. !(watch.eq
  26719. ? equals(value, last)
  26720. : (typeof value === 'number' && typeof last === 'number'
  26721. && isNaN(value) && isNaN(last)))) {
  26722. dirty = true;
  26723. lastDirtyWatch = watch;
  26724. watch.last = watch.eq ? copy(value, null) : value;
  26725. fn = watch.fn;
  26726. fn(value, ((last === initWatchVal) ? value : last), current);
  26727. if (ttl < 5) {
  26728. logIdx = 4 - ttl;
  26729. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  26730. watchLog[logIdx].push({
  26731. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  26732. newVal: value,
  26733. oldVal: last
  26734. });
  26735. }
  26736. } else if (watch === lastDirtyWatch) {
  26737. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  26738. // have already been tested.
  26739. dirty = false;
  26740. break traverseScopesLoop;
  26741. }
  26742. }
  26743. } catch (e) {
  26744. $exceptionHandler(e);
  26745. }
  26746. }
  26747. }
  26748. // Insanity Warning: scope depth-first traversal
  26749. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  26750. // this piece should be kept in sync with the traversal in $broadcast
  26751. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  26752. (current !== target && current.$$nextSibling)))) {
  26753. while (current !== target && !(next = current.$$nextSibling)) {
  26754. current = current.$parent;
  26755. }
  26756. }
  26757. } while ((current = next));
  26758. // `break traverseScopesLoop;` takes us to here
  26759. if ((dirty || asyncQueue.length) && !(ttl--)) {
  26760. clearPhase();
  26761. throw $rootScopeMinErr('infdig',
  26762. '{0} $digest() iterations reached. Aborting!\n' +
  26763. 'Watchers fired in the last 5 iterations: {1}',
  26764. TTL, watchLog);
  26765. }
  26766. } while (dirty || asyncQueue.length);
  26767. clearPhase();
  26768. while (postDigestQueue.length) {
  26769. try {
  26770. postDigestQueue.shift()();
  26771. } catch (e) {
  26772. $exceptionHandler(e);
  26773. }
  26774. }
  26775. },
  26776. /**
  26777. * @ngdoc event
  26778. * @name $rootScope.Scope#$destroy
  26779. * @eventType broadcast on scope being destroyed
  26780. *
  26781. * @description
  26782. * Broadcasted when a scope and its children are being destroyed.
  26783. *
  26784. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  26785. * clean up DOM bindings before an element is removed from the DOM.
  26786. */
  26787. /**
  26788. * @ngdoc method
  26789. * @name $rootScope.Scope#$destroy
  26790. * @kind function
  26791. *
  26792. * @description
  26793. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  26794. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  26795. * propagate to the current scope and its children. Removal also implies that the current
  26796. * scope is eligible for garbage collection.
  26797. *
  26798. * The `$destroy()` is usually used by directives such as
  26799. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  26800. * unrolling of the loop.
  26801. *
  26802. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  26803. * Application code can register a `$destroy` event handler that will give it a chance to
  26804. * perform any necessary cleanup.
  26805. *
  26806. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  26807. * clean up DOM bindings before an element is removed from the DOM.
  26808. */
  26809. $destroy: function() {
  26810. // We can't destroy a scope that has been already destroyed.
  26811. if (this.$$destroyed) return;
  26812. var parent = this.$parent;
  26813. this.$broadcast('$destroy');
  26814. this.$$destroyed = true;
  26815. if (this === $rootScope) {
  26816. //Remove handlers attached to window when $rootScope is removed
  26817. $browser.$$applicationDestroyed();
  26818. }
  26819. incrementWatchersCount(this, -this.$$watchersCount);
  26820. for (var eventName in this.$$listenerCount) {
  26821. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  26822. }
  26823. // sever all the references to parent scopes (after this cleanup, the current scope should
  26824. // not be retained by any of our references and should be eligible for garbage collection)
  26825. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  26826. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  26827. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  26828. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  26829. // Disable listeners, watchers and apply/digest methods
  26830. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  26831. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  26832. this.$$listeners = {};
  26833. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  26834. this.$$nextSibling = null;
  26835. cleanUpScope(this);
  26836. },
  26837. /**
  26838. * @ngdoc method
  26839. * @name $rootScope.Scope#$eval
  26840. * @kind function
  26841. *
  26842. * @description
  26843. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  26844. * the expression are propagated (uncaught). This is useful when evaluating Angular
  26845. * expressions.
  26846. *
  26847. * # Example
  26848. * ```js
  26849. var scope = ng.$rootScope.Scope();
  26850. scope.a = 1;
  26851. scope.b = 2;
  26852. expect(scope.$eval('a+b')).toEqual(3);
  26853. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  26854. * ```
  26855. *
  26856. * @param {(string|function())=} expression An angular expression to be executed.
  26857. *
  26858. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26859. * - `function(scope)`: execute the function with the current `scope` parameter.
  26860. *
  26861. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  26862. * @returns {*} The result of evaluating the expression.
  26863. */
  26864. $eval: function(expr, locals) {
  26865. return $parse(expr)(this, locals);
  26866. },
  26867. /**
  26868. * @ngdoc method
  26869. * @name $rootScope.Scope#$evalAsync
  26870. * @kind function
  26871. *
  26872. * @description
  26873. * Executes the expression on the current scope at a later point in time.
  26874. *
  26875. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  26876. * that:
  26877. *
  26878. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  26879. * rendering).
  26880. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  26881. * `expression` execution.
  26882. *
  26883. * Any exceptions from the execution of the expression are forwarded to the
  26884. * {@link ng.$exceptionHandler $exceptionHandler} service.
  26885. *
  26886. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  26887. * will be scheduled. However, it is encouraged to always call code that changes the model
  26888. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  26889. *
  26890. * @param {(string|function())=} expression An angular expression to be executed.
  26891. *
  26892. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26893. * - `function(scope)`: execute the function with the current `scope` parameter.
  26894. *
  26895. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  26896. */
  26897. $evalAsync: function(expr, locals) {
  26898. // if we are outside of an $digest loop and this is the first time we are scheduling async
  26899. // task also schedule async auto-flush
  26900. if (!$rootScope.$$phase && !asyncQueue.length) {
  26901. $browser.defer(function() {
  26902. if (asyncQueue.length) {
  26903. $rootScope.$digest();
  26904. }
  26905. });
  26906. }
  26907. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  26908. },
  26909. $$postDigest: function(fn) {
  26910. postDigestQueue.push(fn);
  26911. },
  26912. /**
  26913. * @ngdoc method
  26914. * @name $rootScope.Scope#$apply
  26915. * @kind function
  26916. *
  26917. * @description
  26918. * `$apply()` is used to execute an expression in angular from outside of the angular
  26919. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  26920. * Because we are calling into the angular framework we need to perform proper scope life
  26921. * cycle of {@link ng.$exceptionHandler exception handling},
  26922. * {@link ng.$rootScope.Scope#$digest executing watches}.
  26923. *
  26924. * ## Life cycle
  26925. *
  26926. * # Pseudo-Code of `$apply()`
  26927. * ```js
  26928. function $apply(expr) {
  26929. try {
  26930. return $eval(expr);
  26931. } catch (e) {
  26932. $exceptionHandler(e);
  26933. } finally {
  26934. $root.$digest();
  26935. }
  26936. }
  26937. * ```
  26938. *
  26939. *
  26940. * Scope's `$apply()` method transitions through the following stages:
  26941. *
  26942. * 1. The {@link guide/expression expression} is executed using the
  26943. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  26944. * 2. Any exceptions from the execution of the expression are forwarded to the
  26945. * {@link ng.$exceptionHandler $exceptionHandler} service.
  26946. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  26947. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  26948. *
  26949. *
  26950. * @param {(string|function())=} exp An angular expression to be executed.
  26951. *
  26952. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26953. * - `function(scope)`: execute the function with current `scope` parameter.
  26954. *
  26955. * @returns {*} The result of evaluating the expression.
  26956. */
  26957. $apply: function(expr) {
  26958. try {
  26959. beginPhase('$apply');
  26960. try {
  26961. return this.$eval(expr);
  26962. } finally {
  26963. clearPhase();
  26964. }
  26965. } catch (e) {
  26966. $exceptionHandler(e);
  26967. } finally {
  26968. try {
  26969. $rootScope.$digest();
  26970. } catch (e) {
  26971. $exceptionHandler(e);
  26972. throw e;
  26973. }
  26974. }
  26975. },
  26976. /**
  26977. * @ngdoc method
  26978. * @name $rootScope.Scope#$applyAsync
  26979. * @kind function
  26980. *
  26981. * @description
  26982. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  26983. * varies across browsers, but is typically around ~10 milliseconds.
  26984. *
  26985. * This can be used to queue up multiple expressions which need to be evaluated in the same
  26986. * digest.
  26987. *
  26988. * @param {(string|function())=} exp An angular expression to be executed.
  26989. *
  26990. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26991. * - `function(scope)`: execute the function with current `scope` parameter.
  26992. */
  26993. $applyAsync: function(expr) {
  26994. var scope = this;
  26995. expr && applyAsyncQueue.push($applyAsyncExpression);
  26996. expr = $parse(expr);
  26997. scheduleApplyAsync();
  26998. function $applyAsyncExpression() {
  26999. scope.$eval(expr);
  27000. }
  27001. },
  27002. /**
  27003. * @ngdoc method
  27004. * @name $rootScope.Scope#$on
  27005. * @kind function
  27006. *
  27007. * @description
  27008. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  27009. * discussion of event life cycle.
  27010. *
  27011. * The event listener function format is: `function(event, args...)`. The `event` object
  27012. * passed into the listener has the following attributes:
  27013. *
  27014. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  27015. * `$broadcast`-ed.
  27016. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  27017. * event propagates through the scope hierarchy, this property is set to null.
  27018. * - `name` - `{string}`: name of the event.
  27019. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  27020. * further event propagation (available only for events that were `$emit`-ed).
  27021. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  27022. * to true.
  27023. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  27024. *
  27025. * @param {string} name Event name to listen on.
  27026. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  27027. * @returns {function()} Returns a deregistration function for this listener.
  27028. */
  27029. $on: function(name, listener) {
  27030. var namedListeners = this.$$listeners[name];
  27031. if (!namedListeners) {
  27032. this.$$listeners[name] = namedListeners = [];
  27033. }
  27034. namedListeners.push(listener);
  27035. var current = this;
  27036. do {
  27037. if (!current.$$listenerCount[name]) {
  27038. current.$$listenerCount[name] = 0;
  27039. }
  27040. current.$$listenerCount[name]++;
  27041. } while ((current = current.$parent));
  27042. var self = this;
  27043. return function() {
  27044. var indexOfListener = namedListeners.indexOf(listener);
  27045. if (indexOfListener !== -1) {
  27046. namedListeners[indexOfListener] = null;
  27047. decrementListenerCount(self, 1, name);
  27048. }
  27049. };
  27050. },
  27051. /**
  27052. * @ngdoc method
  27053. * @name $rootScope.Scope#$emit
  27054. * @kind function
  27055. *
  27056. * @description
  27057. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  27058. * registered {@link ng.$rootScope.Scope#$on} listeners.
  27059. *
  27060. * The event life cycle starts at the scope on which `$emit` was called. All
  27061. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  27062. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  27063. * registered listeners along the way. The event will stop propagating if one of the listeners
  27064. * cancels it.
  27065. *
  27066. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  27067. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  27068. *
  27069. * @param {string} name Event name to emit.
  27070. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  27071. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  27072. */
  27073. $emit: function(name, args) {
  27074. var empty = [],
  27075. namedListeners,
  27076. scope = this,
  27077. stopPropagation = false,
  27078. event = {
  27079. name: name,
  27080. targetScope: scope,
  27081. stopPropagation: function() {stopPropagation = true;},
  27082. preventDefault: function() {
  27083. event.defaultPrevented = true;
  27084. },
  27085. defaultPrevented: false
  27086. },
  27087. listenerArgs = concat([event], arguments, 1),
  27088. i, length;
  27089. do {
  27090. namedListeners = scope.$$listeners[name] || empty;
  27091. event.currentScope = scope;
  27092. for (i = 0, length = namedListeners.length; i < length; i++) {
  27093. // if listeners were deregistered, defragment the array
  27094. if (!namedListeners[i]) {
  27095. namedListeners.splice(i, 1);
  27096. i--;
  27097. length--;
  27098. continue;
  27099. }
  27100. try {
  27101. //allow all listeners attached to the current scope to run
  27102. namedListeners[i].apply(null, listenerArgs);
  27103. } catch (e) {
  27104. $exceptionHandler(e);
  27105. }
  27106. }
  27107. //if any listener on the current scope stops propagation, prevent bubbling
  27108. if (stopPropagation) {
  27109. event.currentScope = null;
  27110. return event;
  27111. }
  27112. //traverse upwards
  27113. scope = scope.$parent;
  27114. } while (scope);
  27115. event.currentScope = null;
  27116. return event;
  27117. },
  27118. /**
  27119. * @ngdoc method
  27120. * @name $rootScope.Scope#$broadcast
  27121. * @kind function
  27122. *
  27123. * @description
  27124. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  27125. * registered {@link ng.$rootScope.Scope#$on} listeners.
  27126. *
  27127. * The event life cycle starts at the scope on which `$broadcast` was called. All
  27128. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  27129. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  27130. * scope and calls all registered listeners along the way. The event cannot be canceled.
  27131. *
  27132. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  27133. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  27134. *
  27135. * @param {string} name Event name to broadcast.
  27136. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  27137. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  27138. */
  27139. $broadcast: function(name, args) {
  27140. var target = this,
  27141. current = target,
  27142. next = target,
  27143. event = {
  27144. name: name,
  27145. targetScope: target,
  27146. preventDefault: function() {
  27147. event.defaultPrevented = true;
  27148. },
  27149. defaultPrevented: false
  27150. };
  27151. if (!target.$$listenerCount[name]) return event;
  27152. var listenerArgs = concat([event], arguments, 1),
  27153. listeners, i, length;
  27154. //down while you can, then up and next sibling or up and next sibling until back at root
  27155. while ((current = next)) {
  27156. event.currentScope = current;
  27157. listeners = current.$$listeners[name] || [];
  27158. for (i = 0, length = listeners.length; i < length; i++) {
  27159. // if listeners were deregistered, defragment the array
  27160. if (!listeners[i]) {
  27161. listeners.splice(i, 1);
  27162. i--;
  27163. length--;
  27164. continue;
  27165. }
  27166. try {
  27167. listeners[i].apply(null, listenerArgs);
  27168. } catch (e) {
  27169. $exceptionHandler(e);
  27170. }
  27171. }
  27172. // Insanity Warning: scope depth-first traversal
  27173. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  27174. // this piece should be kept in sync with the traversal in $digest
  27175. // (though it differs due to having the extra check for $$listenerCount)
  27176. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  27177. (current !== target && current.$$nextSibling)))) {
  27178. while (current !== target && !(next = current.$$nextSibling)) {
  27179. current = current.$parent;
  27180. }
  27181. }
  27182. }
  27183. event.currentScope = null;
  27184. return event;
  27185. }
  27186. };
  27187. var $rootScope = new Scope();
  27188. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  27189. var asyncQueue = $rootScope.$$asyncQueue = [];
  27190. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  27191. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  27192. return $rootScope;
  27193. function beginPhase(phase) {
  27194. if ($rootScope.$$phase) {
  27195. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  27196. }
  27197. $rootScope.$$phase = phase;
  27198. }
  27199. function clearPhase() {
  27200. $rootScope.$$phase = null;
  27201. }
  27202. function incrementWatchersCount(current, count) {
  27203. do {
  27204. current.$$watchersCount += count;
  27205. } while ((current = current.$parent));
  27206. }
  27207. function decrementListenerCount(current, count, name) {
  27208. do {
  27209. current.$$listenerCount[name] -= count;
  27210. if (current.$$listenerCount[name] === 0) {
  27211. delete current.$$listenerCount[name];
  27212. }
  27213. } while ((current = current.$parent));
  27214. }
  27215. /**
  27216. * function used as an initial value for watchers.
  27217. * because it's unique we can easily tell it apart from other values
  27218. */
  27219. function initWatchVal() {}
  27220. function flushApplyAsync() {
  27221. while (applyAsyncQueue.length) {
  27222. try {
  27223. applyAsyncQueue.shift()();
  27224. } catch (e) {
  27225. $exceptionHandler(e);
  27226. }
  27227. }
  27228. applyAsyncId = null;
  27229. }
  27230. function scheduleApplyAsync() {
  27231. if (applyAsyncId === null) {
  27232. applyAsyncId = $browser.defer(function() {
  27233. $rootScope.$apply(flushApplyAsync);
  27234. });
  27235. }
  27236. }
  27237. }];
  27238. }
  27239. /**
  27240. * @ngdoc service
  27241. * @name $rootElement
  27242. *
  27243. * @description
  27244. * The root element of Angular application. This is either the element where {@link
  27245. * ng.directive:ngApp ngApp} was declared or the element passed into
  27246. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  27247. * location where the application's {@link auto.$injector $injector} service gets
  27248. * published, and can be retrieved using `$rootElement.injector()`.
  27249. */
  27250. // the implementation is in angular.bootstrap
  27251. /**
  27252. * @description
  27253. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  27254. */
  27255. function $$SanitizeUriProvider() {
  27256. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  27257. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  27258. /**
  27259. * @description
  27260. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  27261. * urls during a[href] sanitization.
  27262. *
  27263. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  27264. *
  27265. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  27266. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  27267. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  27268. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  27269. *
  27270. * @param {RegExp=} regexp New regexp to whitelist urls with.
  27271. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  27272. * chaining otherwise.
  27273. */
  27274. this.aHrefSanitizationWhitelist = function(regexp) {
  27275. if (isDefined(regexp)) {
  27276. aHrefSanitizationWhitelist = regexp;
  27277. return this;
  27278. }
  27279. return aHrefSanitizationWhitelist;
  27280. };
  27281. /**
  27282. * @description
  27283. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  27284. * urls during img[src] sanitization.
  27285. *
  27286. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  27287. *
  27288. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  27289. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  27290. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  27291. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  27292. *
  27293. * @param {RegExp=} regexp New regexp to whitelist urls with.
  27294. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  27295. * chaining otherwise.
  27296. */
  27297. this.imgSrcSanitizationWhitelist = function(regexp) {
  27298. if (isDefined(regexp)) {
  27299. imgSrcSanitizationWhitelist = regexp;
  27300. return this;
  27301. }
  27302. return imgSrcSanitizationWhitelist;
  27303. };
  27304. this.$get = function() {
  27305. return function sanitizeUri(uri, isImage) {
  27306. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  27307. var normalizedVal;
  27308. normalizedVal = urlResolve(uri).href;
  27309. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  27310. return 'unsafe:' + normalizedVal;
  27311. }
  27312. return uri;
  27313. };
  27314. };
  27315. }
  27316. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  27317. * Any commits to this file should be reviewed with security in mind. *
  27318. * Changes to this file can potentially create security vulnerabilities. *
  27319. * An approval from 2 Core members with history of modifying *
  27320. * this file is required. *
  27321. * *
  27322. * Does the change somehow allow for arbitrary javascript to be executed? *
  27323. * Or allows for someone to change the prototype of built-in objects? *
  27324. * Or gives undesired access to variables likes document or window? *
  27325. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  27326. var $sceMinErr = minErr('$sce');
  27327. var SCE_CONTEXTS = {
  27328. HTML: 'html',
  27329. CSS: 'css',
  27330. URL: 'url',
  27331. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  27332. // url. (e.g. ng-include, script src, templateUrl)
  27333. RESOURCE_URL: 'resourceUrl',
  27334. JS: 'js'
  27335. };
  27336. // Helper functions follow.
  27337. function adjustMatcher(matcher) {
  27338. if (matcher === 'self') {
  27339. return matcher;
  27340. } else if (isString(matcher)) {
  27341. // Strings match exactly except for 2 wildcards - '*' and '**'.
  27342. // '*' matches any character except those from the set ':/.?&'.
  27343. // '**' matches any character (like .* in a RegExp).
  27344. // More than 2 *'s raises an error as it's ill defined.
  27345. if (matcher.indexOf('***') > -1) {
  27346. throw $sceMinErr('iwcard',
  27347. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  27348. }
  27349. matcher = escapeForRegexp(matcher).
  27350. replace('\\*\\*', '.*').
  27351. replace('\\*', '[^:/.?&;]*');
  27352. return new RegExp('^' + matcher + '$');
  27353. } else if (isRegExp(matcher)) {
  27354. // The only other type of matcher allowed is a Regexp.
  27355. // Match entire URL / disallow partial matches.
  27356. // Flags are reset (i.e. no global, ignoreCase or multiline)
  27357. return new RegExp('^' + matcher.source + '$');
  27358. } else {
  27359. throw $sceMinErr('imatcher',
  27360. 'Matchers may only be "self", string patterns or RegExp objects');
  27361. }
  27362. }
  27363. function adjustMatchers(matchers) {
  27364. var adjustedMatchers = [];
  27365. if (isDefined(matchers)) {
  27366. forEach(matchers, function(matcher) {
  27367. adjustedMatchers.push(adjustMatcher(matcher));
  27368. });
  27369. }
  27370. return adjustedMatchers;
  27371. }
  27372. /**
  27373. * @ngdoc service
  27374. * @name $sceDelegate
  27375. * @kind function
  27376. *
  27377. * @description
  27378. *
  27379. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  27380. * Contextual Escaping (SCE)} services to AngularJS.
  27381. *
  27382. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  27383. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  27384. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  27385. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  27386. * work because `$sce` delegates to `$sceDelegate` for these operations.
  27387. *
  27388. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  27389. *
  27390. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  27391. * can override it completely to change the behavior of `$sce`, the common case would
  27392. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  27393. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  27394. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  27395. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  27396. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  27397. */
  27398. /**
  27399. * @ngdoc provider
  27400. * @name $sceDelegateProvider
  27401. * @description
  27402. *
  27403. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  27404. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  27405. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  27406. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  27407. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  27408. *
  27409. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  27410. * Strict Contextual Escaping (SCE)}.
  27411. *
  27412. * **Example**: Consider the following case. <a name="example"></a>
  27413. *
  27414. * - your app is hosted at url `http://myapp.example.com/`
  27415. * - but some of your templates are hosted on other domains you control such as
  27416. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  27417. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  27418. *
  27419. * Here is what a secure configuration for this scenario might look like:
  27420. *
  27421. * ```
  27422. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  27423. * $sceDelegateProvider.resourceUrlWhitelist([
  27424. * // Allow same origin resource loads.
  27425. * 'self',
  27426. * // Allow loading from our assets domain. Notice the difference between * and **.
  27427. * 'http://srv*.assets.example.com/**'
  27428. * ]);
  27429. *
  27430. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  27431. * $sceDelegateProvider.resourceUrlBlacklist([
  27432. * 'http://myapp.example.com/clickThru**'
  27433. * ]);
  27434. * });
  27435. * ```
  27436. */
  27437. function $SceDelegateProvider() {
  27438. this.SCE_CONTEXTS = SCE_CONTEXTS;
  27439. // Resource URLs can also be trusted by policy.
  27440. var resourceUrlWhitelist = ['self'],
  27441. resourceUrlBlacklist = [];
  27442. /**
  27443. * @ngdoc method
  27444. * @name $sceDelegateProvider#resourceUrlWhitelist
  27445. * @kind function
  27446. *
  27447. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  27448. * provided. This must be an array or null. A snapshot of this array is used so further
  27449. * changes to the array are ignored.
  27450. *
  27451. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  27452. * allowed in this array.
  27453. *
  27454. * <div class="alert alert-warning">
  27455. * **Note:** an empty whitelist array will block all URLs!
  27456. * </div>
  27457. *
  27458. * @return {Array} the currently set whitelist array.
  27459. *
  27460. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  27461. * same origin resource requests.
  27462. *
  27463. * @description
  27464. * Sets/Gets the whitelist of trusted resource URLs.
  27465. */
  27466. this.resourceUrlWhitelist = function(value) {
  27467. if (arguments.length) {
  27468. resourceUrlWhitelist = adjustMatchers(value);
  27469. }
  27470. return resourceUrlWhitelist;
  27471. };
  27472. /**
  27473. * @ngdoc method
  27474. * @name $sceDelegateProvider#resourceUrlBlacklist
  27475. * @kind function
  27476. *
  27477. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  27478. * provided. This must be an array or null. A snapshot of this array is used so further
  27479. * changes to the array are ignored.
  27480. *
  27481. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  27482. * allowed in this array.
  27483. *
  27484. * The typical usage for the blacklist is to **block
  27485. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  27486. * these would otherwise be trusted but actually return content from the redirected domain.
  27487. *
  27488. * Finally, **the blacklist overrides the whitelist** and has the final say.
  27489. *
  27490. * @return {Array} the currently set blacklist array.
  27491. *
  27492. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  27493. * is no blacklist.)
  27494. *
  27495. * @description
  27496. * Sets/Gets the blacklist of trusted resource URLs.
  27497. */
  27498. this.resourceUrlBlacklist = function(value) {
  27499. if (arguments.length) {
  27500. resourceUrlBlacklist = adjustMatchers(value);
  27501. }
  27502. return resourceUrlBlacklist;
  27503. };
  27504. this.$get = ['$injector', function($injector) {
  27505. var htmlSanitizer = function htmlSanitizer(html) {
  27506. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  27507. };
  27508. if ($injector.has('$sanitize')) {
  27509. htmlSanitizer = $injector.get('$sanitize');
  27510. }
  27511. function matchUrl(matcher, parsedUrl) {
  27512. if (matcher === 'self') {
  27513. return urlIsSameOrigin(parsedUrl);
  27514. } else {
  27515. // definitely a regex. See adjustMatchers()
  27516. return !!matcher.exec(parsedUrl.href);
  27517. }
  27518. }
  27519. function isResourceUrlAllowedByPolicy(url) {
  27520. var parsedUrl = urlResolve(url.toString());
  27521. var i, n, allowed = false;
  27522. // Ensure that at least one item from the whitelist allows this url.
  27523. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  27524. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  27525. allowed = true;
  27526. break;
  27527. }
  27528. }
  27529. if (allowed) {
  27530. // Ensure that no item from the blacklist blocked this url.
  27531. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  27532. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  27533. allowed = false;
  27534. break;
  27535. }
  27536. }
  27537. }
  27538. return allowed;
  27539. }
  27540. function generateHolderType(Base) {
  27541. var holderType = function TrustedValueHolderType(trustedValue) {
  27542. this.$$unwrapTrustedValue = function() {
  27543. return trustedValue;
  27544. };
  27545. };
  27546. if (Base) {
  27547. holderType.prototype = new Base();
  27548. }
  27549. holderType.prototype.valueOf = function sceValueOf() {
  27550. return this.$$unwrapTrustedValue();
  27551. };
  27552. holderType.prototype.toString = function sceToString() {
  27553. return this.$$unwrapTrustedValue().toString();
  27554. };
  27555. return holderType;
  27556. }
  27557. var trustedValueHolderBase = generateHolderType(),
  27558. byType = {};
  27559. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  27560. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  27561. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  27562. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  27563. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  27564. /**
  27565. * @ngdoc method
  27566. * @name $sceDelegate#trustAs
  27567. *
  27568. * @description
  27569. * Returns an object that is trusted by angular for use in specified strict
  27570. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  27571. * attribute interpolation, any dom event binding attribute interpolation
  27572. * such as for onclick, etc.) that uses the provided value.
  27573. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  27574. *
  27575. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  27576. * resourceUrl, html, js and css.
  27577. * @param {*} value The value that that should be considered trusted/safe.
  27578. * @returns {*} A value that can be used to stand in for the provided `value` in places
  27579. * where Angular expects a $sce.trustAs() return value.
  27580. */
  27581. function trustAs(type, trustedValue) {
  27582. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  27583. if (!Constructor) {
  27584. throw $sceMinErr('icontext',
  27585. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  27586. type, trustedValue);
  27587. }
  27588. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  27589. return trustedValue;
  27590. }
  27591. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  27592. // mutable objects, we ensure here that the value passed in is actually a string.
  27593. if (typeof trustedValue !== 'string') {
  27594. throw $sceMinErr('itype',
  27595. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  27596. type);
  27597. }
  27598. return new Constructor(trustedValue);
  27599. }
  27600. /**
  27601. * @ngdoc method
  27602. * @name $sceDelegate#valueOf
  27603. *
  27604. * @description
  27605. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  27606. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  27607. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  27608. *
  27609. * If the passed parameter is not a value that had been returned by {@link
  27610. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  27611. *
  27612. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  27613. * call or anything else.
  27614. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  27615. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  27616. * `value` unchanged.
  27617. */
  27618. function valueOf(maybeTrusted) {
  27619. if (maybeTrusted instanceof trustedValueHolderBase) {
  27620. return maybeTrusted.$$unwrapTrustedValue();
  27621. } else {
  27622. return maybeTrusted;
  27623. }
  27624. }
  27625. /**
  27626. * @ngdoc method
  27627. * @name $sceDelegate#getTrusted
  27628. *
  27629. * @description
  27630. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  27631. * returns the originally supplied value if the queried context type is a supertype of the
  27632. * created type. If this condition isn't satisfied, throws an exception.
  27633. *
  27634. * <div class="alert alert-danger">
  27635. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  27636. * (XSS) vulnerability in your application.
  27637. * </div>
  27638. *
  27639. * @param {string} type The kind of context in which this value is to be used.
  27640. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  27641. * `$sceDelegate.trustAs`} call.
  27642. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  27643. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  27644. */
  27645. function getTrusted(type, maybeTrusted) {
  27646. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  27647. return maybeTrusted;
  27648. }
  27649. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  27650. if (constructor && maybeTrusted instanceof constructor) {
  27651. return maybeTrusted.$$unwrapTrustedValue();
  27652. }
  27653. // If we get here, then we may only take one of two actions.
  27654. // 1. sanitize the value for the requested type, or
  27655. // 2. throw an exception.
  27656. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  27657. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  27658. return maybeTrusted;
  27659. } else {
  27660. throw $sceMinErr('insecurl',
  27661. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  27662. maybeTrusted.toString());
  27663. }
  27664. } else if (type === SCE_CONTEXTS.HTML) {
  27665. return htmlSanitizer(maybeTrusted);
  27666. }
  27667. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  27668. }
  27669. return { trustAs: trustAs,
  27670. getTrusted: getTrusted,
  27671. valueOf: valueOf };
  27672. }];
  27673. }
  27674. /**
  27675. * @ngdoc provider
  27676. * @name $sceProvider
  27677. * @description
  27678. *
  27679. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  27680. * - enable/disable Strict Contextual Escaping (SCE) in a module
  27681. * - override the default implementation with a custom delegate
  27682. *
  27683. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  27684. */
  27685. /* jshint maxlen: false*/
  27686. /**
  27687. * @ngdoc service
  27688. * @name $sce
  27689. * @kind function
  27690. *
  27691. * @description
  27692. *
  27693. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  27694. *
  27695. * # Strict Contextual Escaping
  27696. *
  27697. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  27698. * contexts to result in a value that is marked as safe to use for that context. One example of
  27699. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  27700. * to these contexts as privileged or SCE contexts.
  27701. *
  27702. * As of version 1.2, Angular ships with SCE enabled by default.
  27703. *
  27704. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  27705. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  27706. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  27707. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  27708. * to the top of your HTML document.
  27709. *
  27710. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  27711. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  27712. *
  27713. * Here's an example of a binding in a privileged context:
  27714. *
  27715. * ```
  27716. * <input ng-model="userHtml" aria-label="User input">
  27717. * <div ng-bind-html="userHtml"></div>
  27718. * ```
  27719. *
  27720. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  27721. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  27722. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  27723. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  27724. * security vulnerabilities.)
  27725. *
  27726. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  27727. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  27728. *
  27729. * How would you ensure that every place that used these types of bindings was bound to a value that
  27730. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  27731. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  27732. * properties/fields and forgot to update the binding to the sanitized value?
  27733. *
  27734. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  27735. * determine that something explicitly says it's safe to use a value for binding in that
  27736. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  27737. * for those values that you can easily tell are safe - because they were received from your server,
  27738. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  27739. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  27740. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  27741. *
  27742. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  27743. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  27744. * obtain values that will be accepted by SCE / privileged contexts.
  27745. *
  27746. *
  27747. * ## How does it work?
  27748. *
  27749. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  27750. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  27751. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  27752. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  27753. *
  27754. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  27755. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  27756. * simplified):
  27757. *
  27758. * ```
  27759. * var ngBindHtmlDirective = ['$sce', function($sce) {
  27760. * return function(scope, element, attr) {
  27761. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  27762. * element.html(value || '');
  27763. * });
  27764. * };
  27765. * }];
  27766. * ```
  27767. *
  27768. * ## Impact on loading templates
  27769. *
  27770. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  27771. * `templateUrl`'s specified by {@link guide/directive directives}.
  27772. *
  27773. * By default, Angular only loads templates from the same domain and protocol as the application
  27774. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  27775. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  27776. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  27777. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  27778. *
  27779. * *Please note*:
  27780. * The browser's
  27781. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  27782. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  27783. * policy apply in addition to this and may further restrict whether the template is successfully
  27784. * loaded. This means that without the right CORS policy, loading templates from a different domain
  27785. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  27786. * browsers.
  27787. *
  27788. * ## This feels like too much overhead
  27789. *
  27790. * It's important to remember that SCE only applies to interpolation expressions.
  27791. *
  27792. * If your expressions are constant literals, they're automatically trusted and you don't need to
  27793. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  27794. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  27795. *
  27796. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  27797. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  27798. *
  27799. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  27800. * templates in `ng-include` from your application's domain without having to even know about SCE.
  27801. * It blocks loading templates from other domains or loading templates over http from an https
  27802. * served document. You can change these by setting your own custom {@link
  27803. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  27804. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  27805. *
  27806. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  27807. * application that's secure and can be audited to verify that with much more ease than bolting
  27808. * security onto an application later.
  27809. *
  27810. * <a name="contexts"></a>
  27811. * ## What trusted context types are supported?
  27812. *
  27813. * | Context | Notes |
  27814. * |---------------------|----------------|
  27815. * | `$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. |
  27816. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  27817. * | `$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. |
  27818. * | `$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. |
  27819. * | `$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. |
  27820. *
  27821. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  27822. *
  27823. * Each element in these arrays must be one of the following:
  27824. *
  27825. * - **'self'**
  27826. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  27827. * domain** as the application document using the **same protocol**.
  27828. * - **String** (except the special value `'self'`)
  27829. * - The string is matched against the full *normalized / absolute URL* of the resource
  27830. * being tested (substring matches are not good enough.)
  27831. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  27832. * match themselves.
  27833. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  27834. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  27835. * in a whitelist.
  27836. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  27837. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  27838. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  27839. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  27840. * http://foo.example.com/templates/**).
  27841. * - **RegExp** (*see caveat below*)
  27842. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  27843. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  27844. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  27845. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  27846. * small number of cases. A `.` character in the regex used when matching the scheme or a
  27847. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  27848. * is highly recommended to use the string patterns and only fall back to regular expressions
  27849. * as a last resort.
  27850. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  27851. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  27852. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  27853. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  27854. * - If you are generating your JavaScript from some other templating engine (not
  27855. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  27856. * remember to escape your regular expression (and be aware that you might need more than
  27857. * one level of escaping depending on your templating engine and the way you interpolated
  27858. * the value.) Do make use of your platform's escaping mechanism as it might be good
  27859. * enough before coding your own. E.g. Ruby has
  27860. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  27861. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  27862. * Javascript lacks a similar built in function for escaping. Take a look at Google
  27863. * Closure library's [goog.string.regExpEscape(s)](
  27864. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  27865. *
  27866. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  27867. *
  27868. * ## Show me an example using SCE.
  27869. *
  27870. * <example module="mySceApp" deps="angular-sanitize.js">
  27871. * <file name="index.html">
  27872. * <div ng-controller="AppController as myCtrl">
  27873. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  27874. * <b>User comments</b><br>
  27875. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  27876. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  27877. * exploit.
  27878. * <div class="well">
  27879. * <div ng-repeat="userComment in myCtrl.userComments">
  27880. * <b>{{userComment.name}}</b>:
  27881. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  27882. * <br>
  27883. * </div>
  27884. * </div>
  27885. * </div>
  27886. * </file>
  27887. *
  27888. * <file name="script.js">
  27889. * angular.module('mySceApp', ['ngSanitize'])
  27890. * .controller('AppController', ['$http', '$templateCache', '$sce',
  27891. * function($http, $templateCache, $sce) {
  27892. * var self = this;
  27893. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  27894. * self.userComments = userComments;
  27895. * });
  27896. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  27897. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  27898. * 'sanitization.&quot;">Hover over this text.</span>');
  27899. * }]);
  27900. * </file>
  27901. *
  27902. * <file name="test_data.json">
  27903. * [
  27904. * { "name": "Alice",
  27905. * "htmlComment":
  27906. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  27907. * },
  27908. * { "name": "Bob",
  27909. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  27910. * }
  27911. * ]
  27912. * </file>
  27913. *
  27914. * <file name="protractor.js" type="protractor">
  27915. * describe('SCE doc demo', function() {
  27916. * it('should sanitize untrusted values', function() {
  27917. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  27918. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  27919. * });
  27920. *
  27921. * it('should NOT sanitize explicitly trusted values', function() {
  27922. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  27923. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  27924. * 'sanitization.&quot;">Hover over this text.</span>');
  27925. * });
  27926. * });
  27927. * </file>
  27928. * </example>
  27929. *
  27930. *
  27931. *
  27932. * ## Can I disable SCE completely?
  27933. *
  27934. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  27935. * for little coding overhead. It will be much harder to take an SCE disabled application and
  27936. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  27937. * for cases where you have a lot of existing code that was written before SCE was introduced and
  27938. * you're migrating them a module at a time.
  27939. *
  27940. * That said, here's how you can completely disable SCE:
  27941. *
  27942. * ```
  27943. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  27944. * // Completely disable SCE. For demonstration purposes only!
  27945. * // Do not use in new projects.
  27946. * $sceProvider.enabled(false);
  27947. * });
  27948. * ```
  27949. *
  27950. */
  27951. /* jshint maxlen: 100 */
  27952. function $SceProvider() {
  27953. var enabled = true;
  27954. /**
  27955. * @ngdoc method
  27956. * @name $sceProvider#enabled
  27957. * @kind function
  27958. *
  27959. * @param {boolean=} value If provided, then enables/disables SCE.
  27960. * @return {boolean} true if SCE is enabled, false otherwise.
  27961. *
  27962. * @description
  27963. * Enables/disables SCE and returns the current value.
  27964. */
  27965. this.enabled = function(value) {
  27966. if (arguments.length) {
  27967. enabled = !!value;
  27968. }
  27969. return enabled;
  27970. };
  27971. /* Design notes on the default implementation for SCE.
  27972. *
  27973. * The API contract for the SCE delegate
  27974. * -------------------------------------
  27975. * The SCE delegate object must provide the following 3 methods:
  27976. *
  27977. * - trustAs(contextEnum, value)
  27978. * This method is used to tell the SCE service that the provided value is OK to use in the
  27979. * contexts specified by contextEnum. It must return an object that will be accepted by
  27980. * getTrusted() for a compatible contextEnum and return this value.
  27981. *
  27982. * - valueOf(value)
  27983. * For values that were not produced by trustAs(), return them as is. For values that were
  27984. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  27985. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  27986. * such a value.
  27987. *
  27988. * - getTrusted(contextEnum, value)
  27989. * This function should return the a value that is safe to use in the context specified by
  27990. * contextEnum or throw and exception otherwise.
  27991. *
  27992. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  27993. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  27994. * instance, an implementation could maintain a registry of all trusted objects by context. In
  27995. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  27996. * return the same object passed in if it was found in the registry under a compatible context or
  27997. * throw an exception otherwise. An implementation might only wrap values some of the time based
  27998. * on some criteria. getTrusted() might return a value and not throw an exception for special
  27999. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  28000. *
  28001. *
  28002. * A note on the inheritance model for SCE contexts
  28003. * ------------------------------------------------
  28004. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  28005. * is purely an implementation details.
  28006. *
  28007. * The contract is simply this:
  28008. *
  28009. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  28010. * will also succeed.
  28011. *
  28012. * Inheritance happens to capture this in a natural way. In some future, we
  28013. * may not use inheritance anymore. That is OK because no code outside of
  28014. * sce.js and sceSpecs.js would need to be aware of this detail.
  28015. */
  28016. this.$get = ['$parse', '$sceDelegate', function(
  28017. $parse, $sceDelegate) {
  28018. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  28019. // the "expression(javascript expression)" syntax which is insecure.
  28020. if (enabled && msie < 8) {
  28021. throw $sceMinErr('iequirks',
  28022. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  28023. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  28024. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  28025. }
  28026. var sce = shallowCopy(SCE_CONTEXTS);
  28027. /**
  28028. * @ngdoc method
  28029. * @name $sce#isEnabled
  28030. * @kind function
  28031. *
  28032. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  28033. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  28034. *
  28035. * @description
  28036. * Returns a boolean indicating if SCE is enabled.
  28037. */
  28038. sce.isEnabled = function() {
  28039. return enabled;
  28040. };
  28041. sce.trustAs = $sceDelegate.trustAs;
  28042. sce.getTrusted = $sceDelegate.getTrusted;
  28043. sce.valueOf = $sceDelegate.valueOf;
  28044. if (!enabled) {
  28045. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  28046. sce.valueOf = identity;
  28047. }
  28048. /**
  28049. * @ngdoc method
  28050. * @name $sce#parseAs
  28051. *
  28052. * @description
  28053. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  28054. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  28055. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  28056. * *result*)}
  28057. *
  28058. * @param {string} type The kind of SCE context in which this result will be used.
  28059. * @param {string} expression String expression to compile.
  28060. * @returns {function(context, locals)} a function which represents the compiled expression:
  28061. *
  28062. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28063. * are evaluated against (typically a scope object).
  28064. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28065. * `context`.
  28066. */
  28067. sce.parseAs = function sceParseAs(type, expr) {
  28068. var parsed = $parse(expr);
  28069. if (parsed.literal && parsed.constant) {
  28070. return parsed;
  28071. } else {
  28072. return $parse(expr, function(value) {
  28073. return sce.getTrusted(type, value);
  28074. });
  28075. }
  28076. };
  28077. /**
  28078. * @ngdoc method
  28079. * @name $sce#trustAs
  28080. *
  28081. * @description
  28082. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  28083. * returns an object that is trusted by angular for use in specified strict contextual
  28084. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  28085. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  28086. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  28087. * escaping.
  28088. *
  28089. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  28090. * resourceUrl, html, js and css.
  28091. * @param {*} value The value that that should be considered trusted/safe.
  28092. * @returns {*} A value that can be used to stand in for the provided `value` in places
  28093. * where Angular expects a $sce.trustAs() return value.
  28094. */
  28095. /**
  28096. * @ngdoc method
  28097. * @name $sce#trustAsHtml
  28098. *
  28099. * @description
  28100. * Shorthand method. `$sce.trustAsHtml(value)` →
  28101. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  28102. *
  28103. * @param {*} value The value to trustAs.
  28104. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  28105. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  28106. * only accept expressions that are either literal constants or are the
  28107. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28108. */
  28109. /**
  28110. * @ngdoc method
  28111. * @name $sce#trustAsUrl
  28112. *
  28113. * @description
  28114. * Shorthand method. `$sce.trustAsUrl(value)` →
  28115. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  28116. *
  28117. * @param {*} value The value to trustAs.
  28118. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  28119. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  28120. * only accept expressions that are either literal constants or are the
  28121. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28122. */
  28123. /**
  28124. * @ngdoc method
  28125. * @name $sce#trustAsResourceUrl
  28126. *
  28127. * @description
  28128. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  28129. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  28130. *
  28131. * @param {*} value The value to trustAs.
  28132. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  28133. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  28134. * only accept expressions that are either literal constants or are the return
  28135. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28136. */
  28137. /**
  28138. * @ngdoc method
  28139. * @name $sce#trustAsJs
  28140. *
  28141. * @description
  28142. * Shorthand method. `$sce.trustAsJs(value)` →
  28143. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  28144. *
  28145. * @param {*} value The value to trustAs.
  28146. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  28147. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  28148. * only accept expressions that are either literal constants or are the
  28149. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28150. */
  28151. /**
  28152. * @ngdoc method
  28153. * @name $sce#getTrusted
  28154. *
  28155. * @description
  28156. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  28157. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  28158. * originally supplied value if the queried context type is a supertype of the created type.
  28159. * If this condition isn't satisfied, throws an exception.
  28160. *
  28161. * @param {string} type The kind of context in which this value is to be used.
  28162. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  28163. * call.
  28164. * @returns {*} The value the was originally provided to
  28165. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  28166. * Otherwise, throws an exception.
  28167. */
  28168. /**
  28169. * @ngdoc method
  28170. * @name $sce#getTrustedHtml
  28171. *
  28172. * @description
  28173. * Shorthand method. `$sce.getTrustedHtml(value)` →
  28174. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  28175. *
  28176. * @param {*} value The value to pass to `$sce.getTrusted`.
  28177. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  28178. */
  28179. /**
  28180. * @ngdoc method
  28181. * @name $sce#getTrustedCss
  28182. *
  28183. * @description
  28184. * Shorthand method. `$sce.getTrustedCss(value)` →
  28185. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  28186. *
  28187. * @param {*} value The value to pass to `$sce.getTrusted`.
  28188. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  28189. */
  28190. /**
  28191. * @ngdoc method
  28192. * @name $sce#getTrustedUrl
  28193. *
  28194. * @description
  28195. * Shorthand method. `$sce.getTrustedUrl(value)` →
  28196. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  28197. *
  28198. * @param {*} value The value to pass to `$sce.getTrusted`.
  28199. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  28200. */
  28201. /**
  28202. * @ngdoc method
  28203. * @name $sce#getTrustedResourceUrl
  28204. *
  28205. * @description
  28206. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  28207. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  28208. *
  28209. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  28210. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  28211. */
  28212. /**
  28213. * @ngdoc method
  28214. * @name $sce#getTrustedJs
  28215. *
  28216. * @description
  28217. * Shorthand method. `$sce.getTrustedJs(value)` →
  28218. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  28219. *
  28220. * @param {*} value The value to pass to `$sce.getTrusted`.
  28221. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  28222. */
  28223. /**
  28224. * @ngdoc method
  28225. * @name $sce#parseAsHtml
  28226. *
  28227. * @description
  28228. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  28229. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  28230. *
  28231. * @param {string} expression String expression to compile.
  28232. * @returns {function(context, locals)} a function which represents the compiled expression:
  28233. *
  28234. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28235. * are evaluated against (typically a scope object).
  28236. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28237. * `context`.
  28238. */
  28239. /**
  28240. * @ngdoc method
  28241. * @name $sce#parseAsCss
  28242. *
  28243. * @description
  28244. * Shorthand method. `$sce.parseAsCss(value)` →
  28245. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  28246. *
  28247. * @param {string} expression String expression to compile.
  28248. * @returns {function(context, locals)} a function which represents the compiled expression:
  28249. *
  28250. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28251. * are evaluated against (typically a scope object).
  28252. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28253. * `context`.
  28254. */
  28255. /**
  28256. * @ngdoc method
  28257. * @name $sce#parseAsUrl
  28258. *
  28259. * @description
  28260. * Shorthand method. `$sce.parseAsUrl(value)` →
  28261. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  28262. *
  28263. * @param {string} expression String expression to compile.
  28264. * @returns {function(context, locals)} a function which represents the compiled expression:
  28265. *
  28266. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28267. * are evaluated against (typically a scope object).
  28268. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28269. * `context`.
  28270. */
  28271. /**
  28272. * @ngdoc method
  28273. * @name $sce#parseAsResourceUrl
  28274. *
  28275. * @description
  28276. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  28277. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  28278. *
  28279. * @param {string} expression String expression to compile.
  28280. * @returns {function(context, locals)} a function which represents the compiled expression:
  28281. *
  28282. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28283. * are evaluated against (typically a scope object).
  28284. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28285. * `context`.
  28286. */
  28287. /**
  28288. * @ngdoc method
  28289. * @name $sce#parseAsJs
  28290. *
  28291. * @description
  28292. * Shorthand method. `$sce.parseAsJs(value)` →
  28293. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  28294. *
  28295. * @param {string} expression String expression to compile.
  28296. * @returns {function(context, locals)} a function which represents the compiled expression:
  28297. *
  28298. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28299. * are evaluated against (typically a scope object).
  28300. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28301. * `context`.
  28302. */
  28303. // Shorthand delegations.
  28304. var parse = sce.parseAs,
  28305. getTrusted = sce.getTrusted,
  28306. trustAs = sce.trustAs;
  28307. forEach(SCE_CONTEXTS, function(enumValue, name) {
  28308. var lName = lowercase(name);
  28309. sce[camelCase("parse_as_" + lName)] = function(expr) {
  28310. return parse(enumValue, expr);
  28311. };
  28312. sce[camelCase("get_trusted_" + lName)] = function(value) {
  28313. return getTrusted(enumValue, value);
  28314. };
  28315. sce[camelCase("trust_as_" + lName)] = function(value) {
  28316. return trustAs(enumValue, value);
  28317. };
  28318. });
  28319. return sce;
  28320. }];
  28321. }
  28322. /**
  28323. * !!! This is an undocumented "private" service !!!
  28324. *
  28325. * @name $sniffer
  28326. * @requires $window
  28327. * @requires $document
  28328. *
  28329. * @property {boolean} history Does the browser support html5 history api ?
  28330. * @property {boolean} transitions Does the browser support CSS transition events ?
  28331. * @property {boolean} animations Does the browser support CSS animation events ?
  28332. *
  28333. * @description
  28334. * This is very simple implementation of testing browser's features.
  28335. */
  28336. function $SnifferProvider() {
  28337. this.$get = ['$window', '$document', function($window, $document) {
  28338. var eventSupport = {},
  28339. // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
  28340. // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
  28341. isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
  28342. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  28343. android =
  28344. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  28345. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  28346. document = $document[0] || {},
  28347. vendorPrefix,
  28348. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  28349. bodyStyle = document.body && document.body.style,
  28350. transitions = false,
  28351. animations = false,
  28352. match;
  28353. if (bodyStyle) {
  28354. for (var prop in bodyStyle) {
  28355. if (match = vendorRegex.exec(prop)) {
  28356. vendorPrefix = match[0];
  28357. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  28358. break;
  28359. }
  28360. }
  28361. if (!vendorPrefix) {
  28362. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  28363. }
  28364. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  28365. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  28366. if (android && (!transitions || !animations)) {
  28367. transitions = isString(bodyStyle.webkitTransition);
  28368. animations = isString(bodyStyle.webkitAnimation);
  28369. }
  28370. }
  28371. return {
  28372. // Android has history.pushState, but it does not update location correctly
  28373. // so let's not use the history API at all.
  28374. // http://code.google.com/p/android/issues/detail?id=17471
  28375. // https://github.com/angular/angular.js/issues/904
  28376. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  28377. // so let's not use the history API also
  28378. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  28379. // jshint -W018
  28380. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  28381. // jshint +W018
  28382. hasEvent: function(event) {
  28383. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  28384. // it. In particular the event is not fired when backspace or delete key are pressed or
  28385. // when cut operation is performed.
  28386. // IE10+ implements 'input' event but it erroneously fires under various situations,
  28387. // e.g. when placeholder changes, or a form is focused.
  28388. if (event === 'input' && msie <= 11) return false;
  28389. if (isUndefined(eventSupport[event])) {
  28390. var divElm = document.createElement('div');
  28391. eventSupport[event] = 'on' + event in divElm;
  28392. }
  28393. return eventSupport[event];
  28394. },
  28395. csp: csp(),
  28396. vendorPrefix: vendorPrefix,
  28397. transitions: transitions,
  28398. animations: animations,
  28399. android: android
  28400. };
  28401. }];
  28402. }
  28403. var $templateRequestMinErr = minErr('$compile');
  28404. /**
  28405. * @ngdoc provider
  28406. * @name $templateRequestProvider
  28407. * @description
  28408. * Used to configure the options passed to the {@link $http} service when making a template request.
  28409. *
  28410. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  28411. * requesting a template.
  28412. */
  28413. function $TemplateRequestProvider() {
  28414. var httpOptions;
  28415. /**
  28416. * @ngdoc method
  28417. * @name $templateRequestProvider#httpOptions
  28418. * @description
  28419. * The options to be passed to the {@link $http} service when making the request.
  28420. * You can use this to override options such as the "Accept" header for template requests.
  28421. *
  28422. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  28423. * options if not overridden here.
  28424. *
  28425. * @param {string=} value new value for the {@link $http} options.
  28426. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  28427. */
  28428. this.httpOptions = function(val) {
  28429. if (val) {
  28430. httpOptions = val;
  28431. return this;
  28432. }
  28433. return httpOptions;
  28434. };
  28435. /**
  28436. * @ngdoc service
  28437. * @name $templateRequest
  28438. *
  28439. * @description
  28440. * The `$templateRequest` service runs security checks then downloads the provided template using
  28441. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  28442. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  28443. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  28444. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  28445. * when `tpl` is of type string and `$templateCache` has the matching entry.
  28446. *
  28447. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  28448. * can configure this via {@link $templateRequestProvider#httpOptions}.
  28449. *
  28450. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  28451. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  28452. *
  28453. * @return {Promise} a promise for the HTTP response data of the given URL.
  28454. *
  28455. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  28456. */
  28457. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  28458. function handleRequestFn(tpl, ignoreRequestError) {
  28459. handleRequestFn.totalPendingRequests++;
  28460. // We consider the template cache holds only trusted templates, so
  28461. // there's no need to go through whitelisting again for keys that already
  28462. // are included in there. This also makes Angular accept any script
  28463. // directive, no matter its name. However, we still need to unwrap trusted
  28464. // types.
  28465. if (!isString(tpl) || !$templateCache.get(tpl)) {
  28466. tpl = $sce.getTrustedResourceUrl(tpl);
  28467. }
  28468. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  28469. if (isArray(transformResponse)) {
  28470. transformResponse = transformResponse.filter(function(transformer) {
  28471. return transformer !== defaultHttpResponseTransform;
  28472. });
  28473. } else if (transformResponse === defaultHttpResponseTransform) {
  28474. transformResponse = null;
  28475. }
  28476. return $http.get(tpl, extend({
  28477. cache: $templateCache,
  28478. transformResponse: transformResponse
  28479. }, httpOptions))
  28480. ['finally'](function() {
  28481. handleRequestFn.totalPendingRequests--;
  28482. })
  28483. .then(function(response) {
  28484. $templateCache.put(tpl, response.data);
  28485. return response.data;
  28486. }, handleError);
  28487. function handleError(resp) {
  28488. if (!ignoreRequestError) {
  28489. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  28490. tpl, resp.status, resp.statusText);
  28491. }
  28492. return $q.reject(resp);
  28493. }
  28494. }
  28495. handleRequestFn.totalPendingRequests = 0;
  28496. return handleRequestFn;
  28497. }];
  28498. }
  28499. function $$TestabilityProvider() {
  28500. this.$get = ['$rootScope', '$browser', '$location',
  28501. function($rootScope, $browser, $location) {
  28502. /**
  28503. * @name $testability
  28504. *
  28505. * @description
  28506. * The private $$testability service provides a collection of methods for use when debugging
  28507. * or by automated test and debugging tools.
  28508. */
  28509. var testability = {};
  28510. /**
  28511. * @name $$testability#findBindings
  28512. *
  28513. * @description
  28514. * Returns an array of elements that are bound (via ng-bind or {{}})
  28515. * to expressions matching the input.
  28516. *
  28517. * @param {Element} element The element root to search from.
  28518. * @param {string} expression The binding expression to match.
  28519. * @param {boolean} opt_exactMatch If true, only returns exact matches
  28520. * for the expression. Filters and whitespace are ignored.
  28521. */
  28522. testability.findBindings = function(element, expression, opt_exactMatch) {
  28523. var bindings = element.getElementsByClassName('ng-binding');
  28524. var matches = [];
  28525. forEach(bindings, function(binding) {
  28526. var dataBinding = angular.element(binding).data('$binding');
  28527. if (dataBinding) {
  28528. forEach(dataBinding, function(bindingName) {
  28529. if (opt_exactMatch) {
  28530. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  28531. if (matcher.test(bindingName)) {
  28532. matches.push(binding);
  28533. }
  28534. } else {
  28535. if (bindingName.indexOf(expression) != -1) {
  28536. matches.push(binding);
  28537. }
  28538. }
  28539. });
  28540. }
  28541. });
  28542. return matches;
  28543. };
  28544. /**
  28545. * @name $$testability#findModels
  28546. *
  28547. * @description
  28548. * Returns an array of elements that are two-way found via ng-model to
  28549. * expressions matching the input.
  28550. *
  28551. * @param {Element} element The element root to search from.
  28552. * @param {string} expression The model expression to match.
  28553. * @param {boolean} opt_exactMatch If true, only returns exact matches
  28554. * for the expression.
  28555. */
  28556. testability.findModels = function(element, expression, opt_exactMatch) {
  28557. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  28558. for (var p = 0; p < prefixes.length; ++p) {
  28559. var attributeEquals = opt_exactMatch ? '=' : '*=';
  28560. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  28561. var elements = element.querySelectorAll(selector);
  28562. if (elements.length) {
  28563. return elements;
  28564. }
  28565. }
  28566. };
  28567. /**
  28568. * @name $$testability#getLocation
  28569. *
  28570. * @description
  28571. * Shortcut for getting the location in a browser agnostic way. Returns
  28572. * the path, search, and hash. (e.g. /path?a=b#hash)
  28573. */
  28574. testability.getLocation = function() {
  28575. return $location.url();
  28576. };
  28577. /**
  28578. * @name $$testability#setLocation
  28579. *
  28580. * @description
  28581. * Shortcut for navigating to a location without doing a full page reload.
  28582. *
  28583. * @param {string} url The location url (path, search and hash,
  28584. * e.g. /path?a=b#hash) to go to.
  28585. */
  28586. testability.setLocation = function(url) {
  28587. if (url !== $location.url()) {
  28588. $location.url(url);
  28589. $rootScope.$digest();
  28590. }
  28591. };
  28592. /**
  28593. * @name $$testability#whenStable
  28594. *
  28595. * @description
  28596. * Calls the callback when $timeout and $http requests are completed.
  28597. *
  28598. * @param {function} callback
  28599. */
  28600. testability.whenStable = function(callback) {
  28601. $browser.notifyWhenNoOutstandingRequests(callback);
  28602. };
  28603. return testability;
  28604. }];
  28605. }
  28606. function $TimeoutProvider() {
  28607. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  28608. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  28609. var deferreds = {};
  28610. /**
  28611. * @ngdoc service
  28612. * @name $timeout
  28613. *
  28614. * @description
  28615. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  28616. * block and delegates any exceptions to
  28617. * {@link ng.$exceptionHandler $exceptionHandler} service.
  28618. *
  28619. * The return value of calling `$timeout` is a promise, which will be resolved when
  28620. * the delay has passed and the timeout function, if provided, is executed.
  28621. *
  28622. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  28623. *
  28624. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  28625. * synchronously flush the queue of deferred functions.
  28626. *
  28627. * If you only want a promise that will be resolved after some specified delay
  28628. * then you can call `$timeout` without the `fn` function.
  28629. *
  28630. * @param {function()=} fn A function, whose execution should be delayed.
  28631. * @param {number=} [delay=0] Delay in milliseconds.
  28632. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  28633. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  28634. * @param {...*=} Pass additional parameters to the executed function.
  28635. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  28636. * will be resolved with the return value of the `fn` function.
  28637. *
  28638. */
  28639. function timeout(fn, delay, invokeApply) {
  28640. if (!isFunction(fn)) {
  28641. invokeApply = delay;
  28642. delay = fn;
  28643. fn = noop;
  28644. }
  28645. var args = sliceArgs(arguments, 3),
  28646. skipApply = (isDefined(invokeApply) && !invokeApply),
  28647. deferred = (skipApply ? $$q : $q).defer(),
  28648. promise = deferred.promise,
  28649. timeoutId;
  28650. timeoutId = $browser.defer(function() {
  28651. try {
  28652. deferred.resolve(fn.apply(null, args));
  28653. } catch (e) {
  28654. deferred.reject(e);
  28655. $exceptionHandler(e);
  28656. }
  28657. finally {
  28658. delete deferreds[promise.$$timeoutId];
  28659. }
  28660. if (!skipApply) $rootScope.$apply();
  28661. }, delay);
  28662. promise.$$timeoutId = timeoutId;
  28663. deferreds[timeoutId] = deferred;
  28664. return promise;
  28665. }
  28666. /**
  28667. * @ngdoc method
  28668. * @name $timeout#cancel
  28669. *
  28670. * @description
  28671. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  28672. * resolved with a rejection.
  28673. *
  28674. * @param {Promise=} promise Promise returned by the `$timeout` function.
  28675. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  28676. * canceled.
  28677. */
  28678. timeout.cancel = function(promise) {
  28679. if (promise && promise.$$timeoutId in deferreds) {
  28680. deferreds[promise.$$timeoutId].reject('canceled');
  28681. delete deferreds[promise.$$timeoutId];
  28682. return $browser.defer.cancel(promise.$$timeoutId);
  28683. }
  28684. return false;
  28685. };
  28686. return timeout;
  28687. }];
  28688. }
  28689. // NOTE: The usage of window and document instead of $window and $document here is
  28690. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  28691. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  28692. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  28693. // doesn't know about mocked locations and resolves URLs to the real document - which is
  28694. // exactly the behavior needed here. There is little value is mocking these out for this
  28695. // service.
  28696. var urlParsingNode = document.createElement("a");
  28697. var originUrl = urlResolve(window.location.href);
  28698. /**
  28699. *
  28700. * Implementation Notes for non-IE browsers
  28701. * ----------------------------------------
  28702. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  28703. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  28704. * URL will be resolved into an absolute URL in the context of the application document.
  28705. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  28706. * properties are all populated to reflect the normalized URL. This approach has wide
  28707. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  28708. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  28709. *
  28710. * Implementation Notes for IE
  28711. * ---------------------------
  28712. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  28713. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  28714. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  28715. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  28716. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  28717. * properties such as protocol, hostname, port, etc.
  28718. *
  28719. * References:
  28720. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  28721. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  28722. * http://url.spec.whatwg.org/#urlutils
  28723. * https://github.com/angular/angular.js/pull/2902
  28724. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  28725. *
  28726. * @kind function
  28727. * @param {string} url The URL to be parsed.
  28728. * @description Normalizes and parses a URL.
  28729. * @returns {object} Returns the normalized URL as a dictionary.
  28730. *
  28731. * | member name | Description |
  28732. * |---------------|----------------|
  28733. * | href | A normalized version of the provided URL if it was not an absolute URL |
  28734. * | protocol | The protocol including the trailing colon |
  28735. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  28736. * | search | The search params, minus the question mark |
  28737. * | hash | The hash string, minus the hash symbol
  28738. * | hostname | The hostname
  28739. * | port | The port, without ":"
  28740. * | pathname | The pathname, beginning with "/"
  28741. *
  28742. */
  28743. function urlResolve(url) {
  28744. var href = url;
  28745. if (msie) {
  28746. // Normalize before parse. Refer Implementation Notes on why this is
  28747. // done in two steps on IE.
  28748. urlParsingNode.setAttribute("href", href);
  28749. href = urlParsingNode.href;
  28750. }
  28751. urlParsingNode.setAttribute('href', href);
  28752. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  28753. return {
  28754. href: urlParsingNode.href,
  28755. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  28756. host: urlParsingNode.host,
  28757. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  28758. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  28759. hostname: urlParsingNode.hostname,
  28760. port: urlParsingNode.port,
  28761. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  28762. ? urlParsingNode.pathname
  28763. : '/' + urlParsingNode.pathname
  28764. };
  28765. }
  28766. /**
  28767. * Parse a request URL and determine whether this is a same-origin request as the application document.
  28768. *
  28769. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  28770. * or a parsed URL object.
  28771. * @returns {boolean} Whether the request is for the same origin as the application document.
  28772. */
  28773. function urlIsSameOrigin(requestUrl) {
  28774. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  28775. return (parsed.protocol === originUrl.protocol &&
  28776. parsed.host === originUrl.host);
  28777. }
  28778. /**
  28779. * @ngdoc service
  28780. * @name $window
  28781. *
  28782. * @description
  28783. * A reference to the browser's `window` object. While `window`
  28784. * is globally available in JavaScript, it causes testability problems, because
  28785. * it is a global variable. In angular we always refer to it through the
  28786. * `$window` service, so it may be overridden, removed or mocked for testing.
  28787. *
  28788. * Expressions, like the one defined for the `ngClick` directive in the example
  28789. * below, are evaluated with respect to the current scope. Therefore, there is
  28790. * no risk of inadvertently coding in a dependency on a global value in such an
  28791. * expression.
  28792. *
  28793. * @example
  28794. <example module="windowExample">
  28795. <file name="index.html">
  28796. <script>
  28797. angular.module('windowExample', [])
  28798. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  28799. $scope.greeting = 'Hello, World!';
  28800. $scope.doGreeting = function(greeting) {
  28801. $window.alert(greeting);
  28802. };
  28803. }]);
  28804. </script>
  28805. <div ng-controller="ExampleController">
  28806. <input type="text" ng-model="greeting" aria-label="greeting" />
  28807. <button ng-click="doGreeting(greeting)">ALERT</button>
  28808. </div>
  28809. </file>
  28810. <file name="protractor.js" type="protractor">
  28811. it('should display the greeting in the input box', function() {
  28812. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  28813. // If we click the button it will block the test runner
  28814. // element(':button').click();
  28815. });
  28816. </file>
  28817. </example>
  28818. */
  28819. function $WindowProvider() {
  28820. this.$get = valueFn(window);
  28821. }
  28822. /**
  28823. * @name $$cookieReader
  28824. * @requires $document
  28825. *
  28826. * @description
  28827. * This is a private service for reading cookies used by $http and ngCookies
  28828. *
  28829. * @return {Object} a key/value map of the current cookies
  28830. */
  28831. function $$CookieReader($document) {
  28832. var rawDocument = $document[0] || {};
  28833. var lastCookies = {};
  28834. var lastCookieString = '';
  28835. function safeDecodeURIComponent(str) {
  28836. try {
  28837. return decodeURIComponent(str);
  28838. } catch (e) {
  28839. return str;
  28840. }
  28841. }
  28842. return function() {
  28843. var cookieArray, cookie, i, index, name;
  28844. var currentCookieString = rawDocument.cookie || '';
  28845. if (currentCookieString !== lastCookieString) {
  28846. lastCookieString = currentCookieString;
  28847. cookieArray = lastCookieString.split('; ');
  28848. lastCookies = {};
  28849. for (i = 0; i < cookieArray.length; i++) {
  28850. cookie = cookieArray[i];
  28851. index = cookie.indexOf('=');
  28852. if (index > 0) { //ignore nameless cookies
  28853. name = safeDecodeURIComponent(cookie.substring(0, index));
  28854. // the first value that is seen for a cookie is the most
  28855. // specific one. values for the same cookie name that
  28856. // follow are for less specific paths.
  28857. if (isUndefined(lastCookies[name])) {
  28858. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  28859. }
  28860. }
  28861. }
  28862. }
  28863. return lastCookies;
  28864. };
  28865. }
  28866. $$CookieReader.$inject = ['$document'];
  28867. function $$CookieReaderProvider() {
  28868. this.$get = $$CookieReader;
  28869. }
  28870. /* global currencyFilter: true,
  28871. dateFilter: true,
  28872. filterFilter: true,
  28873. jsonFilter: true,
  28874. limitToFilter: true,
  28875. lowercaseFilter: true,
  28876. numberFilter: true,
  28877. orderByFilter: true,
  28878. uppercaseFilter: true,
  28879. */
  28880. /**
  28881. * @ngdoc provider
  28882. * @name $filterProvider
  28883. * @description
  28884. *
  28885. * Filters are just functions which transform input to an output. However filters need to be
  28886. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  28887. * annotated with dependencies and is responsible for creating a filter function.
  28888. *
  28889. * <div class="alert alert-warning">
  28890. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  28891. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  28892. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  28893. * (`myapp_subsection_filterx`).
  28894. * </div>
  28895. *
  28896. * ```js
  28897. * // Filter registration
  28898. * function MyModule($provide, $filterProvider) {
  28899. * // create a service to demonstrate injection (not always needed)
  28900. * $provide.value('greet', function(name){
  28901. * return 'Hello ' + name + '!';
  28902. * });
  28903. *
  28904. * // register a filter factory which uses the
  28905. * // greet service to demonstrate DI.
  28906. * $filterProvider.register('greet', function(greet){
  28907. * // return the filter function which uses the greet service
  28908. * // to generate salutation
  28909. * return function(text) {
  28910. * // filters need to be forgiving so check input validity
  28911. * return text && greet(text) || text;
  28912. * };
  28913. * });
  28914. * }
  28915. * ```
  28916. *
  28917. * The filter function is registered with the `$injector` under the filter name suffix with
  28918. * `Filter`.
  28919. *
  28920. * ```js
  28921. * it('should be the same instance', inject(
  28922. * function($filterProvider) {
  28923. * $filterProvider.register('reverse', function(){
  28924. * return ...;
  28925. * });
  28926. * },
  28927. * function($filter, reverseFilter) {
  28928. * expect($filter('reverse')).toBe(reverseFilter);
  28929. * });
  28930. * ```
  28931. *
  28932. *
  28933. * For more information about how angular filters work, and how to create your own filters, see
  28934. * {@link guide/filter Filters} in the Angular Developer Guide.
  28935. */
  28936. /**
  28937. * @ngdoc service
  28938. * @name $filter
  28939. * @kind function
  28940. * @description
  28941. * Filters are used for formatting data displayed to the user.
  28942. *
  28943. * The general syntax in templates is as follows:
  28944. *
  28945. * {{ expression [| filter_name[:parameter_value] ... ] }}
  28946. *
  28947. * @param {String} name Name of the filter function to retrieve
  28948. * @return {Function} the filter function
  28949. * @example
  28950. <example name="$filter" module="filterExample">
  28951. <file name="index.html">
  28952. <div ng-controller="MainCtrl">
  28953. <h3>{{ originalText }}</h3>
  28954. <h3>{{ filteredText }}</h3>
  28955. </div>
  28956. </file>
  28957. <file name="script.js">
  28958. angular.module('filterExample', [])
  28959. .controller('MainCtrl', function($scope, $filter) {
  28960. $scope.originalText = 'hello';
  28961. $scope.filteredText = $filter('uppercase')($scope.originalText);
  28962. });
  28963. </file>
  28964. </example>
  28965. */
  28966. $FilterProvider.$inject = ['$provide'];
  28967. function $FilterProvider($provide) {
  28968. var suffix = 'Filter';
  28969. /**
  28970. * @ngdoc method
  28971. * @name $filterProvider#register
  28972. * @param {string|Object} name Name of the filter function, or an object map of filters where
  28973. * the keys are the filter names and the values are the filter factories.
  28974. *
  28975. * <div class="alert alert-warning">
  28976. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  28977. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  28978. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  28979. * (`myapp_subsection_filterx`).
  28980. * </div>
  28981. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  28982. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  28983. * of the registered filter instances.
  28984. */
  28985. function register(name, factory) {
  28986. if (isObject(name)) {
  28987. var filters = {};
  28988. forEach(name, function(filter, key) {
  28989. filters[key] = register(key, filter);
  28990. });
  28991. return filters;
  28992. } else {
  28993. return $provide.factory(name + suffix, factory);
  28994. }
  28995. }
  28996. this.register = register;
  28997. this.$get = ['$injector', function($injector) {
  28998. return function(name) {
  28999. return $injector.get(name + suffix);
  29000. };
  29001. }];
  29002. ////////////////////////////////////////
  29003. /* global
  29004. currencyFilter: false,
  29005. dateFilter: false,
  29006. filterFilter: false,
  29007. jsonFilter: false,
  29008. limitToFilter: false,
  29009. lowercaseFilter: false,
  29010. numberFilter: false,
  29011. orderByFilter: false,
  29012. uppercaseFilter: false,
  29013. */
  29014. register('currency', currencyFilter);
  29015. register('date', dateFilter);
  29016. register('filter', filterFilter);
  29017. register('json', jsonFilter);
  29018. register('limitTo', limitToFilter);
  29019. register('lowercase', lowercaseFilter);
  29020. register('number', numberFilter);
  29021. register('orderBy', orderByFilter);
  29022. register('uppercase', uppercaseFilter);
  29023. }
  29024. /**
  29025. * @ngdoc filter
  29026. * @name filter
  29027. * @kind function
  29028. *
  29029. * @description
  29030. * Selects a subset of items from `array` and returns it as a new array.
  29031. *
  29032. * @param {Array} array The source array.
  29033. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  29034. * `array`.
  29035. *
  29036. * Can be one of:
  29037. *
  29038. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  29039. * objects with string properties in `array` that match this string will be returned. This also
  29040. * applies to nested object properties.
  29041. * The predicate can be negated by prefixing the string with `!`.
  29042. *
  29043. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  29044. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  29045. * which have property `name` containing "M" and property `phone` containing "1". A special
  29046. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  29047. * property of the object or its nested object properties. That's equivalent to the simple
  29048. * substring match with a `string` as described above. The predicate can be negated by prefixing
  29049. * the string with `!`.
  29050. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  29051. * not containing "M".
  29052. *
  29053. * Note that a named property will match properties on the same level only, while the special
  29054. * `$` property will match properties on the same level or deeper. E.g. an array item like
  29055. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  29056. * **will** be matched by `{$: 'John'}`.
  29057. *
  29058. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  29059. * The function is called for each element of the array, with the element, its index, and
  29060. * the entire array itself as arguments.
  29061. *
  29062. * The final result is an array of those elements that the predicate returned true for.
  29063. *
  29064. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  29065. * determining if the expected value (from the filter expression) and actual value (from
  29066. * the object in the array) should be considered a match.
  29067. *
  29068. * Can be one of:
  29069. *
  29070. * - `function(actual, expected)`:
  29071. * The function will be given the object value and the predicate value to compare and
  29072. * should return true if both values should be considered equal.
  29073. *
  29074. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  29075. * This is essentially strict comparison of expected and actual.
  29076. *
  29077. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  29078. * insensitive way.
  29079. *
  29080. * Primitive values are converted to strings. Objects are not compared against primitives,
  29081. * unless they have a custom `toString` method (e.g. `Date` objects).
  29082. *
  29083. * @example
  29084. <example>
  29085. <file name="index.html">
  29086. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  29087. {name:'Mary', phone:'800-BIG-MARY'},
  29088. {name:'Mike', phone:'555-4321'},
  29089. {name:'Adam', phone:'555-5678'},
  29090. {name:'Julie', phone:'555-8765'},
  29091. {name:'Juliette', phone:'555-5678'}]"></div>
  29092. <label>Search: <input ng-model="searchText"></label>
  29093. <table id="searchTextResults">
  29094. <tr><th>Name</th><th>Phone</th></tr>
  29095. <tr ng-repeat="friend in friends | filter:searchText">
  29096. <td>{{friend.name}}</td>
  29097. <td>{{friend.phone}}</td>
  29098. </tr>
  29099. </table>
  29100. <hr>
  29101. <label>Any: <input ng-model="search.$"></label> <br>
  29102. <label>Name only <input ng-model="search.name"></label><br>
  29103. <label>Phone only <input ng-model="search.phone"></label><br>
  29104. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  29105. <table id="searchObjResults">
  29106. <tr><th>Name</th><th>Phone</th></tr>
  29107. <tr ng-repeat="friendObj in friends | filter:search:strict">
  29108. <td>{{friendObj.name}}</td>
  29109. <td>{{friendObj.phone}}</td>
  29110. </tr>
  29111. </table>
  29112. </file>
  29113. <file name="protractor.js" type="protractor">
  29114. var expectFriendNames = function(expectedNames, key) {
  29115. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  29116. arr.forEach(function(wd, i) {
  29117. expect(wd.getText()).toMatch(expectedNames[i]);
  29118. });
  29119. });
  29120. };
  29121. it('should search across all fields when filtering with a string', function() {
  29122. var searchText = element(by.model('searchText'));
  29123. searchText.clear();
  29124. searchText.sendKeys('m');
  29125. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  29126. searchText.clear();
  29127. searchText.sendKeys('76');
  29128. expectFriendNames(['John', 'Julie'], 'friend');
  29129. });
  29130. it('should search in specific fields when filtering with a predicate object', function() {
  29131. var searchAny = element(by.model('search.$'));
  29132. searchAny.clear();
  29133. searchAny.sendKeys('i');
  29134. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  29135. });
  29136. it('should use a equal comparison when comparator is true', function() {
  29137. var searchName = element(by.model('search.name'));
  29138. var strict = element(by.model('strict'));
  29139. searchName.clear();
  29140. searchName.sendKeys('Julie');
  29141. strict.click();
  29142. expectFriendNames(['Julie'], 'friendObj');
  29143. });
  29144. </file>
  29145. </example>
  29146. */
  29147. function filterFilter() {
  29148. return function(array, expression, comparator) {
  29149. if (!isArrayLike(array)) {
  29150. if (array == null) {
  29151. return array;
  29152. } else {
  29153. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  29154. }
  29155. }
  29156. var expressionType = getTypeForFilter(expression);
  29157. var predicateFn;
  29158. var matchAgainstAnyProp;
  29159. switch (expressionType) {
  29160. case 'function':
  29161. predicateFn = expression;
  29162. break;
  29163. case 'boolean':
  29164. case 'null':
  29165. case 'number':
  29166. case 'string':
  29167. matchAgainstAnyProp = true;
  29168. //jshint -W086
  29169. case 'object':
  29170. //jshint +W086
  29171. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  29172. break;
  29173. default:
  29174. return array;
  29175. }
  29176. return Array.prototype.filter.call(array, predicateFn);
  29177. };
  29178. }
  29179. // Helper functions for `filterFilter`
  29180. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  29181. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  29182. var predicateFn;
  29183. if (comparator === true) {
  29184. comparator = equals;
  29185. } else if (!isFunction(comparator)) {
  29186. comparator = function(actual, expected) {
  29187. if (isUndefined(actual)) {
  29188. // No substring matching against `undefined`
  29189. return false;
  29190. }
  29191. if ((actual === null) || (expected === null)) {
  29192. // No substring matching against `null`; only match against `null`
  29193. return actual === expected;
  29194. }
  29195. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  29196. // Should not compare primitives against objects, unless they have custom `toString` method
  29197. return false;
  29198. }
  29199. actual = lowercase('' + actual);
  29200. expected = lowercase('' + expected);
  29201. return actual.indexOf(expected) !== -1;
  29202. };
  29203. }
  29204. predicateFn = function(item) {
  29205. if (shouldMatchPrimitives && !isObject(item)) {
  29206. return deepCompare(item, expression.$, comparator, false);
  29207. }
  29208. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  29209. };
  29210. return predicateFn;
  29211. }
  29212. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  29213. var actualType = getTypeForFilter(actual);
  29214. var expectedType = getTypeForFilter(expected);
  29215. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  29216. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  29217. } else if (isArray(actual)) {
  29218. // In case `actual` is an array, consider it a match
  29219. // if ANY of it's items matches `expected`
  29220. return actual.some(function(item) {
  29221. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  29222. });
  29223. }
  29224. switch (actualType) {
  29225. case 'object':
  29226. var key;
  29227. if (matchAgainstAnyProp) {
  29228. for (key in actual) {
  29229. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  29230. return true;
  29231. }
  29232. }
  29233. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  29234. } else if (expectedType === 'object') {
  29235. for (key in expected) {
  29236. var expectedVal = expected[key];
  29237. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  29238. continue;
  29239. }
  29240. var matchAnyProperty = key === '$';
  29241. var actualVal = matchAnyProperty ? actual : actual[key];
  29242. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  29243. return false;
  29244. }
  29245. }
  29246. return true;
  29247. } else {
  29248. return comparator(actual, expected);
  29249. }
  29250. break;
  29251. case 'function':
  29252. return false;
  29253. default:
  29254. return comparator(actual, expected);
  29255. }
  29256. }
  29257. // Used for easily differentiating between `null` and actual `object`
  29258. function getTypeForFilter(val) {
  29259. return (val === null) ? 'null' : typeof val;
  29260. }
  29261. var MAX_DIGITS = 22;
  29262. var DECIMAL_SEP = '.';
  29263. var ZERO_CHAR = '0';
  29264. /**
  29265. * @ngdoc filter
  29266. * @name currency
  29267. * @kind function
  29268. *
  29269. * @description
  29270. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  29271. * symbol for current locale is used.
  29272. *
  29273. * @param {number} amount Input to filter.
  29274. * @param {string=} symbol Currency symbol or identifier to be displayed.
  29275. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  29276. * @returns {string} Formatted number.
  29277. *
  29278. *
  29279. * @example
  29280. <example module="currencyExample">
  29281. <file name="index.html">
  29282. <script>
  29283. angular.module('currencyExample', [])
  29284. .controller('ExampleController', ['$scope', function($scope) {
  29285. $scope.amount = 1234.56;
  29286. }]);
  29287. </script>
  29288. <div ng-controller="ExampleController">
  29289. <input type="number" ng-model="amount" aria-label="amount"> <br>
  29290. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  29291. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  29292. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  29293. </div>
  29294. </file>
  29295. <file name="protractor.js" type="protractor">
  29296. it('should init with 1234.56', function() {
  29297. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  29298. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  29299. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  29300. });
  29301. it('should update', function() {
  29302. if (browser.params.browser == 'safari') {
  29303. // Safari does not understand the minus key. See
  29304. // https://github.com/angular/protractor/issues/481
  29305. return;
  29306. }
  29307. element(by.model('amount')).clear();
  29308. element(by.model('amount')).sendKeys('-1234');
  29309. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  29310. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  29311. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  29312. });
  29313. </file>
  29314. </example>
  29315. */
  29316. currencyFilter.$inject = ['$locale'];
  29317. function currencyFilter($locale) {
  29318. var formats = $locale.NUMBER_FORMATS;
  29319. return function(amount, currencySymbol, fractionSize) {
  29320. if (isUndefined(currencySymbol)) {
  29321. currencySymbol = formats.CURRENCY_SYM;
  29322. }
  29323. if (isUndefined(fractionSize)) {
  29324. fractionSize = formats.PATTERNS[1].maxFrac;
  29325. }
  29326. // if null or undefined pass it through
  29327. return (amount == null)
  29328. ? amount
  29329. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  29330. replace(/\u00A4/g, currencySymbol);
  29331. };
  29332. }
  29333. /**
  29334. * @ngdoc filter
  29335. * @name number
  29336. * @kind function
  29337. *
  29338. * @description
  29339. * Formats a number as text.
  29340. *
  29341. * If the input is null or undefined, it will just be returned.
  29342. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  29343. * If the input is not a number an empty string is returned.
  29344. *
  29345. *
  29346. * @param {number|string} number Number to format.
  29347. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  29348. * If this is not provided then the fraction size is computed from the current locale's number
  29349. * formatting pattern. In the case of the default locale, it will be 3.
  29350. * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
  29351. *
  29352. * @example
  29353. <example module="numberFilterExample">
  29354. <file name="index.html">
  29355. <script>
  29356. angular.module('numberFilterExample', [])
  29357. .controller('ExampleController', ['$scope', function($scope) {
  29358. $scope.val = 1234.56789;
  29359. }]);
  29360. </script>
  29361. <div ng-controller="ExampleController">
  29362. <label>Enter number: <input ng-model='val'></label><br>
  29363. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  29364. No fractions: <span>{{val | number:0}}</span><br>
  29365. Negative number: <span>{{-val | number:4}}</span>
  29366. </div>
  29367. </file>
  29368. <file name="protractor.js" type="protractor">
  29369. it('should format numbers', function() {
  29370. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  29371. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  29372. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  29373. });
  29374. it('should update', function() {
  29375. element(by.model('val')).clear();
  29376. element(by.model('val')).sendKeys('3374.333');
  29377. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  29378. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  29379. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  29380. });
  29381. </file>
  29382. </example>
  29383. */
  29384. numberFilter.$inject = ['$locale'];
  29385. function numberFilter($locale) {
  29386. var formats = $locale.NUMBER_FORMATS;
  29387. return function(number, fractionSize) {
  29388. // if null or undefined pass it through
  29389. return (number == null)
  29390. ? number
  29391. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  29392. fractionSize);
  29393. };
  29394. }
  29395. /**
  29396. * Parse a number (as a string) into three components that can be used
  29397. * for formatting the number.
  29398. *
  29399. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  29400. *
  29401. * @param {string} numStr The number to parse
  29402. * @return {object} An object describing this number, containing the following keys:
  29403. * - d : an array of digits containing leading zeros as necessary
  29404. * - i : the number of the digits in `d` that are to the left of the decimal point
  29405. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  29406. *
  29407. */
  29408. function parse(numStr) {
  29409. var exponent = 0, digits, numberOfIntegerDigits;
  29410. var i, j, zeros;
  29411. // Decimal point?
  29412. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  29413. numStr = numStr.replace(DECIMAL_SEP, '');
  29414. }
  29415. // Exponential form?
  29416. if ((i = numStr.search(/e/i)) > 0) {
  29417. // Work out the exponent.
  29418. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  29419. numberOfIntegerDigits += +numStr.slice(i + 1);
  29420. numStr = numStr.substring(0, i);
  29421. } else if (numberOfIntegerDigits < 0) {
  29422. // There was no decimal point or exponent so it is an integer.
  29423. numberOfIntegerDigits = numStr.length;
  29424. }
  29425. // Count the number of leading zeros.
  29426. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  29427. if (i == (zeros = numStr.length)) {
  29428. // The digits are all zero.
  29429. digits = [0];
  29430. numberOfIntegerDigits = 1;
  29431. } else {
  29432. // Count the number of trailing zeros
  29433. zeros--;
  29434. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  29435. // Trailing zeros are insignificant so ignore them
  29436. numberOfIntegerDigits -= i;
  29437. digits = [];
  29438. // Convert string to array of digits without leading/trailing zeros.
  29439. for (j = 0; i <= zeros; i++, j++) {
  29440. digits[j] = +numStr.charAt(i);
  29441. }
  29442. }
  29443. // If the number overflows the maximum allowed digits then use an exponent.
  29444. if (numberOfIntegerDigits > MAX_DIGITS) {
  29445. digits = digits.splice(0, MAX_DIGITS - 1);
  29446. exponent = numberOfIntegerDigits - 1;
  29447. numberOfIntegerDigits = 1;
  29448. }
  29449. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  29450. }
  29451. /**
  29452. * Round the parsed number to the specified number of decimal places
  29453. * This function changed the parsedNumber in-place
  29454. */
  29455. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  29456. var digits = parsedNumber.d;
  29457. var fractionLen = digits.length - parsedNumber.i;
  29458. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  29459. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  29460. // The index of the digit to where rounding is to occur
  29461. var roundAt = fractionSize + parsedNumber.i;
  29462. var digit = digits[roundAt];
  29463. if (roundAt > 0) {
  29464. // Drop fractional digits beyond `roundAt`
  29465. digits.splice(Math.max(parsedNumber.i, roundAt));
  29466. // Set non-fractional digits beyond `roundAt` to 0
  29467. for (var j = roundAt; j < digits.length; j++) {
  29468. digits[j] = 0;
  29469. }
  29470. } else {
  29471. // We rounded to zero so reset the parsedNumber
  29472. fractionLen = Math.max(0, fractionLen);
  29473. parsedNumber.i = 1;
  29474. digits.length = Math.max(1, roundAt = fractionSize + 1);
  29475. digits[0] = 0;
  29476. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  29477. }
  29478. if (digit >= 5) {
  29479. if (roundAt - 1 < 0) {
  29480. for (var k = 0; k > roundAt; k--) {
  29481. digits.unshift(0);
  29482. parsedNumber.i++;
  29483. }
  29484. digits.unshift(1);
  29485. parsedNumber.i++;
  29486. } else {
  29487. digits[roundAt - 1]++;
  29488. }
  29489. }
  29490. // Pad out with zeros to get the required fraction length
  29491. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  29492. // Do any carrying, e.g. a digit was rounded up to 10
  29493. var carry = digits.reduceRight(function(carry, d, i, digits) {
  29494. d = d + carry;
  29495. digits[i] = d % 10;
  29496. return Math.floor(d / 10);
  29497. }, 0);
  29498. if (carry) {
  29499. digits.unshift(carry);
  29500. parsedNumber.i++;
  29501. }
  29502. }
  29503. /**
  29504. * Format a number into a string
  29505. * @param {number} number The number to format
  29506. * @param {{
  29507. * minFrac, // the minimum number of digits required in the fraction part of the number
  29508. * maxFrac, // the maximum number of digits required in the fraction part of the number
  29509. * gSize, // number of digits in each group of separated digits
  29510. * lgSize, // number of digits in the last group of digits before the decimal separator
  29511. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  29512. * posPre, // the string to go in front of a positive number
  29513. * negSuf, // the string to go after a negative number (e.g. `)`)
  29514. * posSuf // the string to go after a positive number
  29515. * }} pattern
  29516. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  29517. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  29518. * @param {[type]} fractionSize The size of the fractional part of the number
  29519. * @return {string} The number formatted as a string
  29520. */
  29521. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  29522. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  29523. var isInfinity = !isFinite(number);
  29524. var isZero = false;
  29525. var numStr = Math.abs(number) + '',
  29526. formattedText = '',
  29527. parsedNumber;
  29528. if (isInfinity) {
  29529. formattedText = '\u221e';
  29530. } else {
  29531. parsedNumber = parse(numStr);
  29532. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  29533. var digits = parsedNumber.d;
  29534. var integerLen = parsedNumber.i;
  29535. var exponent = parsedNumber.e;
  29536. var decimals = [];
  29537. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  29538. // pad zeros for small numbers
  29539. while (integerLen < 0) {
  29540. digits.unshift(0);
  29541. integerLen++;
  29542. }
  29543. // extract decimals digits
  29544. if (integerLen > 0) {
  29545. decimals = digits.splice(integerLen);
  29546. } else {
  29547. decimals = digits;
  29548. digits = [0];
  29549. }
  29550. // format the integer digits with grouping separators
  29551. var groups = [];
  29552. if (digits.length >= pattern.lgSize) {
  29553. groups.unshift(digits.splice(-pattern.lgSize).join(''));
  29554. }
  29555. while (digits.length > pattern.gSize) {
  29556. groups.unshift(digits.splice(-pattern.gSize).join(''));
  29557. }
  29558. if (digits.length) {
  29559. groups.unshift(digits.join(''));
  29560. }
  29561. formattedText = groups.join(groupSep);
  29562. // append the decimal digits
  29563. if (decimals.length) {
  29564. formattedText += decimalSep + decimals.join('');
  29565. }
  29566. if (exponent) {
  29567. formattedText += 'e+' + exponent;
  29568. }
  29569. }
  29570. if (number < 0 && !isZero) {
  29571. return pattern.negPre + formattedText + pattern.negSuf;
  29572. } else {
  29573. return pattern.posPre + formattedText + pattern.posSuf;
  29574. }
  29575. }
  29576. function padNumber(num, digits, trim, negWrap) {
  29577. var neg = '';
  29578. if (num < 0 || (negWrap && num <= 0)) {
  29579. if (negWrap) {
  29580. num = -num + 1;
  29581. } else {
  29582. num = -num;
  29583. neg = '-';
  29584. }
  29585. }
  29586. num = '' + num;
  29587. while (num.length < digits) num = ZERO_CHAR + num;
  29588. if (trim) {
  29589. num = num.substr(num.length - digits);
  29590. }
  29591. return neg + num;
  29592. }
  29593. function dateGetter(name, size, offset, trim, negWrap) {
  29594. offset = offset || 0;
  29595. return function(date) {
  29596. var value = date['get' + name]();
  29597. if (offset > 0 || value > -offset) {
  29598. value += offset;
  29599. }
  29600. if (value === 0 && offset == -12) value = 12;
  29601. return padNumber(value, size, trim, negWrap);
  29602. };
  29603. }
  29604. function dateStrGetter(name, shortForm, standAlone) {
  29605. return function(date, formats) {
  29606. var value = date['get' + name]();
  29607. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  29608. var get = uppercase(propPrefix + name);
  29609. return formats[get][value];
  29610. };
  29611. }
  29612. function timeZoneGetter(date, formats, offset) {
  29613. var zone = -1 * offset;
  29614. var paddedZone = (zone >= 0) ? "+" : "";
  29615. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  29616. padNumber(Math.abs(zone % 60), 2);
  29617. return paddedZone;
  29618. }
  29619. function getFirstThursdayOfYear(year) {
  29620. // 0 = index of January
  29621. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  29622. // 4 = index of Thursday (+1 to account for 1st = 5)
  29623. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  29624. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  29625. }
  29626. function getThursdayThisWeek(datetime) {
  29627. return new Date(datetime.getFullYear(), datetime.getMonth(),
  29628. // 4 = index of Thursday
  29629. datetime.getDate() + (4 - datetime.getDay()));
  29630. }
  29631. function weekGetter(size) {
  29632. return function(date) {
  29633. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  29634. thisThurs = getThursdayThisWeek(date);
  29635. var diff = +thisThurs - +firstThurs,
  29636. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  29637. return padNumber(result, size);
  29638. };
  29639. }
  29640. function ampmGetter(date, formats) {
  29641. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  29642. }
  29643. function eraGetter(date, formats) {
  29644. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  29645. }
  29646. function longEraGetter(date, formats) {
  29647. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  29648. }
  29649. var DATE_FORMATS = {
  29650. yyyy: dateGetter('FullYear', 4, 0, false, true),
  29651. yy: dateGetter('FullYear', 2, 0, true, true),
  29652. y: dateGetter('FullYear', 1, 0, false, true),
  29653. MMMM: dateStrGetter('Month'),
  29654. MMM: dateStrGetter('Month', true),
  29655. MM: dateGetter('Month', 2, 1),
  29656. M: dateGetter('Month', 1, 1),
  29657. LLLL: dateStrGetter('Month', false, true),
  29658. dd: dateGetter('Date', 2),
  29659. d: dateGetter('Date', 1),
  29660. HH: dateGetter('Hours', 2),
  29661. H: dateGetter('Hours', 1),
  29662. hh: dateGetter('Hours', 2, -12),
  29663. h: dateGetter('Hours', 1, -12),
  29664. mm: dateGetter('Minutes', 2),
  29665. m: dateGetter('Minutes', 1),
  29666. ss: dateGetter('Seconds', 2),
  29667. s: dateGetter('Seconds', 1),
  29668. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  29669. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  29670. sss: dateGetter('Milliseconds', 3),
  29671. EEEE: dateStrGetter('Day'),
  29672. EEE: dateStrGetter('Day', true),
  29673. a: ampmGetter,
  29674. Z: timeZoneGetter,
  29675. ww: weekGetter(2),
  29676. w: weekGetter(1),
  29677. G: eraGetter,
  29678. GG: eraGetter,
  29679. GGG: eraGetter,
  29680. GGGG: longEraGetter
  29681. };
  29682. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  29683. NUMBER_STRING = /^\-?\d+$/;
  29684. /**
  29685. * @ngdoc filter
  29686. * @name date
  29687. * @kind function
  29688. *
  29689. * @description
  29690. * Formats `date` to a string based on the requested `format`.
  29691. *
  29692. * `format` string can be composed of the following elements:
  29693. *
  29694. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  29695. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  29696. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  29697. * * `'MMMM'`: Month in year (January-December)
  29698. * * `'MMM'`: Month in year (Jan-Dec)
  29699. * * `'MM'`: Month in year, padded (01-12)
  29700. * * `'M'`: Month in year (1-12)
  29701. * * `'LLLL'`: Stand-alone month in year (January-December)
  29702. * * `'dd'`: Day in month, padded (01-31)
  29703. * * `'d'`: Day in month (1-31)
  29704. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  29705. * * `'EEE'`: Day in Week, (Sun-Sat)
  29706. * * `'HH'`: Hour in day, padded (00-23)
  29707. * * `'H'`: Hour in day (0-23)
  29708. * * `'hh'`: Hour in AM/PM, padded (01-12)
  29709. * * `'h'`: Hour in AM/PM, (1-12)
  29710. * * `'mm'`: Minute in hour, padded (00-59)
  29711. * * `'m'`: Minute in hour (0-59)
  29712. * * `'ss'`: Second in minute, padded (00-59)
  29713. * * `'s'`: Second in minute (0-59)
  29714. * * `'sss'`: Millisecond in second, padded (000-999)
  29715. * * `'a'`: AM/PM marker
  29716. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  29717. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  29718. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  29719. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  29720. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  29721. *
  29722. * `format` string can also be one of the following predefined
  29723. * {@link guide/i18n localizable formats}:
  29724. *
  29725. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  29726. * (e.g. Sep 3, 2010 12:05:08 PM)
  29727. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  29728. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  29729. * (e.g. Friday, September 3, 2010)
  29730. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  29731. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  29732. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  29733. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  29734. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  29735. *
  29736. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  29737. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  29738. * (e.g. `"h 'o''clock'"`).
  29739. *
  29740. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  29741. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  29742. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  29743. * specified in the string input, the time is considered to be in the local timezone.
  29744. * @param {string=} format Formatting rules (see Description). If not specified,
  29745. * `mediumDate` is used.
  29746. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  29747. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  29748. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  29749. * If not specified, the timezone of the browser will be used.
  29750. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  29751. *
  29752. * @example
  29753. <example>
  29754. <file name="index.html">
  29755. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  29756. <span>{{1288323623006 | date:'medium'}}</span><br>
  29757. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  29758. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  29759. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  29760. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  29761. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  29762. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  29763. </file>
  29764. <file name="protractor.js" type="protractor">
  29765. it('should format date', function() {
  29766. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  29767. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  29768. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  29769. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  29770. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  29771. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  29772. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  29773. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  29774. });
  29775. </file>
  29776. </example>
  29777. */
  29778. dateFilter.$inject = ['$locale'];
  29779. function dateFilter($locale) {
  29780. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  29781. // 1 2 3 4 5 6 7 8 9 10 11
  29782. function jsonStringToDate(string) {
  29783. var match;
  29784. if (match = string.match(R_ISO8601_STR)) {
  29785. var date = new Date(0),
  29786. tzHour = 0,
  29787. tzMin = 0,
  29788. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  29789. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  29790. if (match[9]) {
  29791. tzHour = toInt(match[9] + match[10]);
  29792. tzMin = toInt(match[9] + match[11]);
  29793. }
  29794. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  29795. var h = toInt(match[4] || 0) - tzHour;
  29796. var m = toInt(match[5] || 0) - tzMin;
  29797. var s = toInt(match[6] || 0);
  29798. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  29799. timeSetter.call(date, h, m, s, ms);
  29800. return date;
  29801. }
  29802. return string;
  29803. }
  29804. return function(date, format, timezone) {
  29805. var text = '',
  29806. parts = [],
  29807. fn, match;
  29808. format = format || 'mediumDate';
  29809. format = $locale.DATETIME_FORMATS[format] || format;
  29810. if (isString(date)) {
  29811. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  29812. }
  29813. if (isNumber(date)) {
  29814. date = new Date(date);
  29815. }
  29816. if (!isDate(date) || !isFinite(date.getTime())) {
  29817. return date;
  29818. }
  29819. while (format) {
  29820. match = DATE_FORMATS_SPLIT.exec(format);
  29821. if (match) {
  29822. parts = concat(parts, match, 1);
  29823. format = parts.pop();
  29824. } else {
  29825. parts.push(format);
  29826. format = null;
  29827. }
  29828. }
  29829. var dateTimezoneOffset = date.getTimezoneOffset();
  29830. if (timezone) {
  29831. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  29832. date = convertTimezoneToLocal(date, timezone, true);
  29833. }
  29834. forEach(parts, function(value) {
  29835. fn = DATE_FORMATS[value];
  29836. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  29837. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  29838. });
  29839. return text;
  29840. };
  29841. }
  29842. /**
  29843. * @ngdoc filter
  29844. * @name json
  29845. * @kind function
  29846. *
  29847. * @description
  29848. * Allows you to convert a JavaScript object into JSON string.
  29849. *
  29850. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  29851. * the binding is automatically converted to JSON.
  29852. *
  29853. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  29854. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  29855. * @returns {string} JSON string.
  29856. *
  29857. *
  29858. * @example
  29859. <example>
  29860. <file name="index.html">
  29861. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  29862. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  29863. </file>
  29864. <file name="protractor.js" type="protractor">
  29865. it('should jsonify filtered objects', function() {
  29866. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  29867. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  29868. });
  29869. </file>
  29870. </example>
  29871. *
  29872. */
  29873. function jsonFilter() {
  29874. return function(object, spacing) {
  29875. if (isUndefined(spacing)) {
  29876. spacing = 2;
  29877. }
  29878. return toJson(object, spacing);
  29879. };
  29880. }
  29881. /**
  29882. * @ngdoc filter
  29883. * @name lowercase
  29884. * @kind function
  29885. * @description
  29886. * Converts string to lowercase.
  29887. * @see angular.lowercase
  29888. */
  29889. var lowercaseFilter = valueFn(lowercase);
  29890. /**
  29891. * @ngdoc filter
  29892. * @name uppercase
  29893. * @kind function
  29894. * @description
  29895. * Converts string to uppercase.
  29896. * @see angular.uppercase
  29897. */
  29898. var uppercaseFilter = valueFn(uppercase);
  29899. /**
  29900. * @ngdoc filter
  29901. * @name limitTo
  29902. * @kind function
  29903. *
  29904. * @description
  29905. * Creates a new array or string containing only a specified number of elements. The elements
  29906. * are taken from either the beginning or the end of the source array, string or number, as specified by
  29907. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  29908. * converted to a string.
  29909. *
  29910. * @param {Array|string|number} input Source array, string or number to be limited.
  29911. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  29912. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  29913. * If the number is negative, `limit` number of items from the end of the source array/string
  29914. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  29915. * the input will be returned unchanged.
  29916. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  29917. * indicates an offset from the end of `input`. Defaults to `0`.
  29918. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  29919. * had less than `limit` elements.
  29920. *
  29921. * @example
  29922. <example module="limitToExample">
  29923. <file name="index.html">
  29924. <script>
  29925. angular.module('limitToExample', [])
  29926. .controller('ExampleController', ['$scope', function($scope) {
  29927. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  29928. $scope.letters = "abcdefghi";
  29929. $scope.longNumber = 2345432342;
  29930. $scope.numLimit = 3;
  29931. $scope.letterLimit = 3;
  29932. $scope.longNumberLimit = 3;
  29933. }]);
  29934. </script>
  29935. <div ng-controller="ExampleController">
  29936. <label>
  29937. Limit {{numbers}} to:
  29938. <input type="number" step="1" ng-model="numLimit">
  29939. </label>
  29940. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  29941. <label>
  29942. Limit {{letters}} to:
  29943. <input type="number" step="1" ng-model="letterLimit">
  29944. </label>
  29945. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  29946. <label>
  29947. Limit {{longNumber}} to:
  29948. <input type="number" step="1" ng-model="longNumberLimit">
  29949. </label>
  29950. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  29951. </div>
  29952. </file>
  29953. <file name="protractor.js" type="protractor">
  29954. var numLimitInput = element(by.model('numLimit'));
  29955. var letterLimitInput = element(by.model('letterLimit'));
  29956. var longNumberLimitInput = element(by.model('longNumberLimit'));
  29957. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  29958. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  29959. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  29960. it('should limit the number array to first three items', function() {
  29961. expect(numLimitInput.getAttribute('value')).toBe('3');
  29962. expect(letterLimitInput.getAttribute('value')).toBe('3');
  29963. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  29964. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  29965. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  29966. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  29967. });
  29968. // There is a bug in safari and protractor that doesn't like the minus key
  29969. // it('should update the output when -3 is entered', function() {
  29970. // numLimitInput.clear();
  29971. // numLimitInput.sendKeys('-3');
  29972. // letterLimitInput.clear();
  29973. // letterLimitInput.sendKeys('-3');
  29974. // longNumberLimitInput.clear();
  29975. // longNumberLimitInput.sendKeys('-3');
  29976. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  29977. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  29978. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  29979. // });
  29980. it('should not exceed the maximum size of input array', function() {
  29981. numLimitInput.clear();
  29982. numLimitInput.sendKeys('100');
  29983. letterLimitInput.clear();
  29984. letterLimitInput.sendKeys('100');
  29985. longNumberLimitInput.clear();
  29986. longNumberLimitInput.sendKeys('100');
  29987. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  29988. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  29989. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  29990. });
  29991. </file>
  29992. </example>
  29993. */
  29994. function limitToFilter() {
  29995. return function(input, limit, begin) {
  29996. if (Math.abs(Number(limit)) === Infinity) {
  29997. limit = Number(limit);
  29998. } else {
  29999. limit = toInt(limit);
  30000. }
  30001. if (isNaN(limit)) return input;
  30002. if (isNumber(input)) input = input.toString();
  30003. if (!isArray(input) && !isString(input)) return input;
  30004. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  30005. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  30006. if (limit >= 0) {
  30007. return input.slice(begin, begin + limit);
  30008. } else {
  30009. if (begin === 0) {
  30010. return input.slice(limit, input.length);
  30011. } else {
  30012. return input.slice(Math.max(0, begin + limit), begin);
  30013. }
  30014. }
  30015. };
  30016. }
  30017. /**
  30018. * @ngdoc filter
  30019. * @name orderBy
  30020. * @kind function
  30021. *
  30022. * @description
  30023. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  30024. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  30025. * as expected, make sure they are actually being saved as numbers and not strings.
  30026. * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
  30027. *
  30028. * @param {Array} array The array (or array-like object) to sort.
  30029. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  30030. * used by the comparator to determine the order of elements.
  30031. *
  30032. * Can be one of:
  30033. *
  30034. * - `function`: Getter function. The result of this function will be sorted using the
  30035. * `<`, `===`, `>` operator.
  30036. * - `string`: An Angular expression. The result of this expression is used to compare elements
  30037. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  30038. * 3 first characters of a property called `name`). The result of a constant expression
  30039. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  30040. * to sort object by the value of their `special name` property). An expression can be
  30041. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  30042. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  30043. * element itself is used to compare where sorting.
  30044. * - `Array`: An array of function or string predicates. The first predicate in the array
  30045. * is used for sorting, but when two items are equivalent, the next predicate is used.
  30046. *
  30047. * If the predicate is missing or empty then it defaults to `'+'`.
  30048. *
  30049. * @param {boolean=} reverse Reverse the order of the array.
  30050. * @returns {Array} Sorted copy of the source array.
  30051. *
  30052. *
  30053. * @example
  30054. * The example below demonstrates a simple ngRepeat, where the data is sorted
  30055. * by age in descending order (predicate is set to `'-age'`).
  30056. * `reverse` is not set, which means it defaults to `false`.
  30057. <example module="orderByExample">
  30058. <file name="index.html">
  30059. <div ng-controller="ExampleController">
  30060. <table class="friend">
  30061. <tr>
  30062. <th>Name</th>
  30063. <th>Phone Number</th>
  30064. <th>Age</th>
  30065. </tr>
  30066. <tr ng-repeat="friend in friends | orderBy:'-age'">
  30067. <td>{{friend.name}}</td>
  30068. <td>{{friend.phone}}</td>
  30069. <td>{{friend.age}}</td>
  30070. </tr>
  30071. </table>
  30072. </div>
  30073. </file>
  30074. <file name="script.js">
  30075. angular.module('orderByExample', [])
  30076. .controller('ExampleController', ['$scope', function($scope) {
  30077. $scope.friends =
  30078. [{name:'John', phone:'555-1212', age:10},
  30079. {name:'Mary', phone:'555-9876', age:19},
  30080. {name:'Mike', phone:'555-4321', age:21},
  30081. {name:'Adam', phone:'555-5678', age:35},
  30082. {name:'Julie', phone:'555-8765', age:29}];
  30083. }]);
  30084. </file>
  30085. </example>
  30086. *
  30087. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  30088. * as shown in the next example.
  30089. * @example
  30090. <example module="orderByExample">
  30091. <file name="index.html">
  30092. <div ng-controller="ExampleController">
  30093. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  30094. <hr/>
  30095. <button ng-click="predicate=''">Set to unsorted</button>
  30096. <table class="friend">
  30097. <tr>
  30098. <th>
  30099. <button ng-click="order('name')">Name</button>
  30100. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  30101. </th>
  30102. <th>
  30103. <button ng-click="order('phone')">Phone Number</button>
  30104. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  30105. </th>
  30106. <th>
  30107. <button ng-click="order('age')">Age</button>
  30108. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  30109. </th>
  30110. </tr>
  30111. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  30112. <td>{{friend.name}}</td>
  30113. <td>{{friend.phone}}</td>
  30114. <td>{{friend.age}}</td>
  30115. </tr>
  30116. </table>
  30117. </div>
  30118. </file>
  30119. <file name="script.js">
  30120. angular.module('orderByExample', [])
  30121. .controller('ExampleController', ['$scope', function($scope) {
  30122. $scope.friends =
  30123. [{name:'John', phone:'555-1212', age:10},
  30124. {name:'Mary', phone:'555-9876', age:19},
  30125. {name:'Mike', phone:'555-4321', age:21},
  30126. {name:'Adam', phone:'555-5678', age:35},
  30127. {name:'Julie', phone:'555-8765', age:29}];
  30128. $scope.predicate = 'age';
  30129. $scope.reverse = true;
  30130. $scope.order = function(predicate) {
  30131. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  30132. $scope.predicate = predicate;
  30133. };
  30134. }]);
  30135. </file>
  30136. <file name="style.css">
  30137. .sortorder:after {
  30138. content: '\25b2';
  30139. }
  30140. .sortorder.reverse:after {
  30141. content: '\25bc';
  30142. }
  30143. </file>
  30144. </example>
  30145. *
  30146. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  30147. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  30148. * desired parameters.
  30149. *
  30150. * Example:
  30151. *
  30152. * @example
  30153. <example module="orderByExample">
  30154. <file name="index.html">
  30155. <div ng-controller="ExampleController">
  30156. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  30157. <table class="friend">
  30158. <tr>
  30159. <th>
  30160. <button ng-click="order('name')">Name</button>
  30161. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  30162. </th>
  30163. <th>
  30164. <button ng-click="order('phone')">Phone Number</button>
  30165. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  30166. </th>
  30167. <th>
  30168. <button ng-click="order('age')">Age</button>
  30169. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  30170. </th>
  30171. </tr>
  30172. <tr ng-repeat="friend in friends">
  30173. <td>{{friend.name}}</td>
  30174. <td>{{friend.phone}}</td>
  30175. <td>{{friend.age}}</td>
  30176. </tr>
  30177. </table>
  30178. </div>
  30179. </file>
  30180. <file name="script.js">
  30181. angular.module('orderByExample', [])
  30182. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  30183. var orderBy = $filter('orderBy');
  30184. $scope.friends = [
  30185. { name: 'John', phone: '555-1212', age: 10 },
  30186. { name: 'Mary', phone: '555-9876', age: 19 },
  30187. { name: 'Mike', phone: '555-4321', age: 21 },
  30188. { name: 'Adam', phone: '555-5678', age: 35 },
  30189. { name: 'Julie', phone: '555-8765', age: 29 }
  30190. ];
  30191. $scope.order = function(predicate) {
  30192. $scope.predicate = predicate;
  30193. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  30194. $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
  30195. };
  30196. $scope.order('age', true);
  30197. }]);
  30198. </file>
  30199. <file name="style.css">
  30200. .sortorder:after {
  30201. content: '\25b2';
  30202. }
  30203. .sortorder.reverse:after {
  30204. content: '\25bc';
  30205. }
  30206. </file>
  30207. </example>
  30208. */
  30209. orderByFilter.$inject = ['$parse'];
  30210. function orderByFilter($parse) {
  30211. return function(array, sortPredicate, reverseOrder) {
  30212. if (array == null) return array;
  30213. if (!isArrayLike(array)) {
  30214. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  30215. }
  30216. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  30217. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  30218. var predicates = processPredicates(sortPredicate, reverseOrder);
  30219. // Add a predicate at the end that evaluates to the element index. This makes the
  30220. // sort stable as it works as a tie-breaker when all the input predicates cannot
  30221. // distinguish between two elements.
  30222. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  30223. // The next three lines are a version of a Swartzian Transform idiom from Perl
  30224. // (sometimes called the Decorate-Sort-Undecorate idiom)
  30225. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  30226. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  30227. compareValues.sort(doComparison);
  30228. array = compareValues.map(function(item) { return item.value; });
  30229. return array;
  30230. function getComparisonObject(value, index) {
  30231. return {
  30232. value: value,
  30233. predicateValues: predicates.map(function(predicate) {
  30234. return getPredicateValue(predicate.get(value), index);
  30235. })
  30236. };
  30237. }
  30238. function doComparison(v1, v2) {
  30239. var result = 0;
  30240. for (var index=0, length = predicates.length; index < length; ++index) {
  30241. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  30242. if (result) break;
  30243. }
  30244. return result;
  30245. }
  30246. };
  30247. function processPredicates(sortPredicate, reverseOrder) {
  30248. reverseOrder = reverseOrder ? -1 : 1;
  30249. return sortPredicate.map(function(predicate) {
  30250. var descending = 1, get = identity;
  30251. if (isFunction(predicate)) {
  30252. get = predicate;
  30253. } else if (isString(predicate)) {
  30254. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  30255. descending = predicate.charAt(0) == '-' ? -1 : 1;
  30256. predicate = predicate.substring(1);
  30257. }
  30258. if (predicate !== '') {
  30259. get = $parse(predicate);
  30260. if (get.constant) {
  30261. var key = get();
  30262. get = function(value) { return value[key]; };
  30263. }
  30264. }
  30265. }
  30266. return { get: get, descending: descending * reverseOrder };
  30267. });
  30268. }
  30269. function isPrimitive(value) {
  30270. switch (typeof value) {
  30271. case 'number': /* falls through */
  30272. case 'boolean': /* falls through */
  30273. case 'string':
  30274. return true;
  30275. default:
  30276. return false;
  30277. }
  30278. }
  30279. function objectValue(value, index) {
  30280. // If `valueOf` is a valid function use that
  30281. if (typeof value.valueOf === 'function') {
  30282. value = value.valueOf();
  30283. if (isPrimitive(value)) return value;
  30284. }
  30285. // If `toString` is a valid function and not the one from `Object.prototype` use that
  30286. if (hasCustomToString(value)) {
  30287. value = value.toString();
  30288. if (isPrimitive(value)) return value;
  30289. }
  30290. // We have a basic object so we use the position of the object in the collection
  30291. return index;
  30292. }
  30293. function getPredicateValue(value, index) {
  30294. var type = typeof value;
  30295. if (value === null) {
  30296. type = 'string';
  30297. value = 'null';
  30298. } else if (type === 'string') {
  30299. value = value.toLowerCase();
  30300. } else if (type === 'object') {
  30301. value = objectValue(value, index);
  30302. }
  30303. return { value: value, type: type };
  30304. }
  30305. function compare(v1, v2) {
  30306. var result = 0;
  30307. if (v1.type === v2.type) {
  30308. if (v1.value !== v2.value) {
  30309. result = v1.value < v2.value ? -1 : 1;
  30310. }
  30311. } else {
  30312. result = v1.type < v2.type ? -1 : 1;
  30313. }
  30314. return result;
  30315. }
  30316. }
  30317. function ngDirective(directive) {
  30318. if (isFunction(directive)) {
  30319. directive = {
  30320. link: directive
  30321. };
  30322. }
  30323. directive.restrict = directive.restrict || 'AC';
  30324. return valueFn(directive);
  30325. }
  30326. /**
  30327. * @ngdoc directive
  30328. * @name a
  30329. * @restrict E
  30330. *
  30331. * @description
  30332. * Modifies the default behavior of the html A tag so that the default action is prevented when
  30333. * the href attribute is empty.
  30334. *
  30335. * This change permits the easy creation of action links with the `ngClick` directive
  30336. * without changing the location or causing page reloads, e.g.:
  30337. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  30338. */
  30339. var htmlAnchorDirective = valueFn({
  30340. restrict: 'E',
  30341. compile: function(element, attr) {
  30342. if (!attr.href && !attr.xlinkHref) {
  30343. return function(scope, element) {
  30344. // If the linked element is not an anchor tag anymore, do nothing
  30345. if (element[0].nodeName.toLowerCase() !== 'a') return;
  30346. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  30347. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  30348. 'xlink:href' : 'href';
  30349. element.on('click', function(event) {
  30350. // if we have no href url, then don't navigate anywhere.
  30351. if (!element.attr(href)) {
  30352. event.preventDefault();
  30353. }
  30354. });
  30355. };
  30356. }
  30357. }
  30358. });
  30359. /**
  30360. * @ngdoc directive
  30361. * @name ngHref
  30362. * @restrict A
  30363. * @priority 99
  30364. *
  30365. * @description
  30366. * Using Angular markup like `{{hash}}` in an href attribute will
  30367. * make the link go to the wrong URL if the user clicks it before
  30368. * Angular has a chance to replace the `{{hash}}` markup with its
  30369. * value. Until Angular replaces the markup the link will be broken
  30370. * and will most likely return a 404 error. The `ngHref` directive
  30371. * solves this problem.
  30372. *
  30373. * The wrong way to write it:
  30374. * ```html
  30375. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  30376. * ```
  30377. *
  30378. * The correct way to write it:
  30379. * ```html
  30380. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  30381. * ```
  30382. *
  30383. * @element A
  30384. * @param {template} ngHref any string which can contain `{{}}` markup.
  30385. *
  30386. * @example
  30387. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  30388. * in links and their different behaviors:
  30389. <example>
  30390. <file name="index.html">
  30391. <input ng-model="value" /><br />
  30392. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  30393. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  30394. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  30395. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  30396. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  30397. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  30398. </file>
  30399. <file name="protractor.js" type="protractor">
  30400. it('should execute ng-click but not reload when href without value', function() {
  30401. element(by.id('link-1')).click();
  30402. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  30403. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  30404. });
  30405. it('should execute ng-click but not reload when href empty string', function() {
  30406. element(by.id('link-2')).click();
  30407. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  30408. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  30409. });
  30410. it('should execute ng-click and change url when ng-href specified', function() {
  30411. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  30412. element(by.id('link-3')).click();
  30413. // At this point, we navigate away from an Angular page, so we need
  30414. // to use browser.driver to get the base webdriver.
  30415. browser.wait(function() {
  30416. return browser.driver.getCurrentUrl().then(function(url) {
  30417. return url.match(/\/123$/);
  30418. });
  30419. }, 5000, 'page should navigate to /123');
  30420. });
  30421. it('should execute ng-click but not reload when href empty string and name specified', function() {
  30422. element(by.id('link-4')).click();
  30423. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  30424. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  30425. });
  30426. it('should execute ng-click but not reload when no href but name specified', function() {
  30427. element(by.id('link-5')).click();
  30428. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  30429. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  30430. });
  30431. it('should only change url when only ng-href', function() {
  30432. element(by.model('value')).clear();
  30433. element(by.model('value')).sendKeys('6');
  30434. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  30435. element(by.id('link-6')).click();
  30436. // At this point, we navigate away from an Angular page, so we need
  30437. // to use browser.driver to get the base webdriver.
  30438. browser.wait(function() {
  30439. return browser.driver.getCurrentUrl().then(function(url) {
  30440. return url.match(/\/6$/);
  30441. });
  30442. }, 5000, 'page should navigate to /6');
  30443. });
  30444. </file>
  30445. </example>
  30446. */
  30447. /**
  30448. * @ngdoc directive
  30449. * @name ngSrc
  30450. * @restrict A
  30451. * @priority 99
  30452. *
  30453. * @description
  30454. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  30455. * work right: The browser will fetch from the URL with the literal
  30456. * text `{{hash}}` until Angular replaces the expression inside
  30457. * `{{hash}}`. The `ngSrc` directive solves this problem.
  30458. *
  30459. * The buggy way to write it:
  30460. * ```html
  30461. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  30462. * ```
  30463. *
  30464. * The correct way to write it:
  30465. * ```html
  30466. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  30467. * ```
  30468. *
  30469. * @element IMG
  30470. * @param {template} ngSrc any string which can contain `{{}}` markup.
  30471. */
  30472. /**
  30473. * @ngdoc directive
  30474. * @name ngSrcset
  30475. * @restrict A
  30476. * @priority 99
  30477. *
  30478. * @description
  30479. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  30480. * work right: The browser will fetch from the URL with the literal
  30481. * text `{{hash}}` until Angular replaces the expression inside
  30482. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  30483. *
  30484. * The buggy way to write it:
  30485. * ```html
  30486. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  30487. * ```
  30488. *
  30489. * The correct way to write it:
  30490. * ```html
  30491. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  30492. * ```
  30493. *
  30494. * @element IMG
  30495. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  30496. */
  30497. /**
  30498. * @ngdoc directive
  30499. * @name ngDisabled
  30500. * @restrict A
  30501. * @priority 100
  30502. *
  30503. * @description
  30504. *
  30505. * This directive sets the `disabled` attribute on the element if the
  30506. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  30507. *
  30508. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  30509. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30510. *
  30511. * @example
  30512. <example>
  30513. <file name="index.html">
  30514. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  30515. <button ng-model="button" ng-disabled="checked">Button</button>
  30516. </file>
  30517. <file name="protractor.js" type="protractor">
  30518. it('should toggle button', function() {
  30519. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  30520. element(by.model('checked')).click();
  30521. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  30522. });
  30523. </file>
  30524. </example>
  30525. *
  30526. * @element INPUT
  30527. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  30528. * then the `disabled` attribute will be set on the element
  30529. */
  30530. /**
  30531. * @ngdoc directive
  30532. * @name ngChecked
  30533. * @restrict A
  30534. * @priority 100
  30535. *
  30536. * @description
  30537. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  30538. *
  30539. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  30540. * as this can lead to unexpected behavior.
  30541. *
  30542. * A special directive is necessary because we cannot use interpolation inside the `checked`
  30543. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30544. *
  30545. * @example
  30546. <example>
  30547. <file name="index.html">
  30548. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  30549. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  30550. </file>
  30551. <file name="protractor.js" type="protractor">
  30552. it('should check both checkBoxes', function() {
  30553. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  30554. element(by.model('master')).click();
  30555. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  30556. });
  30557. </file>
  30558. </example>
  30559. *
  30560. * @element INPUT
  30561. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  30562. * then the `checked` attribute will be set on the element
  30563. */
  30564. /**
  30565. * @ngdoc directive
  30566. * @name ngReadonly
  30567. * @restrict A
  30568. * @priority 100
  30569. *
  30570. * @description
  30571. *
  30572. * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  30573. *
  30574. * A special directive is necessary because we cannot use interpolation inside the `readOnly`
  30575. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30576. *
  30577. * @example
  30578. <example>
  30579. <file name="index.html">
  30580. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  30581. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  30582. </file>
  30583. <file name="protractor.js" type="protractor">
  30584. it('should toggle readonly attr', function() {
  30585. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  30586. element(by.model('checked')).click();
  30587. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  30588. });
  30589. </file>
  30590. </example>
  30591. *
  30592. * @element INPUT
  30593. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  30594. * then special attribute "readonly" will be set on the element
  30595. */
  30596. /**
  30597. * @ngdoc directive
  30598. * @name ngSelected
  30599. * @restrict A
  30600. * @priority 100
  30601. *
  30602. * @description
  30603. *
  30604. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  30605. *
  30606. * A special directive is necessary because we cannot use interpolation inside the `selected`
  30607. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30608. *
  30609. * @example
  30610. <example>
  30611. <file name="index.html">
  30612. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  30613. <select aria-label="ngSelected demo">
  30614. <option>Hello!</option>
  30615. <option id="greet" ng-selected="selected">Greetings!</option>
  30616. </select>
  30617. </file>
  30618. <file name="protractor.js" type="protractor">
  30619. it('should select Greetings!', function() {
  30620. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  30621. element(by.model('selected')).click();
  30622. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  30623. });
  30624. </file>
  30625. </example>
  30626. *
  30627. * @element OPTION
  30628. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  30629. * then special attribute "selected" will be set on the element
  30630. */
  30631. /**
  30632. * @ngdoc directive
  30633. * @name ngOpen
  30634. * @restrict A
  30635. * @priority 100
  30636. *
  30637. * @description
  30638. *
  30639. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  30640. *
  30641. * A special directive is necessary because we cannot use interpolation inside the `open`
  30642. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30643. *
  30644. * @example
  30645. <example>
  30646. <file name="index.html">
  30647. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  30648. <details id="details" ng-open="open">
  30649. <summary>Show/Hide me</summary>
  30650. </details>
  30651. </file>
  30652. <file name="protractor.js" type="protractor">
  30653. it('should toggle open', function() {
  30654. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  30655. element(by.model('open')).click();
  30656. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  30657. });
  30658. </file>
  30659. </example>
  30660. *
  30661. * @element DETAILS
  30662. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  30663. * then special attribute "open" will be set on the element
  30664. */
  30665. var ngAttributeAliasDirectives = {};
  30666. // boolean attrs are evaluated
  30667. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  30668. // binding to multiple is not supported
  30669. if (propName == "multiple") return;
  30670. function defaultLinkFn(scope, element, attr) {
  30671. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  30672. attr.$set(attrName, !!value);
  30673. });
  30674. }
  30675. var normalized = directiveNormalize('ng-' + attrName);
  30676. var linkFn = defaultLinkFn;
  30677. if (propName === 'checked') {
  30678. linkFn = function(scope, element, attr) {
  30679. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  30680. if (attr.ngModel !== attr[normalized]) {
  30681. defaultLinkFn(scope, element, attr);
  30682. }
  30683. };
  30684. }
  30685. ngAttributeAliasDirectives[normalized] = function() {
  30686. return {
  30687. restrict: 'A',
  30688. priority: 100,
  30689. link: linkFn
  30690. };
  30691. };
  30692. });
  30693. // aliased input attrs are evaluated
  30694. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  30695. ngAttributeAliasDirectives[ngAttr] = function() {
  30696. return {
  30697. priority: 100,
  30698. link: function(scope, element, attr) {
  30699. //special case ngPattern when a literal regular expression value
  30700. //is used as the expression (this way we don't have to watch anything).
  30701. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  30702. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  30703. if (match) {
  30704. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  30705. return;
  30706. }
  30707. }
  30708. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  30709. attr.$set(ngAttr, value);
  30710. });
  30711. }
  30712. };
  30713. };
  30714. });
  30715. // ng-src, ng-srcset, ng-href are interpolated
  30716. forEach(['src', 'srcset', 'href'], function(attrName) {
  30717. var normalized = directiveNormalize('ng-' + attrName);
  30718. ngAttributeAliasDirectives[normalized] = function() {
  30719. return {
  30720. priority: 99, // it needs to run after the attributes are interpolated
  30721. link: function(scope, element, attr) {
  30722. var propName = attrName,
  30723. name = attrName;
  30724. if (attrName === 'href' &&
  30725. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  30726. name = 'xlinkHref';
  30727. attr.$attr[name] = 'xlink:href';
  30728. propName = null;
  30729. }
  30730. attr.$observe(normalized, function(value) {
  30731. if (!value) {
  30732. if (attrName === 'href') {
  30733. attr.$set(name, null);
  30734. }
  30735. return;
  30736. }
  30737. attr.$set(name, value);
  30738. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  30739. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  30740. // to set the property as well to achieve the desired effect.
  30741. // we use attr[attrName] value since $set can sanitize the url.
  30742. if (msie && propName) element.prop(propName, attr[name]);
  30743. });
  30744. }
  30745. };
  30746. };
  30747. });
  30748. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  30749. */
  30750. var nullFormCtrl = {
  30751. $addControl: noop,
  30752. $$renameControl: nullFormRenameControl,
  30753. $removeControl: noop,
  30754. $setValidity: noop,
  30755. $setDirty: noop,
  30756. $setPristine: noop,
  30757. $setSubmitted: noop
  30758. },
  30759. SUBMITTED_CLASS = 'ng-submitted';
  30760. function nullFormRenameControl(control, name) {
  30761. control.$name = name;
  30762. }
  30763. /**
  30764. * @ngdoc type
  30765. * @name form.FormController
  30766. *
  30767. * @property {boolean} $pristine True if user has not interacted with the form yet.
  30768. * @property {boolean} $dirty True if user has already interacted with the form.
  30769. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  30770. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  30771. * @property {boolean} $pending True if at least one containing control or form is pending.
  30772. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  30773. *
  30774. * @property {Object} $error Is an object hash, containing references to controls or
  30775. * forms with failing validators, where:
  30776. *
  30777. * - keys are validation tokens (error names),
  30778. * - values are arrays of controls or forms that have a failing validator for given error name.
  30779. *
  30780. * Built-in validation tokens:
  30781. *
  30782. * - `email`
  30783. * - `max`
  30784. * - `maxlength`
  30785. * - `min`
  30786. * - `minlength`
  30787. * - `number`
  30788. * - `pattern`
  30789. * - `required`
  30790. * - `url`
  30791. * - `date`
  30792. * - `datetimelocal`
  30793. * - `time`
  30794. * - `week`
  30795. * - `month`
  30796. *
  30797. * @description
  30798. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  30799. * such as being valid/invalid or dirty/pristine.
  30800. *
  30801. * Each {@link ng.directive:form form} directive creates an instance
  30802. * of `FormController`.
  30803. *
  30804. */
  30805. //asks for $scope to fool the BC controller module
  30806. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  30807. function FormController(element, attrs, $scope, $animate, $interpolate) {
  30808. var form = this,
  30809. controls = [];
  30810. // init state
  30811. form.$error = {};
  30812. form.$$success = {};
  30813. form.$pending = undefined;
  30814. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  30815. form.$dirty = false;
  30816. form.$pristine = true;
  30817. form.$valid = true;
  30818. form.$invalid = false;
  30819. form.$submitted = false;
  30820. form.$$parentForm = nullFormCtrl;
  30821. /**
  30822. * @ngdoc method
  30823. * @name form.FormController#$rollbackViewValue
  30824. *
  30825. * @description
  30826. * Rollback all form controls pending updates to the `$modelValue`.
  30827. *
  30828. * Updates may be pending by a debounced event or because the input is waiting for a some future
  30829. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  30830. * a form that uses `ng-model-options` to pend updates.
  30831. */
  30832. form.$rollbackViewValue = function() {
  30833. forEach(controls, function(control) {
  30834. control.$rollbackViewValue();
  30835. });
  30836. };
  30837. /**
  30838. * @ngdoc method
  30839. * @name form.FormController#$commitViewValue
  30840. *
  30841. * @description
  30842. * Commit all form controls pending updates to the `$modelValue`.
  30843. *
  30844. * Updates may be pending by a debounced event or because the input is waiting for a some future
  30845. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  30846. * usually handles calling this in response to input events.
  30847. */
  30848. form.$commitViewValue = function() {
  30849. forEach(controls, function(control) {
  30850. control.$commitViewValue();
  30851. });
  30852. };
  30853. /**
  30854. * @ngdoc method
  30855. * @name form.FormController#$addControl
  30856. * @param {object} control control object, either a {@link form.FormController} or an
  30857. * {@link ngModel.NgModelController}
  30858. *
  30859. * @description
  30860. * Register a control with the form. Input elements using ngModelController do this automatically
  30861. * when they are linked.
  30862. *
  30863. * Note that the current state of the control will not be reflected on the new parent form. This
  30864. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  30865. * state.
  30866. *
  30867. * However, if the method is used programmatically, for example by adding dynamically created controls,
  30868. * or controls that have been previously removed without destroying their corresponding DOM element,
  30869. * it's the developers responsibility to make sure the current state propagates to the parent form.
  30870. *
  30871. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  30872. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  30873. */
  30874. form.$addControl = function(control) {
  30875. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  30876. // and not added to the scope. Now we throw an error.
  30877. assertNotHasOwnProperty(control.$name, 'input');
  30878. controls.push(control);
  30879. if (control.$name) {
  30880. form[control.$name] = control;
  30881. }
  30882. control.$$parentForm = form;
  30883. };
  30884. // Private API: rename a form control
  30885. form.$$renameControl = function(control, newName) {
  30886. var oldName = control.$name;
  30887. if (form[oldName] === control) {
  30888. delete form[oldName];
  30889. }
  30890. form[newName] = control;
  30891. control.$name = newName;
  30892. };
  30893. /**
  30894. * @ngdoc method
  30895. * @name form.FormController#$removeControl
  30896. * @param {object} control control object, either a {@link form.FormController} or an
  30897. * {@link ngModel.NgModelController}
  30898. *
  30899. * @description
  30900. * Deregister a control from the form.
  30901. *
  30902. * Input elements using ngModelController do this automatically when they are destroyed.
  30903. *
  30904. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  30905. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  30906. * different from case to case. For example, removing the only `$dirty` control from a form may or
  30907. * may not mean that the form is still `$dirty`.
  30908. */
  30909. form.$removeControl = function(control) {
  30910. if (control.$name && form[control.$name] === control) {
  30911. delete form[control.$name];
  30912. }
  30913. forEach(form.$pending, function(value, name) {
  30914. form.$setValidity(name, null, control);
  30915. });
  30916. forEach(form.$error, function(value, name) {
  30917. form.$setValidity(name, null, control);
  30918. });
  30919. forEach(form.$$success, function(value, name) {
  30920. form.$setValidity(name, null, control);
  30921. });
  30922. arrayRemove(controls, control);
  30923. control.$$parentForm = nullFormCtrl;
  30924. };
  30925. /**
  30926. * @ngdoc method
  30927. * @name form.FormController#$setValidity
  30928. *
  30929. * @description
  30930. * Sets the validity of a form control.
  30931. *
  30932. * This method will also propagate to parent forms.
  30933. */
  30934. addSetValidityMethod({
  30935. ctrl: this,
  30936. $element: element,
  30937. set: function(object, property, controller) {
  30938. var list = object[property];
  30939. if (!list) {
  30940. object[property] = [controller];
  30941. } else {
  30942. var index = list.indexOf(controller);
  30943. if (index === -1) {
  30944. list.push(controller);
  30945. }
  30946. }
  30947. },
  30948. unset: function(object, property, controller) {
  30949. var list = object[property];
  30950. if (!list) {
  30951. return;
  30952. }
  30953. arrayRemove(list, controller);
  30954. if (list.length === 0) {
  30955. delete object[property];
  30956. }
  30957. },
  30958. $animate: $animate
  30959. });
  30960. /**
  30961. * @ngdoc method
  30962. * @name form.FormController#$setDirty
  30963. *
  30964. * @description
  30965. * Sets the form to a dirty state.
  30966. *
  30967. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  30968. * state (ng-dirty class). This method will also propagate to parent forms.
  30969. */
  30970. form.$setDirty = function() {
  30971. $animate.removeClass(element, PRISTINE_CLASS);
  30972. $animate.addClass(element, DIRTY_CLASS);
  30973. form.$dirty = true;
  30974. form.$pristine = false;
  30975. form.$$parentForm.$setDirty();
  30976. };
  30977. /**
  30978. * @ngdoc method
  30979. * @name form.FormController#$setPristine
  30980. *
  30981. * @description
  30982. * Sets the form to its pristine state.
  30983. *
  30984. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  30985. * state (ng-pristine class). This method will also propagate to all the controls contained
  30986. * in this form.
  30987. *
  30988. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  30989. * saving or resetting it.
  30990. */
  30991. form.$setPristine = function() {
  30992. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  30993. form.$dirty = false;
  30994. form.$pristine = true;
  30995. form.$submitted = false;
  30996. forEach(controls, function(control) {
  30997. control.$setPristine();
  30998. });
  30999. };
  31000. /**
  31001. * @ngdoc method
  31002. * @name form.FormController#$setUntouched
  31003. *
  31004. * @description
  31005. * Sets the form to its untouched state.
  31006. *
  31007. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  31008. * untouched state (ng-untouched class).
  31009. *
  31010. * Setting a form controls back to their untouched state is often useful when setting the form
  31011. * back to its pristine state.
  31012. */
  31013. form.$setUntouched = function() {
  31014. forEach(controls, function(control) {
  31015. control.$setUntouched();
  31016. });
  31017. };
  31018. /**
  31019. * @ngdoc method
  31020. * @name form.FormController#$setSubmitted
  31021. *
  31022. * @description
  31023. * Sets the form to its submitted state.
  31024. */
  31025. form.$setSubmitted = function() {
  31026. $animate.addClass(element, SUBMITTED_CLASS);
  31027. form.$submitted = true;
  31028. form.$$parentForm.$setSubmitted();
  31029. };
  31030. }
  31031. /**
  31032. * @ngdoc directive
  31033. * @name ngForm
  31034. * @restrict EAC
  31035. *
  31036. * @description
  31037. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  31038. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  31039. * sub-group of controls needs to be determined.
  31040. *
  31041. * Note: the purpose of `ngForm` is to group controls,
  31042. * but not to be a replacement for the `<form>` tag with all of its capabilities
  31043. * (e.g. posting to the server, ...).
  31044. *
  31045. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  31046. * related scope, under this name.
  31047. *
  31048. */
  31049. /**
  31050. * @ngdoc directive
  31051. * @name form
  31052. * @restrict E
  31053. *
  31054. * @description
  31055. * Directive that instantiates
  31056. * {@link form.FormController FormController}.
  31057. *
  31058. * If the `name` attribute is specified, the form controller is published onto the current scope under
  31059. * this name.
  31060. *
  31061. * # Alias: {@link ng.directive:ngForm `ngForm`}
  31062. *
  31063. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  31064. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  31065. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  31066. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  31067. * of controls needs to be determined.
  31068. *
  31069. * # CSS classes
  31070. * - `ng-valid` is set if the form is valid.
  31071. * - `ng-invalid` is set if the form is invalid.
  31072. * - `ng-pending` is set if the form is pending.
  31073. * - `ng-pristine` is set if the form is pristine.
  31074. * - `ng-dirty` is set if the form is dirty.
  31075. * - `ng-submitted` is set if the form was submitted.
  31076. *
  31077. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  31078. *
  31079. *
  31080. * # Submitting a form and preventing the default action
  31081. *
  31082. * Since the role of forms in client-side Angular applications is different than in classical
  31083. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  31084. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  31085. * to handle the form submission in an application-specific way.
  31086. *
  31087. * For this reason, Angular prevents the default action (form submission to the server) unless the
  31088. * `<form>` element has an `action` attribute specified.
  31089. *
  31090. * You can use one of the following two ways to specify what javascript method should be called when
  31091. * a form is submitted:
  31092. *
  31093. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  31094. * - {@link ng.directive:ngClick ngClick} directive on the first
  31095. * button or input field of type submit (input[type=submit])
  31096. *
  31097. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  31098. * or {@link ng.directive:ngClick ngClick} directives.
  31099. * This is because of the following form submission rules in the HTML specification:
  31100. *
  31101. * - If a form has only one input field then hitting enter in this field triggers form submit
  31102. * (`ngSubmit`)
  31103. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  31104. * doesn't trigger submit
  31105. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  31106. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  31107. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  31108. *
  31109. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  31110. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  31111. * to have access to the updated model.
  31112. *
  31113. * ## Animation Hooks
  31114. *
  31115. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  31116. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  31117. * other validations that are performed within the form. Animations in ngForm are similar to how
  31118. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  31119. * as JS animations.
  31120. *
  31121. * The following example shows a simple way to utilize CSS transitions to style a form element
  31122. * that has been rendered as invalid after it has been validated:
  31123. *
  31124. * <pre>
  31125. * //be sure to include ngAnimate as a module to hook into more
  31126. * //advanced animations
  31127. * .my-form {
  31128. * transition:0.5s linear all;
  31129. * background: white;
  31130. * }
  31131. * .my-form.ng-invalid {
  31132. * background: red;
  31133. * color:white;
  31134. * }
  31135. * </pre>
  31136. *
  31137. * @example
  31138. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  31139. <file name="index.html">
  31140. <script>
  31141. angular.module('formExample', [])
  31142. .controller('FormController', ['$scope', function($scope) {
  31143. $scope.userType = 'guest';
  31144. }]);
  31145. </script>
  31146. <style>
  31147. .my-form {
  31148. transition:all linear 0.5s;
  31149. background: transparent;
  31150. }
  31151. .my-form.ng-invalid {
  31152. background: red;
  31153. }
  31154. </style>
  31155. <form name="myForm" ng-controller="FormController" class="my-form">
  31156. userType: <input name="input" ng-model="userType" required>
  31157. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  31158. <code>userType = {{userType}}</code><br>
  31159. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  31160. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  31161. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  31162. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  31163. </form>
  31164. </file>
  31165. <file name="protractor.js" type="protractor">
  31166. it('should initialize to model', function() {
  31167. var userType = element(by.binding('userType'));
  31168. var valid = element(by.binding('myForm.input.$valid'));
  31169. expect(userType.getText()).toContain('guest');
  31170. expect(valid.getText()).toContain('true');
  31171. });
  31172. it('should be invalid if empty', function() {
  31173. var userType = element(by.binding('userType'));
  31174. var valid = element(by.binding('myForm.input.$valid'));
  31175. var userInput = element(by.model('userType'));
  31176. userInput.clear();
  31177. userInput.sendKeys('');
  31178. expect(userType.getText()).toEqual('userType =');
  31179. expect(valid.getText()).toContain('false');
  31180. });
  31181. </file>
  31182. </example>
  31183. *
  31184. * @param {string=} name Name of the form. If specified, the form controller will be published into
  31185. * related scope, under this name.
  31186. */
  31187. var formDirectiveFactory = function(isNgForm) {
  31188. return ['$timeout', '$parse', function($timeout, $parse) {
  31189. var formDirective = {
  31190. name: 'form',
  31191. restrict: isNgForm ? 'EAC' : 'E',
  31192. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  31193. controller: FormController,
  31194. compile: function ngFormCompile(formElement, attr) {
  31195. // Setup initial state of the control
  31196. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  31197. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  31198. return {
  31199. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  31200. var controller = ctrls[0];
  31201. // if `action` attr is not present on the form, prevent the default action (submission)
  31202. if (!('action' in attr)) {
  31203. // we can't use jq events because if a form is destroyed during submission the default
  31204. // action is not prevented. see #1238
  31205. //
  31206. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  31207. // page reload if the form was destroyed by submission of the form via a click handler
  31208. // on a button in the form. Looks like an IE9 specific bug.
  31209. var handleFormSubmission = function(event) {
  31210. scope.$apply(function() {
  31211. controller.$commitViewValue();
  31212. controller.$setSubmitted();
  31213. });
  31214. event.preventDefault();
  31215. };
  31216. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  31217. // unregister the preventDefault listener so that we don't not leak memory but in a
  31218. // way that will achieve the prevention of the default action.
  31219. formElement.on('$destroy', function() {
  31220. $timeout(function() {
  31221. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  31222. }, 0, false);
  31223. });
  31224. }
  31225. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  31226. parentFormCtrl.$addControl(controller);
  31227. var setter = nameAttr ? getSetter(controller.$name) : noop;
  31228. if (nameAttr) {
  31229. setter(scope, controller);
  31230. attr.$observe(nameAttr, function(newValue) {
  31231. if (controller.$name === newValue) return;
  31232. setter(scope, undefined);
  31233. controller.$$parentForm.$$renameControl(controller, newValue);
  31234. setter = getSetter(controller.$name);
  31235. setter(scope, controller);
  31236. });
  31237. }
  31238. formElement.on('$destroy', function() {
  31239. controller.$$parentForm.$removeControl(controller);
  31240. setter(scope, undefined);
  31241. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  31242. });
  31243. }
  31244. };
  31245. }
  31246. };
  31247. return formDirective;
  31248. function getSetter(expression) {
  31249. if (expression === '') {
  31250. //create an assignable expression, so forms with an empty name can be renamed later
  31251. return $parse('this[""]').assign;
  31252. }
  31253. return $parse(expression).assign || noop;
  31254. }
  31255. }];
  31256. };
  31257. var formDirective = formDirectiveFactory();
  31258. var ngFormDirective = formDirectiveFactory(true);
  31259. /* global VALID_CLASS: false,
  31260. INVALID_CLASS: false,
  31261. PRISTINE_CLASS: false,
  31262. DIRTY_CLASS: false,
  31263. UNTOUCHED_CLASS: false,
  31264. TOUCHED_CLASS: false,
  31265. ngModelMinErr: false,
  31266. */
  31267. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  31268. 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)$/;
  31269. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  31270. // Note: We are being more lenient, because browsers are too.
  31271. // 1. Scheme
  31272. // 2. Slashes
  31273. // 3. Username
  31274. // 4. Password
  31275. // 5. Hostname
  31276. // 6. Port
  31277. // 7. Path
  31278. // 8. Query
  31279. // 9. Fragment
  31280. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  31281. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  31282. 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;
  31283. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  31284. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  31285. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  31286. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  31287. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  31288. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  31289. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  31290. var PARTIAL_VALIDATION_TYPES = createMap();
  31291. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  31292. PARTIAL_VALIDATION_TYPES[type] = true;
  31293. });
  31294. var inputType = {
  31295. /**
  31296. * @ngdoc input
  31297. * @name input[text]
  31298. *
  31299. * @description
  31300. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  31301. *
  31302. *
  31303. * @param {string} ngModel Assignable angular expression to data-bind to.
  31304. * @param {string=} name Property name of the form under which the control is published.
  31305. * @param {string=} required Adds `required` validation error key if the value is not entered.
  31306. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31307. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31308. * `required` when you want to data-bind to the `required` attribute.
  31309. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  31310. * minlength.
  31311. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  31312. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  31313. * any length.
  31314. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  31315. * that contains the regular expression body that will be converted to a regular expression
  31316. * as in the ngPattern directive.
  31317. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  31318. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  31319. * If the expression evaluates to a RegExp object, then this is used directly.
  31320. * If the expression evaluates to a string, then it will be converted to a RegExp
  31321. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  31322. * `new RegExp('^abc$')`.<br />
  31323. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  31324. * start at the index of the last search's match, thus not taking the whole input value into
  31325. * account.
  31326. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31327. * interaction with the input element.
  31328. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  31329. * This parameter is ignored for input[type=password] controls, which will never trim the
  31330. * input.
  31331. *
  31332. * @example
  31333. <example name="text-input-directive" module="textInputExample">
  31334. <file name="index.html">
  31335. <script>
  31336. angular.module('textInputExample', [])
  31337. .controller('ExampleController', ['$scope', function($scope) {
  31338. $scope.example = {
  31339. text: 'guest',
  31340. word: /^\s*\w*\s*$/
  31341. };
  31342. }]);
  31343. </script>
  31344. <form name="myForm" ng-controller="ExampleController">
  31345. <label>Single word:
  31346. <input type="text" name="input" ng-model="example.text"
  31347. ng-pattern="example.word" required ng-trim="false">
  31348. </label>
  31349. <div role="alert">
  31350. <span class="error" ng-show="myForm.input.$error.required">
  31351. Required!</span>
  31352. <span class="error" ng-show="myForm.input.$error.pattern">
  31353. Single word only!</span>
  31354. </div>
  31355. <tt>text = {{example.text}}</tt><br/>
  31356. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31357. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31358. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31359. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31360. </form>
  31361. </file>
  31362. <file name="protractor.js" type="protractor">
  31363. var text = element(by.binding('example.text'));
  31364. var valid = element(by.binding('myForm.input.$valid'));
  31365. var input = element(by.model('example.text'));
  31366. it('should initialize to model', function() {
  31367. expect(text.getText()).toContain('guest');
  31368. expect(valid.getText()).toContain('true');
  31369. });
  31370. it('should be invalid if empty', function() {
  31371. input.clear();
  31372. input.sendKeys('');
  31373. expect(text.getText()).toEqual('text =');
  31374. expect(valid.getText()).toContain('false');
  31375. });
  31376. it('should be invalid if multi word', function() {
  31377. input.clear();
  31378. input.sendKeys('hello world');
  31379. expect(valid.getText()).toContain('false');
  31380. });
  31381. </file>
  31382. </example>
  31383. */
  31384. 'text': textInputType,
  31385. /**
  31386. * @ngdoc input
  31387. * @name input[date]
  31388. *
  31389. * @description
  31390. * Input with date validation and transformation. In browsers that do not yet support
  31391. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  31392. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  31393. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  31394. * expected input format via a placeholder or label.
  31395. *
  31396. * The model must always be a Date object, otherwise Angular will throw an error.
  31397. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31398. *
  31399. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31400. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31401. *
  31402. * @param {string} ngModel Assignable angular expression to data-bind to.
  31403. * @param {string=} name Property name of the form under which the control is published.
  31404. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  31405. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  31406. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  31407. * constraint validation.
  31408. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  31409. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  31410. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  31411. * constraint validation.
  31412. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  31413. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31414. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  31415. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31416. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31417. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31418. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31419. * `required` when you want to data-bind to the `required` attribute.
  31420. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31421. * interaction with the input element.
  31422. *
  31423. * @example
  31424. <example name="date-input-directive" module="dateInputExample">
  31425. <file name="index.html">
  31426. <script>
  31427. angular.module('dateInputExample', [])
  31428. .controller('DateController', ['$scope', function($scope) {
  31429. $scope.example = {
  31430. value: new Date(2013, 9, 22)
  31431. };
  31432. }]);
  31433. </script>
  31434. <form name="myForm" ng-controller="DateController as dateCtrl">
  31435. <label for="exampleInput">Pick a date in 2013:</label>
  31436. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  31437. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  31438. <div role="alert">
  31439. <span class="error" ng-show="myForm.input.$error.required">
  31440. Required!</span>
  31441. <span class="error" ng-show="myForm.input.$error.date">
  31442. Not a valid date!</span>
  31443. </div>
  31444. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  31445. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31446. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31447. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31448. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31449. </form>
  31450. </file>
  31451. <file name="protractor.js" type="protractor">
  31452. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  31453. var valid = element(by.binding('myForm.input.$valid'));
  31454. var input = element(by.model('example.value'));
  31455. // currently protractor/webdriver does not support
  31456. // sending keys to all known HTML5 input controls
  31457. // for various browsers (see https://github.com/angular/protractor/issues/562).
  31458. function setInput(val) {
  31459. // set the value of the element and force validation.
  31460. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31461. "ipt.value = '" + val + "';" +
  31462. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31463. browser.executeScript(scr);
  31464. }
  31465. it('should initialize to model', function() {
  31466. expect(value.getText()).toContain('2013-10-22');
  31467. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31468. });
  31469. it('should be invalid if empty', function() {
  31470. setInput('');
  31471. expect(value.getText()).toEqual('value =');
  31472. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31473. });
  31474. it('should be invalid if over max', function() {
  31475. setInput('2015-01-01');
  31476. expect(value.getText()).toContain('');
  31477. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31478. });
  31479. </file>
  31480. </example>
  31481. */
  31482. 'date': createDateInputType('date', DATE_REGEXP,
  31483. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  31484. 'yyyy-MM-dd'),
  31485. /**
  31486. * @ngdoc input
  31487. * @name input[datetime-local]
  31488. *
  31489. * @description
  31490. * Input with datetime validation and transformation. In browsers that do not yet support
  31491. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31492. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  31493. *
  31494. * The model must always be a Date object, otherwise Angular will throw an error.
  31495. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31496. *
  31497. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31498. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31499. *
  31500. * @param {string} ngModel Assignable angular expression to data-bind to.
  31501. * @param {string=} name Property name of the form under which the control is published.
  31502. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31503. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  31504. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  31505. * Note that `min` will also add native HTML5 constraint validation.
  31506. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31507. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  31508. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  31509. * Note that `max` will also add native HTML5 constraint validation.
  31510. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  31511. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31512. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  31513. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31514. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31515. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31516. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31517. * `required` when you want to data-bind to the `required` attribute.
  31518. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31519. * interaction with the input element.
  31520. *
  31521. * @example
  31522. <example name="datetimelocal-input-directive" module="dateExample">
  31523. <file name="index.html">
  31524. <script>
  31525. angular.module('dateExample', [])
  31526. .controller('DateController', ['$scope', function($scope) {
  31527. $scope.example = {
  31528. value: new Date(2010, 11, 28, 14, 57)
  31529. };
  31530. }]);
  31531. </script>
  31532. <form name="myForm" ng-controller="DateController as dateCtrl">
  31533. <label for="exampleInput">Pick a date between in 2013:</label>
  31534. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  31535. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  31536. <div role="alert">
  31537. <span class="error" ng-show="myForm.input.$error.required">
  31538. Required!</span>
  31539. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  31540. Not a valid date!</span>
  31541. </div>
  31542. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  31543. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31544. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31545. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31546. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31547. </form>
  31548. </file>
  31549. <file name="protractor.js" type="protractor">
  31550. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  31551. var valid = element(by.binding('myForm.input.$valid'));
  31552. var input = element(by.model('example.value'));
  31553. // currently protractor/webdriver does not support
  31554. // sending keys to all known HTML5 input controls
  31555. // for various browsers (https://github.com/angular/protractor/issues/562).
  31556. function setInput(val) {
  31557. // set the value of the element and force validation.
  31558. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31559. "ipt.value = '" + val + "';" +
  31560. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31561. browser.executeScript(scr);
  31562. }
  31563. it('should initialize to model', function() {
  31564. expect(value.getText()).toContain('2010-12-28T14:57:00');
  31565. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31566. });
  31567. it('should be invalid if empty', function() {
  31568. setInput('');
  31569. expect(value.getText()).toEqual('value =');
  31570. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31571. });
  31572. it('should be invalid if over max', function() {
  31573. setInput('2015-01-01T23:59:00');
  31574. expect(value.getText()).toContain('');
  31575. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31576. });
  31577. </file>
  31578. </example>
  31579. */
  31580. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  31581. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  31582. 'yyyy-MM-ddTHH:mm:ss.sss'),
  31583. /**
  31584. * @ngdoc input
  31585. * @name input[time]
  31586. *
  31587. * @description
  31588. * Input with time validation and transformation. In browsers that do not yet support
  31589. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31590. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  31591. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  31592. *
  31593. * The model must always be a Date object, otherwise Angular will throw an error.
  31594. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31595. *
  31596. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31597. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31598. *
  31599. * @param {string} ngModel Assignable angular expression to data-bind to.
  31600. * @param {string=} name Property name of the form under which the control is published.
  31601. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31602. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  31603. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  31604. * native HTML5 constraint validation.
  31605. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31606. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  31607. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  31608. * native HTML5 constraint validation.
  31609. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  31610. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31611. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  31612. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31613. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31614. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31615. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31616. * `required` when you want to data-bind to the `required` attribute.
  31617. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31618. * interaction with the input element.
  31619. *
  31620. * @example
  31621. <example name="time-input-directive" module="timeExample">
  31622. <file name="index.html">
  31623. <script>
  31624. angular.module('timeExample', [])
  31625. .controller('DateController', ['$scope', function($scope) {
  31626. $scope.example = {
  31627. value: new Date(1970, 0, 1, 14, 57, 0)
  31628. };
  31629. }]);
  31630. </script>
  31631. <form name="myForm" ng-controller="DateController as dateCtrl">
  31632. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  31633. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  31634. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  31635. <div role="alert">
  31636. <span class="error" ng-show="myForm.input.$error.required">
  31637. Required!</span>
  31638. <span class="error" ng-show="myForm.input.$error.time">
  31639. Not a valid date!</span>
  31640. </div>
  31641. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  31642. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31643. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31644. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31645. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31646. </form>
  31647. </file>
  31648. <file name="protractor.js" type="protractor">
  31649. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  31650. var valid = element(by.binding('myForm.input.$valid'));
  31651. var input = element(by.model('example.value'));
  31652. // currently protractor/webdriver does not support
  31653. // sending keys to all known HTML5 input controls
  31654. // for various browsers (https://github.com/angular/protractor/issues/562).
  31655. function setInput(val) {
  31656. // set the value of the element and force validation.
  31657. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31658. "ipt.value = '" + val + "';" +
  31659. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31660. browser.executeScript(scr);
  31661. }
  31662. it('should initialize to model', function() {
  31663. expect(value.getText()).toContain('14:57:00');
  31664. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31665. });
  31666. it('should be invalid if empty', function() {
  31667. setInput('');
  31668. expect(value.getText()).toEqual('value =');
  31669. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31670. });
  31671. it('should be invalid if over max', function() {
  31672. setInput('23:59:00');
  31673. expect(value.getText()).toContain('');
  31674. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31675. });
  31676. </file>
  31677. </example>
  31678. */
  31679. 'time': createDateInputType('time', TIME_REGEXP,
  31680. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  31681. 'HH:mm:ss.sss'),
  31682. /**
  31683. * @ngdoc input
  31684. * @name input[week]
  31685. *
  31686. * @description
  31687. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  31688. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31689. * week format (yyyy-W##), for example: `2013-W02`.
  31690. *
  31691. * The model must always be a Date object, otherwise Angular will throw an error.
  31692. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31693. *
  31694. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31695. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31696. *
  31697. * @param {string} ngModel Assignable angular expression to data-bind to.
  31698. * @param {string=} name Property name of the form under which the control is published.
  31699. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31700. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  31701. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  31702. * native HTML5 constraint validation.
  31703. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31704. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  31705. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  31706. * native HTML5 constraint validation.
  31707. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  31708. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31709. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  31710. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31711. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31712. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31713. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31714. * `required` when you want to data-bind to the `required` attribute.
  31715. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31716. * interaction with the input element.
  31717. *
  31718. * @example
  31719. <example name="week-input-directive" module="weekExample">
  31720. <file name="index.html">
  31721. <script>
  31722. angular.module('weekExample', [])
  31723. .controller('DateController', ['$scope', function($scope) {
  31724. $scope.example = {
  31725. value: new Date(2013, 0, 3)
  31726. };
  31727. }]);
  31728. </script>
  31729. <form name="myForm" ng-controller="DateController as dateCtrl">
  31730. <label>Pick a date between in 2013:
  31731. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  31732. placeholder="YYYY-W##" min="2012-W32"
  31733. max="2013-W52" required />
  31734. </label>
  31735. <div role="alert">
  31736. <span class="error" ng-show="myForm.input.$error.required">
  31737. Required!</span>
  31738. <span class="error" ng-show="myForm.input.$error.week">
  31739. Not a valid date!</span>
  31740. </div>
  31741. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  31742. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31743. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31744. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31745. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31746. </form>
  31747. </file>
  31748. <file name="protractor.js" type="protractor">
  31749. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  31750. var valid = element(by.binding('myForm.input.$valid'));
  31751. var input = element(by.model('example.value'));
  31752. // currently protractor/webdriver does not support
  31753. // sending keys to all known HTML5 input controls
  31754. // for various browsers (https://github.com/angular/protractor/issues/562).
  31755. function setInput(val) {
  31756. // set the value of the element and force validation.
  31757. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31758. "ipt.value = '" + val + "';" +
  31759. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31760. browser.executeScript(scr);
  31761. }
  31762. it('should initialize to model', function() {
  31763. expect(value.getText()).toContain('2013-W01');
  31764. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31765. });
  31766. it('should be invalid if empty', function() {
  31767. setInput('');
  31768. expect(value.getText()).toEqual('value =');
  31769. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31770. });
  31771. it('should be invalid if over max', function() {
  31772. setInput('2015-W01');
  31773. expect(value.getText()).toContain('');
  31774. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31775. });
  31776. </file>
  31777. </example>
  31778. */
  31779. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  31780. /**
  31781. * @ngdoc input
  31782. * @name input[month]
  31783. *
  31784. * @description
  31785. * Input with month validation and transformation. In browsers that do not yet support
  31786. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31787. * month format (yyyy-MM), for example: `2009-01`.
  31788. *
  31789. * The model must always be a Date object, otherwise Angular will throw an error.
  31790. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31791. * If the model is not set to the first of the month, the next view to model update will set it
  31792. * to the first of the month.
  31793. *
  31794. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31795. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31796. *
  31797. * @param {string} ngModel Assignable angular expression to data-bind to.
  31798. * @param {string=} name Property name of the form under which the control is published.
  31799. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31800. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  31801. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  31802. * native HTML5 constraint validation.
  31803. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31804. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  31805. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  31806. * native HTML5 constraint validation.
  31807. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  31808. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31809. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  31810. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31811. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31812. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31813. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31814. * `required` when you want to data-bind to the `required` attribute.
  31815. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31816. * interaction with the input element.
  31817. *
  31818. * @example
  31819. <example name="month-input-directive" module="monthExample">
  31820. <file name="index.html">
  31821. <script>
  31822. angular.module('monthExample', [])
  31823. .controller('DateController', ['$scope', function($scope) {
  31824. $scope.example = {
  31825. value: new Date(2013, 9, 1)
  31826. };
  31827. }]);
  31828. </script>
  31829. <form name="myForm" ng-controller="DateController as dateCtrl">
  31830. <label for="exampleInput">Pick a month in 2013:</label>
  31831. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  31832. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  31833. <div role="alert">
  31834. <span class="error" ng-show="myForm.input.$error.required">
  31835. Required!</span>
  31836. <span class="error" ng-show="myForm.input.$error.month">
  31837. Not a valid month!</span>
  31838. </div>
  31839. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  31840. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31841. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31842. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31843. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31844. </form>
  31845. </file>
  31846. <file name="protractor.js" type="protractor">
  31847. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  31848. var valid = element(by.binding('myForm.input.$valid'));
  31849. var input = element(by.model('example.value'));
  31850. // currently protractor/webdriver does not support
  31851. // sending keys to all known HTML5 input controls
  31852. // for various browsers (https://github.com/angular/protractor/issues/562).
  31853. function setInput(val) {
  31854. // set the value of the element and force validation.
  31855. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31856. "ipt.value = '" + val + "';" +
  31857. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31858. browser.executeScript(scr);
  31859. }
  31860. it('should initialize to model', function() {
  31861. expect(value.getText()).toContain('2013-10');
  31862. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31863. });
  31864. it('should be invalid if empty', function() {
  31865. setInput('');
  31866. expect(value.getText()).toEqual('value =');
  31867. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31868. });
  31869. it('should be invalid if over max', function() {
  31870. setInput('2015-01');
  31871. expect(value.getText()).toContain('');
  31872. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31873. });
  31874. </file>
  31875. </example>
  31876. */
  31877. 'month': createDateInputType('month', MONTH_REGEXP,
  31878. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  31879. 'yyyy-MM'),
  31880. /**
  31881. * @ngdoc input
  31882. * @name input[number]
  31883. *
  31884. * @description
  31885. * Text input with number validation and transformation. Sets the `number` validation
  31886. * error if not a valid number.
  31887. *
  31888. * <div class="alert alert-warning">
  31889. * The model must always be of type `number` otherwise Angular will throw an error.
  31890. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  31891. * error docs for more information and an example of how to convert your model if necessary.
  31892. * </div>
  31893. *
  31894. * ## Issues with HTML5 constraint validation
  31895. *
  31896. * In browsers that follow the
  31897. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  31898. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  31899. * If a non-number is entered in the input, the browser will report the value as an empty string,
  31900. * which means the view / model values in `ngModel` and subsequently the scope value
  31901. * will also be an empty string.
  31902. *
  31903. *
  31904. * @param {string} ngModel Assignable angular expression to data-bind to.
  31905. * @param {string=} name Property name of the form under which the control is published.
  31906. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31907. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31908. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31909. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31910. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31911. * `required` when you want to data-bind to the `required` attribute.
  31912. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  31913. * minlength.
  31914. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  31915. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  31916. * any length.
  31917. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  31918. * that contains the regular expression body that will be converted to a regular expression
  31919. * as in the ngPattern directive.
  31920. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  31921. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  31922. * If the expression evaluates to a RegExp object, then this is used directly.
  31923. * If the expression evaluates to a string, then it will be converted to a RegExp
  31924. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  31925. * `new RegExp('^abc$')`.<br />
  31926. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  31927. * start at the index of the last search's match, thus not taking the whole input value into
  31928. * account.
  31929. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31930. * interaction with the input element.
  31931. *
  31932. * @example
  31933. <example name="number-input-directive" module="numberExample">
  31934. <file name="index.html">
  31935. <script>
  31936. angular.module('numberExample', [])
  31937. .controller('ExampleController', ['$scope', function($scope) {
  31938. $scope.example = {
  31939. value: 12
  31940. };
  31941. }]);
  31942. </script>
  31943. <form name="myForm" ng-controller="ExampleController">
  31944. <label>Number:
  31945. <input type="number" name="input" ng-model="example.value"
  31946. min="0" max="99" required>
  31947. </label>
  31948. <div role="alert">
  31949. <span class="error" ng-show="myForm.input.$error.required">
  31950. Required!</span>
  31951. <span class="error" ng-show="myForm.input.$error.number">
  31952. Not valid number!</span>
  31953. </div>
  31954. <tt>value = {{example.value}}</tt><br/>
  31955. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31956. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31957. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31958. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31959. </form>
  31960. </file>
  31961. <file name="protractor.js" type="protractor">
  31962. var value = element(by.binding('example.value'));
  31963. var valid = element(by.binding('myForm.input.$valid'));
  31964. var input = element(by.model('example.value'));
  31965. it('should initialize to model', function() {
  31966. expect(value.getText()).toContain('12');
  31967. expect(valid.getText()).toContain('true');
  31968. });
  31969. it('should be invalid if empty', function() {
  31970. input.clear();
  31971. input.sendKeys('');
  31972. expect(value.getText()).toEqual('value =');
  31973. expect(valid.getText()).toContain('false');
  31974. });
  31975. it('should be invalid if over max', function() {
  31976. input.clear();
  31977. input.sendKeys('123');
  31978. expect(value.getText()).toEqual('value =');
  31979. expect(valid.getText()).toContain('false');
  31980. });
  31981. </file>
  31982. </example>
  31983. */
  31984. 'number': numberInputType,
  31985. /**
  31986. * @ngdoc input
  31987. * @name input[url]
  31988. *
  31989. * @description
  31990. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  31991. * valid URL.
  31992. *
  31993. * <div class="alert alert-warning">
  31994. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  31995. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  31996. * the built-in validators (see the {@link guide/forms Forms guide})
  31997. * </div>
  31998. *
  31999. * @param {string} ngModel Assignable angular expression to data-bind to.
  32000. * @param {string=} name Property name of the form under which the control is published.
  32001. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32002. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32003. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32004. * `required` when you want to data-bind to the `required` attribute.
  32005. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32006. * minlength.
  32007. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32008. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  32009. * any length.
  32010. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  32011. * that contains the regular expression body that will be converted to a regular expression
  32012. * as in the ngPattern directive.
  32013. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32014. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32015. * If the expression evaluates to a RegExp object, then this is used directly.
  32016. * If the expression evaluates to a string, then it will be converted to a RegExp
  32017. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32018. * `new RegExp('^abc$')`.<br />
  32019. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32020. * start at the index of the last search's match, thus not taking the whole input value into
  32021. * account.
  32022. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32023. * interaction with the input element.
  32024. *
  32025. * @example
  32026. <example name="url-input-directive" module="urlExample">
  32027. <file name="index.html">
  32028. <script>
  32029. angular.module('urlExample', [])
  32030. .controller('ExampleController', ['$scope', function($scope) {
  32031. $scope.url = {
  32032. text: 'http://google.com'
  32033. };
  32034. }]);
  32035. </script>
  32036. <form name="myForm" ng-controller="ExampleController">
  32037. <label>URL:
  32038. <input type="url" name="input" ng-model="url.text" required>
  32039. <label>
  32040. <div role="alert">
  32041. <span class="error" ng-show="myForm.input.$error.required">
  32042. Required!</span>
  32043. <span class="error" ng-show="myForm.input.$error.url">
  32044. Not valid url!</span>
  32045. </div>
  32046. <tt>text = {{url.text}}</tt><br/>
  32047. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  32048. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  32049. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32050. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32051. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  32052. </form>
  32053. </file>
  32054. <file name="protractor.js" type="protractor">
  32055. var text = element(by.binding('url.text'));
  32056. var valid = element(by.binding('myForm.input.$valid'));
  32057. var input = element(by.model('url.text'));
  32058. it('should initialize to model', function() {
  32059. expect(text.getText()).toContain('http://google.com');
  32060. expect(valid.getText()).toContain('true');
  32061. });
  32062. it('should be invalid if empty', function() {
  32063. input.clear();
  32064. input.sendKeys('');
  32065. expect(text.getText()).toEqual('text =');
  32066. expect(valid.getText()).toContain('false');
  32067. });
  32068. it('should be invalid if not url', function() {
  32069. input.clear();
  32070. input.sendKeys('box');
  32071. expect(valid.getText()).toContain('false');
  32072. });
  32073. </file>
  32074. </example>
  32075. */
  32076. 'url': urlInputType,
  32077. /**
  32078. * @ngdoc input
  32079. * @name input[email]
  32080. *
  32081. * @description
  32082. * Text input with email validation. Sets the `email` validation error key if not a valid email
  32083. * address.
  32084. *
  32085. * <div class="alert alert-warning">
  32086. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  32087. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  32088. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  32089. * </div>
  32090. *
  32091. * @param {string} ngModel Assignable angular expression to data-bind to.
  32092. * @param {string=} name Property name of the form under which the control is published.
  32093. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32094. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32095. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32096. * `required` when you want to data-bind to the `required` attribute.
  32097. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32098. * minlength.
  32099. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32100. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  32101. * any length.
  32102. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  32103. * that contains the regular expression body that will be converted to a regular expression
  32104. * as in the ngPattern directive.
  32105. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32106. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32107. * If the expression evaluates to a RegExp object, then this is used directly.
  32108. * If the expression evaluates to a string, then it will be converted to a RegExp
  32109. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32110. * `new RegExp('^abc$')`.<br />
  32111. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32112. * start at the index of the last search's match, thus not taking the whole input value into
  32113. * account.
  32114. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32115. * interaction with the input element.
  32116. *
  32117. * @example
  32118. <example name="email-input-directive" module="emailExample">
  32119. <file name="index.html">
  32120. <script>
  32121. angular.module('emailExample', [])
  32122. .controller('ExampleController', ['$scope', function($scope) {
  32123. $scope.email = {
  32124. text: 'me@example.com'
  32125. };
  32126. }]);
  32127. </script>
  32128. <form name="myForm" ng-controller="ExampleController">
  32129. <label>Email:
  32130. <input type="email" name="input" ng-model="email.text" required>
  32131. </label>
  32132. <div role="alert">
  32133. <span class="error" ng-show="myForm.input.$error.required">
  32134. Required!</span>
  32135. <span class="error" ng-show="myForm.input.$error.email">
  32136. Not valid email!</span>
  32137. </div>
  32138. <tt>text = {{email.text}}</tt><br/>
  32139. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  32140. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  32141. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32142. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32143. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  32144. </form>
  32145. </file>
  32146. <file name="protractor.js" type="protractor">
  32147. var text = element(by.binding('email.text'));
  32148. var valid = element(by.binding('myForm.input.$valid'));
  32149. var input = element(by.model('email.text'));
  32150. it('should initialize to model', function() {
  32151. expect(text.getText()).toContain('me@example.com');
  32152. expect(valid.getText()).toContain('true');
  32153. });
  32154. it('should be invalid if empty', function() {
  32155. input.clear();
  32156. input.sendKeys('');
  32157. expect(text.getText()).toEqual('text =');
  32158. expect(valid.getText()).toContain('false');
  32159. });
  32160. it('should be invalid if not email', function() {
  32161. input.clear();
  32162. input.sendKeys('xxx');
  32163. expect(valid.getText()).toContain('false');
  32164. });
  32165. </file>
  32166. </example>
  32167. */
  32168. 'email': emailInputType,
  32169. /**
  32170. * @ngdoc input
  32171. * @name input[radio]
  32172. *
  32173. * @description
  32174. * HTML radio button.
  32175. *
  32176. * @param {string} ngModel Assignable angular expression to data-bind to.
  32177. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  32178. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  32179. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  32180. * @param {string=} name Property name of the form under which the control is published.
  32181. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32182. * interaction with the input element.
  32183. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  32184. * is selected. Should be used instead of the `value` attribute if you need
  32185. * a non-string `ngModel` (`boolean`, `array`, ...).
  32186. *
  32187. * @example
  32188. <example name="radio-input-directive" module="radioExample">
  32189. <file name="index.html">
  32190. <script>
  32191. angular.module('radioExample', [])
  32192. .controller('ExampleController', ['$scope', function($scope) {
  32193. $scope.color = {
  32194. name: 'blue'
  32195. };
  32196. $scope.specialValue = {
  32197. "id": "12345",
  32198. "value": "green"
  32199. };
  32200. }]);
  32201. </script>
  32202. <form name="myForm" ng-controller="ExampleController">
  32203. <label>
  32204. <input type="radio" ng-model="color.name" value="red">
  32205. Red
  32206. </label><br/>
  32207. <label>
  32208. <input type="radio" ng-model="color.name" ng-value="specialValue">
  32209. Green
  32210. </label><br/>
  32211. <label>
  32212. <input type="radio" ng-model="color.name" value="blue">
  32213. Blue
  32214. </label><br/>
  32215. <tt>color = {{color.name | json}}</tt><br/>
  32216. </form>
  32217. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  32218. </file>
  32219. <file name="protractor.js" type="protractor">
  32220. it('should change state', function() {
  32221. var color = element(by.binding('color.name'));
  32222. expect(color.getText()).toContain('blue');
  32223. element.all(by.model('color.name')).get(0).click();
  32224. expect(color.getText()).toContain('red');
  32225. });
  32226. </file>
  32227. </example>
  32228. */
  32229. 'radio': radioInputType,
  32230. /**
  32231. * @ngdoc input
  32232. * @name input[checkbox]
  32233. *
  32234. * @description
  32235. * HTML checkbox.
  32236. *
  32237. * @param {string} ngModel Assignable angular expression to data-bind to.
  32238. * @param {string=} name Property name of the form under which the control is published.
  32239. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  32240. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  32241. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32242. * interaction with the input element.
  32243. *
  32244. * @example
  32245. <example name="checkbox-input-directive" module="checkboxExample">
  32246. <file name="index.html">
  32247. <script>
  32248. angular.module('checkboxExample', [])
  32249. .controller('ExampleController', ['$scope', function($scope) {
  32250. $scope.checkboxModel = {
  32251. value1 : true,
  32252. value2 : 'YES'
  32253. };
  32254. }]);
  32255. </script>
  32256. <form name="myForm" ng-controller="ExampleController">
  32257. <label>Value1:
  32258. <input type="checkbox" ng-model="checkboxModel.value1">
  32259. </label><br/>
  32260. <label>Value2:
  32261. <input type="checkbox" ng-model="checkboxModel.value2"
  32262. ng-true-value="'YES'" ng-false-value="'NO'">
  32263. </label><br/>
  32264. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  32265. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  32266. </form>
  32267. </file>
  32268. <file name="protractor.js" type="protractor">
  32269. it('should change state', function() {
  32270. var value1 = element(by.binding('checkboxModel.value1'));
  32271. var value2 = element(by.binding('checkboxModel.value2'));
  32272. expect(value1.getText()).toContain('true');
  32273. expect(value2.getText()).toContain('YES');
  32274. element(by.model('checkboxModel.value1')).click();
  32275. element(by.model('checkboxModel.value2')).click();
  32276. expect(value1.getText()).toContain('false');
  32277. expect(value2.getText()).toContain('NO');
  32278. });
  32279. </file>
  32280. </example>
  32281. */
  32282. 'checkbox': checkboxInputType,
  32283. 'hidden': noop,
  32284. 'button': noop,
  32285. 'submit': noop,
  32286. 'reset': noop,
  32287. 'file': noop
  32288. };
  32289. function stringBasedInputType(ctrl) {
  32290. ctrl.$formatters.push(function(value) {
  32291. return ctrl.$isEmpty(value) ? value : value.toString();
  32292. });
  32293. }
  32294. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32295. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32296. stringBasedInputType(ctrl);
  32297. }
  32298. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32299. var type = lowercase(element[0].type);
  32300. // In composition mode, users are still inputing intermediate text buffer,
  32301. // hold the listener until composition is done.
  32302. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  32303. if (!$sniffer.android) {
  32304. var composing = false;
  32305. element.on('compositionstart', function() {
  32306. composing = true;
  32307. });
  32308. element.on('compositionend', function() {
  32309. composing = false;
  32310. listener();
  32311. });
  32312. }
  32313. var timeout;
  32314. var listener = function(ev) {
  32315. if (timeout) {
  32316. $browser.defer.cancel(timeout);
  32317. timeout = null;
  32318. }
  32319. if (composing) return;
  32320. var value = element.val(),
  32321. event = ev && ev.type;
  32322. // By default we will trim the value
  32323. // If the attribute ng-trim exists we will avoid trimming
  32324. // If input type is 'password', the value is never trimmed
  32325. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  32326. value = trim(value);
  32327. }
  32328. // If a control is suffering from bad input (due to native validators), browsers discard its
  32329. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  32330. // control's value is the same empty value twice in a row.
  32331. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  32332. ctrl.$setViewValue(value, event);
  32333. }
  32334. };
  32335. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  32336. // input event on backspace, delete or cut
  32337. if ($sniffer.hasEvent('input')) {
  32338. element.on('input', listener);
  32339. } else {
  32340. var deferListener = function(ev, input, origValue) {
  32341. if (!timeout) {
  32342. timeout = $browser.defer(function() {
  32343. timeout = null;
  32344. if (!input || input.value !== origValue) {
  32345. listener(ev);
  32346. }
  32347. });
  32348. }
  32349. };
  32350. element.on('keydown', function(event) {
  32351. var key = event.keyCode;
  32352. // ignore
  32353. // command modifiers arrows
  32354. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  32355. deferListener(event, this, this.value);
  32356. });
  32357. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  32358. if ($sniffer.hasEvent('paste')) {
  32359. element.on('paste cut', deferListener);
  32360. }
  32361. }
  32362. // if user paste into input using mouse on older browser
  32363. // or form autocomplete on newer browser, we need "change" event to catch it
  32364. element.on('change', listener);
  32365. // Some native input types (date-family) have the ability to change validity without
  32366. // firing any input/change events.
  32367. // For these event types, when native validators are present and the browser supports the type,
  32368. // check for validity changes on various DOM events.
  32369. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  32370. element.on(PARTIAL_VALIDATION_EVENTS, function(ev) {
  32371. if (!timeout) {
  32372. var validity = this[VALIDITY_STATE_PROPERTY];
  32373. var origBadInput = validity.badInput;
  32374. var origTypeMismatch = validity.typeMismatch;
  32375. timeout = $browser.defer(function() {
  32376. timeout = null;
  32377. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  32378. listener(ev);
  32379. }
  32380. });
  32381. }
  32382. });
  32383. }
  32384. ctrl.$render = function() {
  32385. // Workaround for Firefox validation #12102.
  32386. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  32387. if (element.val() !== value) {
  32388. element.val(value);
  32389. }
  32390. };
  32391. }
  32392. function weekParser(isoWeek, existingDate) {
  32393. if (isDate(isoWeek)) {
  32394. return isoWeek;
  32395. }
  32396. if (isString(isoWeek)) {
  32397. WEEK_REGEXP.lastIndex = 0;
  32398. var parts = WEEK_REGEXP.exec(isoWeek);
  32399. if (parts) {
  32400. var year = +parts[1],
  32401. week = +parts[2],
  32402. hours = 0,
  32403. minutes = 0,
  32404. seconds = 0,
  32405. milliseconds = 0,
  32406. firstThurs = getFirstThursdayOfYear(year),
  32407. addDays = (week - 1) * 7;
  32408. if (existingDate) {
  32409. hours = existingDate.getHours();
  32410. minutes = existingDate.getMinutes();
  32411. seconds = existingDate.getSeconds();
  32412. milliseconds = existingDate.getMilliseconds();
  32413. }
  32414. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  32415. }
  32416. }
  32417. return NaN;
  32418. }
  32419. function createDateParser(regexp, mapping) {
  32420. return function(iso, date) {
  32421. var parts, map;
  32422. if (isDate(iso)) {
  32423. return iso;
  32424. }
  32425. if (isString(iso)) {
  32426. // When a date is JSON'ified to wraps itself inside of an extra
  32427. // set of double quotes. This makes the date parsing code unable
  32428. // to match the date string and parse it as a date.
  32429. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  32430. iso = iso.substring(1, iso.length - 1);
  32431. }
  32432. if (ISO_DATE_REGEXP.test(iso)) {
  32433. return new Date(iso);
  32434. }
  32435. regexp.lastIndex = 0;
  32436. parts = regexp.exec(iso);
  32437. if (parts) {
  32438. parts.shift();
  32439. if (date) {
  32440. map = {
  32441. yyyy: date.getFullYear(),
  32442. MM: date.getMonth() + 1,
  32443. dd: date.getDate(),
  32444. HH: date.getHours(),
  32445. mm: date.getMinutes(),
  32446. ss: date.getSeconds(),
  32447. sss: date.getMilliseconds() / 1000
  32448. };
  32449. } else {
  32450. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  32451. }
  32452. forEach(parts, function(part, index) {
  32453. if (index < mapping.length) {
  32454. map[mapping[index]] = +part;
  32455. }
  32456. });
  32457. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  32458. }
  32459. }
  32460. return NaN;
  32461. };
  32462. }
  32463. function createDateInputType(type, regexp, parseDate, format) {
  32464. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  32465. badInputChecker(scope, element, attr, ctrl);
  32466. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32467. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  32468. var previousDate;
  32469. ctrl.$$parserName = type;
  32470. ctrl.$parsers.push(function(value) {
  32471. if (ctrl.$isEmpty(value)) return null;
  32472. if (regexp.test(value)) {
  32473. // Note: We cannot read ctrl.$modelValue, as there might be a different
  32474. // parser/formatter in the processing chain so that the model
  32475. // contains some different data format!
  32476. var parsedDate = parseDate(value, previousDate);
  32477. if (timezone) {
  32478. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  32479. }
  32480. return parsedDate;
  32481. }
  32482. return undefined;
  32483. });
  32484. ctrl.$formatters.push(function(value) {
  32485. if (value && !isDate(value)) {
  32486. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  32487. }
  32488. if (isValidDate(value)) {
  32489. previousDate = value;
  32490. if (previousDate && timezone) {
  32491. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  32492. }
  32493. return $filter('date')(value, format, timezone);
  32494. } else {
  32495. previousDate = null;
  32496. return '';
  32497. }
  32498. });
  32499. if (isDefined(attr.min) || attr.ngMin) {
  32500. var minVal;
  32501. ctrl.$validators.min = function(value) {
  32502. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  32503. };
  32504. attr.$observe('min', function(val) {
  32505. minVal = parseObservedDateValue(val);
  32506. ctrl.$validate();
  32507. });
  32508. }
  32509. if (isDefined(attr.max) || attr.ngMax) {
  32510. var maxVal;
  32511. ctrl.$validators.max = function(value) {
  32512. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  32513. };
  32514. attr.$observe('max', function(val) {
  32515. maxVal = parseObservedDateValue(val);
  32516. ctrl.$validate();
  32517. });
  32518. }
  32519. function isValidDate(value) {
  32520. // Invalid Date: getTime() returns NaN
  32521. return value && !(value.getTime && value.getTime() !== value.getTime());
  32522. }
  32523. function parseObservedDateValue(val) {
  32524. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  32525. }
  32526. };
  32527. }
  32528. function badInputChecker(scope, element, attr, ctrl) {
  32529. var node = element[0];
  32530. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  32531. if (nativeValidation) {
  32532. ctrl.$parsers.push(function(value) {
  32533. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  32534. return validity.badInput || validity.typeMismatch ? undefined : value;
  32535. });
  32536. }
  32537. }
  32538. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32539. badInputChecker(scope, element, attr, ctrl);
  32540. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32541. ctrl.$$parserName = 'number';
  32542. ctrl.$parsers.push(function(value) {
  32543. if (ctrl.$isEmpty(value)) return null;
  32544. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  32545. return undefined;
  32546. });
  32547. ctrl.$formatters.push(function(value) {
  32548. if (!ctrl.$isEmpty(value)) {
  32549. if (!isNumber(value)) {
  32550. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  32551. }
  32552. value = value.toString();
  32553. }
  32554. return value;
  32555. });
  32556. if (isDefined(attr.min) || attr.ngMin) {
  32557. var minVal;
  32558. ctrl.$validators.min = function(value) {
  32559. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  32560. };
  32561. attr.$observe('min', function(val) {
  32562. if (isDefined(val) && !isNumber(val)) {
  32563. val = parseFloat(val, 10);
  32564. }
  32565. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  32566. // TODO(matsko): implement validateLater to reduce number of validations
  32567. ctrl.$validate();
  32568. });
  32569. }
  32570. if (isDefined(attr.max) || attr.ngMax) {
  32571. var maxVal;
  32572. ctrl.$validators.max = function(value) {
  32573. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  32574. };
  32575. attr.$observe('max', function(val) {
  32576. if (isDefined(val) && !isNumber(val)) {
  32577. val = parseFloat(val, 10);
  32578. }
  32579. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  32580. // TODO(matsko): implement validateLater to reduce number of validations
  32581. ctrl.$validate();
  32582. });
  32583. }
  32584. }
  32585. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32586. // Note: no badInputChecker here by purpose as `url` is only a validation
  32587. // in browsers, i.e. we can always read out input.value even if it is not valid!
  32588. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32589. stringBasedInputType(ctrl);
  32590. ctrl.$$parserName = 'url';
  32591. ctrl.$validators.url = function(modelValue, viewValue) {
  32592. var value = modelValue || viewValue;
  32593. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  32594. };
  32595. }
  32596. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32597. // Note: no badInputChecker here by purpose as `url` is only a validation
  32598. // in browsers, i.e. we can always read out input.value even if it is not valid!
  32599. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32600. stringBasedInputType(ctrl);
  32601. ctrl.$$parserName = 'email';
  32602. ctrl.$validators.email = function(modelValue, viewValue) {
  32603. var value = modelValue || viewValue;
  32604. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  32605. };
  32606. }
  32607. function radioInputType(scope, element, attr, ctrl) {
  32608. // make the name unique, if not defined
  32609. if (isUndefined(attr.name)) {
  32610. element.attr('name', nextUid());
  32611. }
  32612. var listener = function(ev) {
  32613. if (element[0].checked) {
  32614. ctrl.$setViewValue(attr.value, ev && ev.type);
  32615. }
  32616. };
  32617. element.on('click', listener);
  32618. ctrl.$render = function() {
  32619. var value = attr.value;
  32620. element[0].checked = (value == ctrl.$viewValue);
  32621. };
  32622. attr.$observe('value', ctrl.$render);
  32623. }
  32624. function parseConstantExpr($parse, context, name, expression, fallback) {
  32625. var parseFn;
  32626. if (isDefined(expression)) {
  32627. parseFn = $parse(expression);
  32628. if (!parseFn.constant) {
  32629. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  32630. '`{1}`.', name, expression);
  32631. }
  32632. return parseFn(context);
  32633. }
  32634. return fallback;
  32635. }
  32636. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  32637. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  32638. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  32639. var listener = function(ev) {
  32640. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  32641. };
  32642. element.on('click', listener);
  32643. ctrl.$render = function() {
  32644. element[0].checked = ctrl.$viewValue;
  32645. };
  32646. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  32647. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  32648. // it to a boolean.
  32649. ctrl.$isEmpty = function(value) {
  32650. return value === false;
  32651. };
  32652. ctrl.$formatters.push(function(value) {
  32653. return equals(value, trueValue);
  32654. });
  32655. ctrl.$parsers.push(function(value) {
  32656. return value ? trueValue : falseValue;
  32657. });
  32658. }
  32659. /**
  32660. * @ngdoc directive
  32661. * @name textarea
  32662. * @restrict E
  32663. *
  32664. * @description
  32665. * HTML textarea element control with angular data-binding. The data-binding and validation
  32666. * properties of this element are exactly the same as those of the
  32667. * {@link ng.directive:input input element}.
  32668. *
  32669. * @param {string} ngModel Assignable angular expression to data-bind to.
  32670. * @param {string=} name Property name of the form under which the control is published.
  32671. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32672. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32673. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32674. * `required` when you want to data-bind to the `required` attribute.
  32675. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32676. * minlength.
  32677. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32678. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  32679. * length.
  32680. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32681. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32682. * If the expression evaluates to a RegExp object, then this is used directly.
  32683. * If the expression evaluates to a string, then it will be converted to a RegExp
  32684. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32685. * `new RegExp('^abc$')`.<br />
  32686. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32687. * start at the index of the last search's match, thus not taking the whole input value into
  32688. * account.
  32689. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32690. * interaction with the input element.
  32691. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  32692. */
  32693. /**
  32694. * @ngdoc directive
  32695. * @name input
  32696. * @restrict E
  32697. *
  32698. * @description
  32699. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  32700. * input state control, and validation.
  32701. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  32702. *
  32703. * <div class="alert alert-warning">
  32704. * **Note:** Not every feature offered is available for all input types.
  32705. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  32706. * </div>
  32707. *
  32708. * @param {string} ngModel Assignable angular expression to data-bind to.
  32709. * @param {string=} name Property name of the form under which the control is published.
  32710. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32711. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  32712. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32713. * minlength.
  32714. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32715. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  32716. * length.
  32717. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32718. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32719. * If the expression evaluates to a RegExp object, then this is used directly.
  32720. * If the expression evaluates to a string, then it will be converted to a RegExp
  32721. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32722. * `new RegExp('^abc$')`.<br />
  32723. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32724. * start at the index of the last search's match, thus not taking the whole input value into
  32725. * account.
  32726. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32727. * interaction with the input element.
  32728. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  32729. * This parameter is ignored for input[type=password] controls, which will never trim the
  32730. * input.
  32731. *
  32732. * @example
  32733. <example name="input-directive" module="inputExample">
  32734. <file name="index.html">
  32735. <script>
  32736. angular.module('inputExample', [])
  32737. .controller('ExampleController', ['$scope', function($scope) {
  32738. $scope.user = {name: 'guest', last: 'visitor'};
  32739. }]);
  32740. </script>
  32741. <div ng-controller="ExampleController">
  32742. <form name="myForm">
  32743. <label>
  32744. User name:
  32745. <input type="text" name="userName" ng-model="user.name" required>
  32746. </label>
  32747. <div role="alert">
  32748. <span class="error" ng-show="myForm.userName.$error.required">
  32749. Required!</span>
  32750. </div>
  32751. <label>
  32752. Last name:
  32753. <input type="text" name="lastName" ng-model="user.last"
  32754. ng-minlength="3" ng-maxlength="10">
  32755. </label>
  32756. <div role="alert">
  32757. <span class="error" ng-show="myForm.lastName.$error.minlength">
  32758. Too short!</span>
  32759. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  32760. Too long!</span>
  32761. </div>
  32762. </form>
  32763. <hr>
  32764. <tt>user = {{user}}</tt><br/>
  32765. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  32766. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  32767. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  32768. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  32769. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32770. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32771. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  32772. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  32773. </div>
  32774. </file>
  32775. <file name="protractor.js" type="protractor">
  32776. var user = element(by.exactBinding('user'));
  32777. var userNameValid = element(by.binding('myForm.userName.$valid'));
  32778. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  32779. var lastNameError = element(by.binding('myForm.lastName.$error'));
  32780. var formValid = element(by.binding('myForm.$valid'));
  32781. var userNameInput = element(by.model('user.name'));
  32782. var userLastInput = element(by.model('user.last'));
  32783. it('should initialize to model', function() {
  32784. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  32785. expect(userNameValid.getText()).toContain('true');
  32786. expect(formValid.getText()).toContain('true');
  32787. });
  32788. it('should be invalid if empty when required', function() {
  32789. userNameInput.clear();
  32790. userNameInput.sendKeys('');
  32791. expect(user.getText()).toContain('{"last":"visitor"}');
  32792. expect(userNameValid.getText()).toContain('false');
  32793. expect(formValid.getText()).toContain('false');
  32794. });
  32795. it('should be valid if empty when min length is set', function() {
  32796. userLastInput.clear();
  32797. userLastInput.sendKeys('');
  32798. expect(user.getText()).toContain('{"name":"guest","last":""}');
  32799. expect(lastNameValid.getText()).toContain('true');
  32800. expect(formValid.getText()).toContain('true');
  32801. });
  32802. it('should be invalid if less than required min length', function() {
  32803. userLastInput.clear();
  32804. userLastInput.sendKeys('xx');
  32805. expect(user.getText()).toContain('{"name":"guest"}');
  32806. expect(lastNameValid.getText()).toContain('false');
  32807. expect(lastNameError.getText()).toContain('minlength');
  32808. expect(formValid.getText()).toContain('false');
  32809. });
  32810. it('should be invalid if longer than max length', function() {
  32811. userLastInput.clear();
  32812. userLastInput.sendKeys('some ridiculously long name');
  32813. expect(user.getText()).toContain('{"name":"guest"}');
  32814. expect(lastNameValid.getText()).toContain('false');
  32815. expect(lastNameError.getText()).toContain('maxlength');
  32816. expect(formValid.getText()).toContain('false');
  32817. });
  32818. </file>
  32819. </example>
  32820. */
  32821. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  32822. function($browser, $sniffer, $filter, $parse) {
  32823. return {
  32824. restrict: 'E',
  32825. require: ['?ngModel'],
  32826. link: {
  32827. pre: function(scope, element, attr, ctrls) {
  32828. if (ctrls[0]) {
  32829. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  32830. $browser, $filter, $parse);
  32831. }
  32832. }
  32833. }
  32834. };
  32835. }];
  32836. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  32837. /**
  32838. * @ngdoc directive
  32839. * @name ngValue
  32840. *
  32841. * @description
  32842. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  32843. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  32844. * the bound value.
  32845. *
  32846. * `ngValue` is useful when dynamically generating lists of radio buttons using
  32847. * {@link ngRepeat `ngRepeat`}, as shown below.
  32848. *
  32849. * Likewise, `ngValue` can be used to generate `<option>` elements for
  32850. * the {@link select `select`} element. In that case however, only strings are supported
  32851. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  32852. * Support for `select` models with non-string values is available via `ngOptions`.
  32853. *
  32854. * @element input
  32855. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  32856. * of the `input` element
  32857. *
  32858. * @example
  32859. <example name="ngValue-directive" module="valueExample">
  32860. <file name="index.html">
  32861. <script>
  32862. angular.module('valueExample', [])
  32863. .controller('ExampleController', ['$scope', function($scope) {
  32864. $scope.names = ['pizza', 'unicorns', 'robots'];
  32865. $scope.my = { favorite: 'unicorns' };
  32866. }]);
  32867. </script>
  32868. <form ng-controller="ExampleController">
  32869. <h2>Which is your favorite?</h2>
  32870. <label ng-repeat="name in names" for="{{name}}">
  32871. {{name}}
  32872. <input type="radio"
  32873. ng-model="my.favorite"
  32874. ng-value="name"
  32875. id="{{name}}"
  32876. name="favorite">
  32877. </label>
  32878. <div>You chose {{my.favorite}}</div>
  32879. </form>
  32880. </file>
  32881. <file name="protractor.js" type="protractor">
  32882. var favorite = element(by.binding('my.favorite'));
  32883. it('should initialize to model', function() {
  32884. expect(favorite.getText()).toContain('unicorns');
  32885. });
  32886. it('should bind the values to the inputs', function() {
  32887. element.all(by.model('my.favorite')).get(0).click();
  32888. expect(favorite.getText()).toContain('pizza');
  32889. });
  32890. </file>
  32891. </example>
  32892. */
  32893. var ngValueDirective = function() {
  32894. return {
  32895. restrict: 'A',
  32896. priority: 100,
  32897. compile: function(tpl, tplAttr) {
  32898. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  32899. return function ngValueConstantLink(scope, elm, attr) {
  32900. attr.$set('value', scope.$eval(attr.ngValue));
  32901. };
  32902. } else {
  32903. return function ngValueLink(scope, elm, attr) {
  32904. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  32905. attr.$set('value', value);
  32906. });
  32907. };
  32908. }
  32909. }
  32910. };
  32911. };
  32912. /**
  32913. * @ngdoc directive
  32914. * @name ngBind
  32915. * @restrict AC
  32916. *
  32917. * @description
  32918. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  32919. * with the value of a given expression, and to update the text content when the value of that
  32920. * expression changes.
  32921. *
  32922. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  32923. * `{{ expression }}` which is similar but less verbose.
  32924. *
  32925. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  32926. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  32927. * element attribute, it makes the bindings invisible to the user while the page is loading.
  32928. *
  32929. * An alternative solution to this problem would be using the
  32930. * {@link ng.directive:ngCloak ngCloak} directive.
  32931. *
  32932. *
  32933. * @element ANY
  32934. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  32935. *
  32936. * @example
  32937. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  32938. <example module="bindExample">
  32939. <file name="index.html">
  32940. <script>
  32941. angular.module('bindExample', [])
  32942. .controller('ExampleController', ['$scope', function($scope) {
  32943. $scope.name = 'Whirled';
  32944. }]);
  32945. </script>
  32946. <div ng-controller="ExampleController">
  32947. <label>Enter name: <input type="text" ng-model="name"></label><br>
  32948. Hello <span ng-bind="name"></span>!
  32949. </div>
  32950. </file>
  32951. <file name="protractor.js" type="protractor">
  32952. it('should check ng-bind', function() {
  32953. var nameInput = element(by.model('name'));
  32954. expect(element(by.binding('name')).getText()).toBe('Whirled');
  32955. nameInput.clear();
  32956. nameInput.sendKeys('world');
  32957. expect(element(by.binding('name')).getText()).toBe('world');
  32958. });
  32959. </file>
  32960. </example>
  32961. */
  32962. var ngBindDirective = ['$compile', function($compile) {
  32963. return {
  32964. restrict: 'AC',
  32965. compile: function ngBindCompile(templateElement) {
  32966. $compile.$$addBindingClass(templateElement);
  32967. return function ngBindLink(scope, element, attr) {
  32968. $compile.$$addBindingInfo(element, attr.ngBind);
  32969. element = element[0];
  32970. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  32971. element.textContent = isUndefined(value) ? '' : value;
  32972. });
  32973. };
  32974. }
  32975. };
  32976. }];
  32977. /**
  32978. * @ngdoc directive
  32979. * @name ngBindTemplate
  32980. *
  32981. * @description
  32982. * The `ngBindTemplate` directive specifies that the element
  32983. * text content should be replaced with the interpolation of the template
  32984. * in the `ngBindTemplate` attribute.
  32985. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  32986. * expressions. This directive is needed since some HTML elements
  32987. * (such as TITLE and OPTION) cannot contain SPAN elements.
  32988. *
  32989. * @element ANY
  32990. * @param {string} ngBindTemplate template of form
  32991. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  32992. *
  32993. * @example
  32994. * Try it here: enter text in text box and watch the greeting change.
  32995. <example module="bindExample">
  32996. <file name="index.html">
  32997. <script>
  32998. angular.module('bindExample', [])
  32999. .controller('ExampleController', ['$scope', function($scope) {
  33000. $scope.salutation = 'Hello';
  33001. $scope.name = 'World';
  33002. }]);
  33003. </script>
  33004. <div ng-controller="ExampleController">
  33005. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  33006. <label>Name: <input type="text" ng-model="name"></label><br>
  33007. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  33008. </div>
  33009. </file>
  33010. <file name="protractor.js" type="protractor">
  33011. it('should check ng-bind', function() {
  33012. var salutationElem = element(by.binding('salutation'));
  33013. var salutationInput = element(by.model('salutation'));
  33014. var nameInput = element(by.model('name'));
  33015. expect(salutationElem.getText()).toBe('Hello World!');
  33016. salutationInput.clear();
  33017. salutationInput.sendKeys('Greetings');
  33018. nameInput.clear();
  33019. nameInput.sendKeys('user');
  33020. expect(salutationElem.getText()).toBe('Greetings user!');
  33021. });
  33022. </file>
  33023. </example>
  33024. */
  33025. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  33026. return {
  33027. compile: function ngBindTemplateCompile(templateElement) {
  33028. $compile.$$addBindingClass(templateElement);
  33029. return function ngBindTemplateLink(scope, element, attr) {
  33030. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  33031. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  33032. element = element[0];
  33033. attr.$observe('ngBindTemplate', function(value) {
  33034. element.textContent = isUndefined(value) ? '' : value;
  33035. });
  33036. };
  33037. }
  33038. };
  33039. }];
  33040. /**
  33041. * @ngdoc directive
  33042. * @name ngBindHtml
  33043. *
  33044. * @description
  33045. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  33046. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  33047. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  33048. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  33049. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  33050. *
  33051. * You may also bypass sanitization for values you know are safe. To do so, bind to
  33052. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  33053. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  33054. *
  33055. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  33056. * will have an exception (instead of an exploit.)
  33057. *
  33058. * @element ANY
  33059. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  33060. *
  33061. * @example
  33062. <example module="bindHtmlExample" deps="angular-sanitize.js">
  33063. <file name="index.html">
  33064. <div ng-controller="ExampleController">
  33065. <p ng-bind-html="myHTML"></p>
  33066. </div>
  33067. </file>
  33068. <file name="script.js">
  33069. angular.module('bindHtmlExample', ['ngSanitize'])
  33070. .controller('ExampleController', ['$scope', function($scope) {
  33071. $scope.myHTML =
  33072. 'I am an <code>HTML</code>string with ' +
  33073. '<a href="#">links!</a> and other <em>stuff</em>';
  33074. }]);
  33075. </file>
  33076. <file name="protractor.js" type="protractor">
  33077. it('should check ng-bind-html', function() {
  33078. expect(element(by.binding('myHTML')).getText()).toBe(
  33079. 'I am an HTMLstring with links! and other stuff');
  33080. });
  33081. </file>
  33082. </example>
  33083. */
  33084. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  33085. return {
  33086. restrict: 'A',
  33087. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  33088. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  33089. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  33090. return (value || '').toString();
  33091. });
  33092. $compile.$$addBindingClass(tElement);
  33093. return function ngBindHtmlLink(scope, element, attr) {
  33094. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  33095. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  33096. // we re-evaluate the expr because we want a TrustedValueHolderType
  33097. // for $sce, not a string
  33098. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  33099. });
  33100. };
  33101. }
  33102. };
  33103. }];
  33104. /**
  33105. * @ngdoc directive
  33106. * @name ngChange
  33107. *
  33108. * @description
  33109. * Evaluate the given expression when the user changes the input.
  33110. * The expression is evaluated immediately, unlike the JavaScript onchange event
  33111. * which only triggers at the end of a change (usually, when the user leaves the
  33112. * form element or presses the return key).
  33113. *
  33114. * The `ngChange` expression is only evaluated when a change in the input value causes
  33115. * a new value to be committed to the model.
  33116. *
  33117. * It will not be evaluated:
  33118. * * if the value returned from the `$parsers` transformation pipeline has not changed
  33119. * * if the input has continued to be invalid since the model will stay `null`
  33120. * * if the model is changed programmatically and not by a change to the input value
  33121. *
  33122. *
  33123. * Note, this directive requires `ngModel` to be present.
  33124. *
  33125. * @element input
  33126. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  33127. * in input value.
  33128. *
  33129. * @example
  33130. * <example name="ngChange-directive" module="changeExample">
  33131. * <file name="index.html">
  33132. * <script>
  33133. * angular.module('changeExample', [])
  33134. * .controller('ExampleController', ['$scope', function($scope) {
  33135. * $scope.counter = 0;
  33136. * $scope.change = function() {
  33137. * $scope.counter++;
  33138. * };
  33139. * }]);
  33140. * </script>
  33141. * <div ng-controller="ExampleController">
  33142. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  33143. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  33144. * <label for="ng-change-example2">Confirmed</label><br />
  33145. * <tt>debug = {{confirmed}}</tt><br/>
  33146. * <tt>counter = {{counter}}</tt><br/>
  33147. * </div>
  33148. * </file>
  33149. * <file name="protractor.js" type="protractor">
  33150. * var counter = element(by.binding('counter'));
  33151. * var debug = element(by.binding('confirmed'));
  33152. *
  33153. * it('should evaluate the expression if changing from view', function() {
  33154. * expect(counter.getText()).toContain('0');
  33155. *
  33156. * element(by.id('ng-change-example1')).click();
  33157. *
  33158. * expect(counter.getText()).toContain('1');
  33159. * expect(debug.getText()).toContain('true');
  33160. * });
  33161. *
  33162. * it('should not evaluate the expression if changing from model', function() {
  33163. * element(by.id('ng-change-example2')).click();
  33164. * expect(counter.getText()).toContain('0');
  33165. * expect(debug.getText()).toContain('true');
  33166. * });
  33167. * </file>
  33168. * </example>
  33169. */
  33170. var ngChangeDirective = valueFn({
  33171. restrict: 'A',
  33172. require: 'ngModel',
  33173. link: function(scope, element, attr, ctrl) {
  33174. ctrl.$viewChangeListeners.push(function() {
  33175. scope.$eval(attr.ngChange);
  33176. });
  33177. }
  33178. });
  33179. function classDirective(name, selector) {
  33180. name = 'ngClass' + name;
  33181. return ['$animate', function($animate) {
  33182. return {
  33183. restrict: 'AC',
  33184. link: function(scope, element, attr) {
  33185. var oldVal;
  33186. scope.$watch(attr[name], ngClassWatchAction, true);
  33187. attr.$observe('class', function(value) {
  33188. ngClassWatchAction(scope.$eval(attr[name]));
  33189. });
  33190. if (name !== 'ngClass') {
  33191. scope.$watch('$index', function($index, old$index) {
  33192. // jshint bitwise: false
  33193. var mod = $index & 1;
  33194. if (mod !== (old$index & 1)) {
  33195. var classes = arrayClasses(scope.$eval(attr[name]));
  33196. mod === selector ?
  33197. addClasses(classes) :
  33198. removeClasses(classes);
  33199. }
  33200. });
  33201. }
  33202. function addClasses(classes) {
  33203. var newClasses = digestClassCounts(classes, 1);
  33204. attr.$addClass(newClasses);
  33205. }
  33206. function removeClasses(classes) {
  33207. var newClasses = digestClassCounts(classes, -1);
  33208. attr.$removeClass(newClasses);
  33209. }
  33210. function digestClassCounts(classes, count) {
  33211. // Use createMap() to prevent class assumptions involving property
  33212. // names in Object.prototype
  33213. var classCounts = element.data('$classCounts') || createMap();
  33214. var classesToUpdate = [];
  33215. forEach(classes, function(className) {
  33216. if (count > 0 || classCounts[className]) {
  33217. classCounts[className] = (classCounts[className] || 0) + count;
  33218. if (classCounts[className] === +(count > 0)) {
  33219. classesToUpdate.push(className);
  33220. }
  33221. }
  33222. });
  33223. element.data('$classCounts', classCounts);
  33224. return classesToUpdate.join(' ');
  33225. }
  33226. function updateClasses(oldClasses, newClasses) {
  33227. var toAdd = arrayDifference(newClasses, oldClasses);
  33228. var toRemove = arrayDifference(oldClasses, newClasses);
  33229. toAdd = digestClassCounts(toAdd, 1);
  33230. toRemove = digestClassCounts(toRemove, -1);
  33231. if (toAdd && toAdd.length) {
  33232. $animate.addClass(element, toAdd);
  33233. }
  33234. if (toRemove && toRemove.length) {
  33235. $animate.removeClass(element, toRemove);
  33236. }
  33237. }
  33238. function ngClassWatchAction(newVal) {
  33239. if (selector === true || scope.$index % 2 === selector) {
  33240. var newClasses = arrayClasses(newVal || []);
  33241. if (!oldVal) {
  33242. addClasses(newClasses);
  33243. } else if (!equals(newVal,oldVal)) {
  33244. var oldClasses = arrayClasses(oldVal);
  33245. updateClasses(oldClasses, newClasses);
  33246. }
  33247. }
  33248. oldVal = shallowCopy(newVal);
  33249. }
  33250. }
  33251. };
  33252. function arrayDifference(tokens1, tokens2) {
  33253. var values = [];
  33254. outer:
  33255. for (var i = 0; i < tokens1.length; i++) {
  33256. var token = tokens1[i];
  33257. for (var j = 0; j < tokens2.length; j++) {
  33258. if (token == tokens2[j]) continue outer;
  33259. }
  33260. values.push(token);
  33261. }
  33262. return values;
  33263. }
  33264. function arrayClasses(classVal) {
  33265. var classes = [];
  33266. if (isArray(classVal)) {
  33267. forEach(classVal, function(v) {
  33268. classes = classes.concat(arrayClasses(v));
  33269. });
  33270. return classes;
  33271. } else if (isString(classVal)) {
  33272. return classVal.split(' ');
  33273. } else if (isObject(classVal)) {
  33274. forEach(classVal, function(v, k) {
  33275. if (v) {
  33276. classes = classes.concat(k.split(' '));
  33277. }
  33278. });
  33279. return classes;
  33280. }
  33281. return classVal;
  33282. }
  33283. }];
  33284. }
  33285. /**
  33286. * @ngdoc directive
  33287. * @name ngClass
  33288. * @restrict AC
  33289. *
  33290. * @description
  33291. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  33292. * an expression that represents all classes to be added.
  33293. *
  33294. * The directive operates in three different ways, depending on which of three types the expression
  33295. * evaluates to:
  33296. *
  33297. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  33298. * names.
  33299. *
  33300. * 2. If the expression evaluates to an object, then for each key-value pair of the
  33301. * object with a truthy value the corresponding key is used as a class name.
  33302. *
  33303. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  33304. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  33305. * to give you more control over what CSS classes appear. See the code below for an example of this.
  33306. *
  33307. *
  33308. * The directive won't add duplicate classes if a particular class was already set.
  33309. *
  33310. * When the expression changes, the previously added classes are removed and only then are the
  33311. * new classes added.
  33312. *
  33313. * @animations
  33314. * | Animation | Occurs |
  33315. * |----------------------------------|-------------------------------------|
  33316. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  33317. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  33318. *
  33319. * @element ANY
  33320. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  33321. * of the evaluation can be a string representing space delimited class
  33322. * names, an array, or a map of class names to boolean values. In the case of a map, the
  33323. * names of the properties whose values are truthy will be added as css classes to the
  33324. * element.
  33325. *
  33326. * @example Example that demonstrates basic bindings via ngClass directive.
  33327. <example>
  33328. <file name="index.html">
  33329. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  33330. <label>
  33331. <input type="checkbox" ng-model="deleted">
  33332. deleted (apply "strike" class)
  33333. </label><br>
  33334. <label>
  33335. <input type="checkbox" ng-model="important">
  33336. important (apply "bold" class)
  33337. </label><br>
  33338. <label>
  33339. <input type="checkbox" ng-model="error">
  33340. error (apply "has-error" class)
  33341. </label>
  33342. <hr>
  33343. <p ng-class="style">Using String Syntax</p>
  33344. <input type="text" ng-model="style"
  33345. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  33346. <hr>
  33347. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  33348. <input ng-model="style1"
  33349. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  33350. <input ng-model="style2"
  33351. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  33352. <input ng-model="style3"
  33353. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  33354. <hr>
  33355. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  33356. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  33357. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  33358. </file>
  33359. <file name="style.css">
  33360. .strike {
  33361. text-decoration: line-through;
  33362. }
  33363. .bold {
  33364. font-weight: bold;
  33365. }
  33366. .red {
  33367. color: red;
  33368. }
  33369. .has-error {
  33370. color: red;
  33371. background-color: yellow;
  33372. }
  33373. .orange {
  33374. color: orange;
  33375. }
  33376. </file>
  33377. <file name="protractor.js" type="protractor">
  33378. var ps = element.all(by.css('p'));
  33379. it('should let you toggle the class', function() {
  33380. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  33381. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  33382. element(by.model('important')).click();
  33383. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  33384. element(by.model('error')).click();
  33385. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  33386. });
  33387. it('should let you toggle string example', function() {
  33388. expect(ps.get(1).getAttribute('class')).toBe('');
  33389. element(by.model('style')).clear();
  33390. element(by.model('style')).sendKeys('red');
  33391. expect(ps.get(1).getAttribute('class')).toBe('red');
  33392. });
  33393. it('array example should have 3 classes', function() {
  33394. expect(ps.get(2).getAttribute('class')).toBe('');
  33395. element(by.model('style1')).sendKeys('bold');
  33396. element(by.model('style2')).sendKeys('strike');
  33397. element(by.model('style3')).sendKeys('red');
  33398. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  33399. });
  33400. it('array with map example should have 2 classes', function() {
  33401. expect(ps.last().getAttribute('class')).toBe('');
  33402. element(by.model('style4')).sendKeys('bold');
  33403. element(by.model('warning')).click();
  33404. expect(ps.last().getAttribute('class')).toBe('bold orange');
  33405. });
  33406. </file>
  33407. </example>
  33408. ## Animations
  33409. The example below demonstrates how to perform animations using ngClass.
  33410. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  33411. <file name="index.html">
  33412. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  33413. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  33414. <br>
  33415. <span class="base-class" ng-class="myVar">Sample Text</span>
  33416. </file>
  33417. <file name="style.css">
  33418. .base-class {
  33419. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  33420. }
  33421. .base-class.my-class {
  33422. color: red;
  33423. font-size:3em;
  33424. }
  33425. </file>
  33426. <file name="protractor.js" type="protractor">
  33427. it('should check ng-class', function() {
  33428. expect(element(by.css('.base-class')).getAttribute('class')).not.
  33429. toMatch(/my-class/);
  33430. element(by.id('setbtn')).click();
  33431. expect(element(by.css('.base-class')).getAttribute('class')).
  33432. toMatch(/my-class/);
  33433. element(by.id('clearbtn')).click();
  33434. expect(element(by.css('.base-class')).getAttribute('class')).not.
  33435. toMatch(/my-class/);
  33436. });
  33437. </file>
  33438. </example>
  33439. ## ngClass and pre-existing CSS3 Transitions/Animations
  33440. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  33441. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  33442. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  33443. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  33444. {@link $animate#removeClass $animate.removeClass}.
  33445. */
  33446. var ngClassDirective = classDirective('', true);
  33447. /**
  33448. * @ngdoc directive
  33449. * @name ngClassOdd
  33450. * @restrict AC
  33451. *
  33452. * @description
  33453. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  33454. * {@link ng.directive:ngClass ngClass}, except they work in
  33455. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  33456. *
  33457. * This directive can be applied only within the scope of an
  33458. * {@link ng.directive:ngRepeat ngRepeat}.
  33459. *
  33460. * @element ANY
  33461. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  33462. * of the evaluation can be a string representing space delimited class names or an array.
  33463. *
  33464. * @example
  33465. <example>
  33466. <file name="index.html">
  33467. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  33468. <li ng-repeat="name in names">
  33469. <span ng-class-odd="'odd'" ng-class-even="'even'">
  33470. {{name}}
  33471. </span>
  33472. </li>
  33473. </ol>
  33474. </file>
  33475. <file name="style.css">
  33476. .odd {
  33477. color: red;
  33478. }
  33479. .even {
  33480. color: blue;
  33481. }
  33482. </file>
  33483. <file name="protractor.js" type="protractor">
  33484. it('should check ng-class-odd and ng-class-even', function() {
  33485. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  33486. toMatch(/odd/);
  33487. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  33488. toMatch(/even/);
  33489. });
  33490. </file>
  33491. </example>
  33492. */
  33493. var ngClassOddDirective = classDirective('Odd', 0);
  33494. /**
  33495. * @ngdoc directive
  33496. * @name ngClassEven
  33497. * @restrict AC
  33498. *
  33499. * @description
  33500. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  33501. * {@link ng.directive:ngClass ngClass}, except they work in
  33502. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  33503. *
  33504. * This directive can be applied only within the scope of an
  33505. * {@link ng.directive:ngRepeat ngRepeat}.
  33506. *
  33507. * @element ANY
  33508. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  33509. * result of the evaluation can be a string representing space delimited class names or an array.
  33510. *
  33511. * @example
  33512. <example>
  33513. <file name="index.html">
  33514. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  33515. <li ng-repeat="name in names">
  33516. <span ng-class-odd="'odd'" ng-class-even="'even'">
  33517. {{name}} &nbsp; &nbsp; &nbsp;
  33518. </span>
  33519. </li>
  33520. </ol>
  33521. </file>
  33522. <file name="style.css">
  33523. .odd {
  33524. color: red;
  33525. }
  33526. .even {
  33527. color: blue;
  33528. }
  33529. </file>
  33530. <file name="protractor.js" type="protractor">
  33531. it('should check ng-class-odd and ng-class-even', function() {
  33532. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  33533. toMatch(/odd/);
  33534. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  33535. toMatch(/even/);
  33536. });
  33537. </file>
  33538. </example>
  33539. */
  33540. var ngClassEvenDirective = classDirective('Even', 1);
  33541. /**
  33542. * @ngdoc directive
  33543. * @name ngCloak
  33544. * @restrict AC
  33545. *
  33546. * @description
  33547. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  33548. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  33549. * directive to avoid the undesirable flicker effect caused by the html template display.
  33550. *
  33551. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  33552. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  33553. * of the browser view.
  33554. *
  33555. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  33556. * `angular.min.js`.
  33557. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  33558. *
  33559. * ```css
  33560. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  33561. * display: none !important;
  33562. * }
  33563. * ```
  33564. *
  33565. * When this css rule is loaded by the browser, all html elements (including their children) that
  33566. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  33567. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  33568. * the compiled element visible.
  33569. *
  33570. * For the best result, the `angular.js` script must be loaded in the head section of the html
  33571. * document; alternatively, the css rule above must be included in the external stylesheet of the
  33572. * application.
  33573. *
  33574. * @element ANY
  33575. *
  33576. * @example
  33577. <example>
  33578. <file name="index.html">
  33579. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  33580. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  33581. </file>
  33582. <file name="protractor.js" type="protractor">
  33583. it('should remove the template directive and css class', function() {
  33584. expect($('#template1').getAttribute('ng-cloak')).
  33585. toBeNull();
  33586. expect($('#template2').getAttribute('ng-cloak')).
  33587. toBeNull();
  33588. });
  33589. </file>
  33590. </example>
  33591. *
  33592. */
  33593. var ngCloakDirective = ngDirective({
  33594. compile: function(element, attr) {
  33595. attr.$set('ngCloak', undefined);
  33596. element.removeClass('ng-cloak');
  33597. }
  33598. });
  33599. /**
  33600. * @ngdoc directive
  33601. * @name ngController
  33602. *
  33603. * @description
  33604. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  33605. * supports the principles behind the Model-View-Controller design pattern.
  33606. *
  33607. * MVC components in angular:
  33608. *
  33609. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  33610. * are accessed through bindings.
  33611. * * View — The template (HTML with data bindings) that is rendered into the View.
  33612. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  33613. * logic behind the application to decorate the scope with functions and values
  33614. *
  33615. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  33616. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  33617. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  33618. * and executed twice.
  33619. *
  33620. * @element ANY
  33621. * @scope
  33622. * @priority 500
  33623. * @param {expression} ngController Name of a constructor function registered with the current
  33624. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  33625. * that on the current scope evaluates to a constructor function.
  33626. *
  33627. * The controller instance can be published into a scope property by specifying
  33628. * `ng-controller="as propertyName"`.
  33629. *
  33630. * If the current `$controllerProvider` is configured to use globals (via
  33631. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  33632. * also be the name of a globally accessible constructor function (not recommended).
  33633. *
  33634. * @example
  33635. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  33636. * greeting are methods declared on the controller (see source tab). These methods can
  33637. * easily be called from the angular markup. Any changes to the data are automatically reflected
  33638. * in the View without the need for a manual update.
  33639. *
  33640. * Two different declaration styles are included below:
  33641. *
  33642. * * one binds methods and properties directly onto the controller using `this`:
  33643. * `ng-controller="SettingsController1 as settings"`
  33644. * * one injects `$scope` into the controller:
  33645. * `ng-controller="SettingsController2"`
  33646. *
  33647. * The second option is more common in the Angular community, and is generally used in boilerplates
  33648. * and in this guide. However, there are advantages to binding properties directly to the controller
  33649. * and avoiding scope.
  33650. *
  33651. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  33652. * multiple controllers apply to an element.
  33653. * * If you are writing your controllers as classes you have easier access to the properties and
  33654. * methods, which will appear on the scope, from inside the controller code.
  33655. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  33656. * inheritance masking primitives.
  33657. *
  33658. * This example demonstrates the `controller as` syntax.
  33659. *
  33660. * <example name="ngControllerAs" module="controllerAsExample">
  33661. * <file name="index.html">
  33662. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  33663. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  33664. * <button ng-click="settings.greet()">greet</button><br/>
  33665. * Contact:
  33666. * <ul>
  33667. * <li ng-repeat="contact in settings.contacts">
  33668. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  33669. * <option>phone</option>
  33670. * <option>email</option>
  33671. * </select>
  33672. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  33673. * <button ng-click="settings.clearContact(contact)">clear</button>
  33674. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  33675. * </li>
  33676. * <li><button ng-click="settings.addContact()">add</button></li>
  33677. * </ul>
  33678. * </div>
  33679. * </file>
  33680. * <file name="app.js">
  33681. * angular.module('controllerAsExample', [])
  33682. * .controller('SettingsController1', SettingsController1);
  33683. *
  33684. * function SettingsController1() {
  33685. * this.name = "John Smith";
  33686. * this.contacts = [
  33687. * {type: 'phone', value: '408 555 1212'},
  33688. * {type: 'email', value: 'john.smith@example.org'} ];
  33689. * }
  33690. *
  33691. * SettingsController1.prototype.greet = function() {
  33692. * alert(this.name);
  33693. * };
  33694. *
  33695. * SettingsController1.prototype.addContact = function() {
  33696. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  33697. * };
  33698. *
  33699. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  33700. * var index = this.contacts.indexOf(contactToRemove);
  33701. * this.contacts.splice(index, 1);
  33702. * };
  33703. *
  33704. * SettingsController1.prototype.clearContact = function(contact) {
  33705. * contact.type = 'phone';
  33706. * contact.value = '';
  33707. * };
  33708. * </file>
  33709. * <file name="protractor.js" type="protractor">
  33710. * it('should check controller as', function() {
  33711. * var container = element(by.id('ctrl-as-exmpl'));
  33712. * expect(container.element(by.model('settings.name'))
  33713. * .getAttribute('value')).toBe('John Smith');
  33714. *
  33715. * var firstRepeat =
  33716. * container.element(by.repeater('contact in settings.contacts').row(0));
  33717. * var secondRepeat =
  33718. * container.element(by.repeater('contact in settings.contacts').row(1));
  33719. *
  33720. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33721. * .toBe('408 555 1212');
  33722. *
  33723. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  33724. * .toBe('john.smith@example.org');
  33725. *
  33726. * firstRepeat.element(by.buttonText('clear')).click();
  33727. *
  33728. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33729. * .toBe('');
  33730. *
  33731. * container.element(by.buttonText('add')).click();
  33732. *
  33733. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  33734. * .element(by.model('contact.value'))
  33735. * .getAttribute('value'))
  33736. * .toBe('yourname@example.org');
  33737. * });
  33738. * </file>
  33739. * </example>
  33740. *
  33741. * This example demonstrates the "attach to `$scope`" style of controller.
  33742. *
  33743. * <example name="ngController" module="controllerExample">
  33744. * <file name="index.html">
  33745. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  33746. * <label>Name: <input type="text" ng-model="name"/></label>
  33747. * <button ng-click="greet()">greet</button><br/>
  33748. * Contact:
  33749. * <ul>
  33750. * <li ng-repeat="contact in contacts">
  33751. * <select ng-model="contact.type" id="select_{{$index}}">
  33752. * <option>phone</option>
  33753. * <option>email</option>
  33754. * </select>
  33755. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  33756. * <button ng-click="clearContact(contact)">clear</button>
  33757. * <button ng-click="removeContact(contact)">X</button>
  33758. * </li>
  33759. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  33760. * </ul>
  33761. * </div>
  33762. * </file>
  33763. * <file name="app.js">
  33764. * angular.module('controllerExample', [])
  33765. * .controller('SettingsController2', ['$scope', SettingsController2]);
  33766. *
  33767. * function SettingsController2($scope) {
  33768. * $scope.name = "John Smith";
  33769. * $scope.contacts = [
  33770. * {type:'phone', value:'408 555 1212'},
  33771. * {type:'email', value:'john.smith@example.org'} ];
  33772. *
  33773. * $scope.greet = function() {
  33774. * alert($scope.name);
  33775. * };
  33776. *
  33777. * $scope.addContact = function() {
  33778. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  33779. * };
  33780. *
  33781. * $scope.removeContact = function(contactToRemove) {
  33782. * var index = $scope.contacts.indexOf(contactToRemove);
  33783. * $scope.contacts.splice(index, 1);
  33784. * };
  33785. *
  33786. * $scope.clearContact = function(contact) {
  33787. * contact.type = 'phone';
  33788. * contact.value = '';
  33789. * };
  33790. * }
  33791. * </file>
  33792. * <file name="protractor.js" type="protractor">
  33793. * it('should check controller', function() {
  33794. * var container = element(by.id('ctrl-exmpl'));
  33795. *
  33796. * expect(container.element(by.model('name'))
  33797. * .getAttribute('value')).toBe('John Smith');
  33798. *
  33799. * var firstRepeat =
  33800. * container.element(by.repeater('contact in contacts').row(0));
  33801. * var secondRepeat =
  33802. * container.element(by.repeater('contact in contacts').row(1));
  33803. *
  33804. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33805. * .toBe('408 555 1212');
  33806. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  33807. * .toBe('john.smith@example.org');
  33808. *
  33809. * firstRepeat.element(by.buttonText('clear')).click();
  33810. *
  33811. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33812. * .toBe('');
  33813. *
  33814. * container.element(by.buttonText('add')).click();
  33815. *
  33816. * expect(container.element(by.repeater('contact in contacts').row(2))
  33817. * .element(by.model('contact.value'))
  33818. * .getAttribute('value'))
  33819. * .toBe('yourname@example.org');
  33820. * });
  33821. * </file>
  33822. *</example>
  33823. */
  33824. var ngControllerDirective = [function() {
  33825. return {
  33826. restrict: 'A',
  33827. scope: true,
  33828. controller: '@',
  33829. priority: 500
  33830. };
  33831. }];
  33832. /**
  33833. * @ngdoc directive
  33834. * @name ngCsp
  33835. *
  33836. * @element html
  33837. * @description
  33838. *
  33839. * Angular has some features that can break certain
  33840. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  33841. *
  33842. * If you intend to implement these rules then you must tell Angular not to use these features.
  33843. *
  33844. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  33845. *
  33846. *
  33847. * The following rules affect Angular:
  33848. *
  33849. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  33850. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  33851. * increase in the speed of evaluating Angular expressions.
  33852. *
  33853. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  33854. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  33855. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  33856. * `angular-csp.css` in your HTML manually.
  33857. *
  33858. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  33859. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  33860. * however, triggers a CSP error to be logged in the console:
  33861. *
  33862. * ```
  33863. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  33864. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  33865. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  33866. * ```
  33867. *
  33868. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  33869. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  33870. * the `angular.js` file.
  33871. *
  33872. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  33873. *
  33874. * You can specify which of the CSP related Angular features should be deactivated by providing
  33875. * a value for the `ng-csp` attribute. The options are as follows:
  33876. *
  33877. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  33878. *
  33879. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  33880. *
  33881. * You can use these values in the following combinations:
  33882. *
  33883. *
  33884. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  33885. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  33886. * of Angular.
  33887. *
  33888. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  33889. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  33890. * of Angular.
  33891. *
  33892. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  33893. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  33894. *
  33895. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  33896. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  33897. *
  33898. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  33899. * styles nor use eval, which is the same as an empty: ng-csp.
  33900. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  33901. *
  33902. * @example
  33903. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  33904. ```html
  33905. <!doctype html>
  33906. <html ng-app ng-csp>
  33907. ...
  33908. ...
  33909. </html>
  33910. ```
  33911. * @example
  33912. // Note: the suffix `.csp` in the example name triggers
  33913. // csp mode in our http server!
  33914. <example name="example.csp" module="cspExample" ng-csp="true">
  33915. <file name="index.html">
  33916. <div ng-controller="MainController as ctrl">
  33917. <div>
  33918. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  33919. <span id="counter">
  33920. {{ctrl.counter}}
  33921. </span>
  33922. </div>
  33923. <div>
  33924. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  33925. <span id="evilError">
  33926. {{ctrl.evilError}}
  33927. </span>
  33928. </div>
  33929. </div>
  33930. </file>
  33931. <file name="script.js">
  33932. angular.module('cspExample', [])
  33933. .controller('MainController', function() {
  33934. this.counter = 0;
  33935. this.inc = function() {
  33936. this.counter++;
  33937. };
  33938. this.evil = function() {
  33939. // jshint evil:true
  33940. try {
  33941. eval('1+2');
  33942. } catch (e) {
  33943. this.evilError = e.message;
  33944. }
  33945. };
  33946. });
  33947. </file>
  33948. <file name="protractor.js" type="protractor">
  33949. var util, webdriver;
  33950. var incBtn = element(by.id('inc'));
  33951. var counter = element(by.id('counter'));
  33952. var evilBtn = element(by.id('evil'));
  33953. var evilError = element(by.id('evilError'));
  33954. function getAndClearSevereErrors() {
  33955. return browser.manage().logs().get('browser').then(function(browserLog) {
  33956. return browserLog.filter(function(logEntry) {
  33957. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  33958. });
  33959. });
  33960. }
  33961. function clearErrors() {
  33962. getAndClearSevereErrors();
  33963. }
  33964. function expectNoErrors() {
  33965. getAndClearSevereErrors().then(function(filteredLog) {
  33966. expect(filteredLog.length).toEqual(0);
  33967. if (filteredLog.length) {
  33968. console.log('browser console errors: ' + util.inspect(filteredLog));
  33969. }
  33970. });
  33971. }
  33972. function expectError(regex) {
  33973. getAndClearSevereErrors().then(function(filteredLog) {
  33974. var found = false;
  33975. filteredLog.forEach(function(log) {
  33976. if (log.message.match(regex)) {
  33977. found = true;
  33978. }
  33979. });
  33980. if (!found) {
  33981. throw new Error('expected an error that matches ' + regex);
  33982. }
  33983. });
  33984. }
  33985. beforeEach(function() {
  33986. util = require('util');
  33987. webdriver = require('protractor/node_modules/selenium-webdriver');
  33988. });
  33989. // For now, we only test on Chrome,
  33990. // as Safari does not load the page with Protractor's injected scripts,
  33991. // and Firefox webdriver always disables content security policy (#6358)
  33992. if (browser.params.browser !== 'chrome') {
  33993. return;
  33994. }
  33995. it('should not report errors when the page is loaded', function() {
  33996. // clear errors so we are not dependent on previous tests
  33997. clearErrors();
  33998. // Need to reload the page as the page is already loaded when
  33999. // we come here
  34000. browser.driver.getCurrentUrl().then(function(url) {
  34001. browser.get(url);
  34002. });
  34003. expectNoErrors();
  34004. });
  34005. it('should evaluate expressions', function() {
  34006. expect(counter.getText()).toEqual('0');
  34007. incBtn.click();
  34008. expect(counter.getText()).toEqual('1');
  34009. expectNoErrors();
  34010. });
  34011. it('should throw and report an error when using "eval"', function() {
  34012. evilBtn.click();
  34013. expect(evilError.getText()).toMatch(/Content Security Policy/);
  34014. expectError(/Content Security Policy/);
  34015. });
  34016. </file>
  34017. </example>
  34018. */
  34019. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  34020. // bootstrap the system (before $parse is instantiated), for this reason we just have
  34021. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  34022. /**
  34023. * @ngdoc directive
  34024. * @name ngClick
  34025. *
  34026. * @description
  34027. * The ngClick directive allows you to specify custom behavior when
  34028. * an element is clicked.
  34029. *
  34030. * @element ANY
  34031. * @priority 0
  34032. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  34033. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  34034. *
  34035. * @example
  34036. <example>
  34037. <file name="index.html">
  34038. <button ng-click="count = count + 1" ng-init="count=0">
  34039. Increment
  34040. </button>
  34041. <span>
  34042. count: {{count}}
  34043. </span>
  34044. </file>
  34045. <file name="protractor.js" type="protractor">
  34046. it('should check ng-click', function() {
  34047. expect(element(by.binding('count')).getText()).toMatch('0');
  34048. element(by.css('button')).click();
  34049. expect(element(by.binding('count')).getText()).toMatch('1');
  34050. });
  34051. </file>
  34052. </example>
  34053. */
  34054. /*
  34055. * A collection of directives that allows creation of custom event handlers that are defined as
  34056. * angular expressions and are compiled and executed within the current scope.
  34057. */
  34058. var ngEventDirectives = {};
  34059. // For events that might fire synchronously during DOM manipulation
  34060. // we need to execute their event handlers asynchronously using $evalAsync,
  34061. // so that they are not executed in an inconsistent state.
  34062. var forceAsyncEvents = {
  34063. 'blur': true,
  34064. 'focus': true
  34065. };
  34066. forEach(
  34067. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  34068. function(eventName) {
  34069. var directiveName = directiveNormalize('ng-' + eventName);
  34070. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  34071. return {
  34072. restrict: 'A',
  34073. compile: function($element, attr) {
  34074. // We expose the powerful $event object on the scope that provides access to the Window,
  34075. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  34076. // checks at the cost of speed since event handler expressions are not executed as
  34077. // frequently as regular change detection.
  34078. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  34079. return function ngEventHandler(scope, element) {
  34080. element.on(eventName, function(event) {
  34081. var callback = function() {
  34082. fn(scope, {$event:event});
  34083. };
  34084. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  34085. scope.$evalAsync(callback);
  34086. } else {
  34087. scope.$apply(callback);
  34088. }
  34089. });
  34090. };
  34091. }
  34092. };
  34093. }];
  34094. }
  34095. );
  34096. /**
  34097. * @ngdoc directive
  34098. * @name ngDblclick
  34099. *
  34100. * @description
  34101. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  34102. *
  34103. * @element ANY
  34104. * @priority 0
  34105. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  34106. * a dblclick. (The Event object is available as `$event`)
  34107. *
  34108. * @example
  34109. <example>
  34110. <file name="index.html">
  34111. <button ng-dblclick="count = count + 1" ng-init="count=0">
  34112. Increment (on double click)
  34113. </button>
  34114. count: {{count}}
  34115. </file>
  34116. </example>
  34117. */
  34118. /**
  34119. * @ngdoc directive
  34120. * @name ngMousedown
  34121. *
  34122. * @description
  34123. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  34124. *
  34125. * @element ANY
  34126. * @priority 0
  34127. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  34128. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  34129. *
  34130. * @example
  34131. <example>
  34132. <file name="index.html">
  34133. <button ng-mousedown="count = count + 1" ng-init="count=0">
  34134. Increment (on mouse down)
  34135. </button>
  34136. count: {{count}}
  34137. </file>
  34138. </example>
  34139. */
  34140. /**
  34141. * @ngdoc directive
  34142. * @name ngMouseup
  34143. *
  34144. * @description
  34145. * Specify custom behavior on mouseup event.
  34146. *
  34147. * @element ANY
  34148. * @priority 0
  34149. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  34150. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  34151. *
  34152. * @example
  34153. <example>
  34154. <file name="index.html">
  34155. <button ng-mouseup="count = count + 1" ng-init="count=0">
  34156. Increment (on mouse up)
  34157. </button>
  34158. count: {{count}}
  34159. </file>
  34160. </example>
  34161. */
  34162. /**
  34163. * @ngdoc directive
  34164. * @name ngMouseover
  34165. *
  34166. * @description
  34167. * Specify custom behavior on mouseover event.
  34168. *
  34169. * @element ANY
  34170. * @priority 0
  34171. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  34172. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  34173. *
  34174. * @example
  34175. <example>
  34176. <file name="index.html">
  34177. <button ng-mouseover="count = count + 1" ng-init="count=0">
  34178. Increment (when mouse is over)
  34179. </button>
  34180. count: {{count}}
  34181. </file>
  34182. </example>
  34183. */
  34184. /**
  34185. * @ngdoc directive
  34186. * @name ngMouseenter
  34187. *
  34188. * @description
  34189. * Specify custom behavior on mouseenter event.
  34190. *
  34191. * @element ANY
  34192. * @priority 0
  34193. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  34194. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  34195. *
  34196. * @example
  34197. <example>
  34198. <file name="index.html">
  34199. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  34200. Increment (when mouse enters)
  34201. </button>
  34202. count: {{count}}
  34203. </file>
  34204. </example>
  34205. */
  34206. /**
  34207. * @ngdoc directive
  34208. * @name ngMouseleave
  34209. *
  34210. * @description
  34211. * Specify custom behavior on mouseleave event.
  34212. *
  34213. * @element ANY
  34214. * @priority 0
  34215. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  34216. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  34217. *
  34218. * @example
  34219. <example>
  34220. <file name="index.html">
  34221. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  34222. Increment (when mouse leaves)
  34223. </button>
  34224. count: {{count}}
  34225. </file>
  34226. </example>
  34227. */
  34228. /**
  34229. * @ngdoc directive
  34230. * @name ngMousemove
  34231. *
  34232. * @description
  34233. * Specify custom behavior on mousemove event.
  34234. *
  34235. * @element ANY
  34236. * @priority 0
  34237. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  34238. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  34239. *
  34240. * @example
  34241. <example>
  34242. <file name="index.html">
  34243. <button ng-mousemove="count = count + 1" ng-init="count=0">
  34244. Increment (when mouse moves)
  34245. </button>
  34246. count: {{count}}
  34247. </file>
  34248. </example>
  34249. */
  34250. /**
  34251. * @ngdoc directive
  34252. * @name ngKeydown
  34253. *
  34254. * @description
  34255. * Specify custom behavior on keydown event.
  34256. *
  34257. * @element ANY
  34258. * @priority 0
  34259. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  34260. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  34261. *
  34262. * @example
  34263. <example>
  34264. <file name="index.html">
  34265. <input ng-keydown="count = count + 1" ng-init="count=0">
  34266. key down count: {{count}}
  34267. </file>
  34268. </example>
  34269. */
  34270. /**
  34271. * @ngdoc directive
  34272. * @name ngKeyup
  34273. *
  34274. * @description
  34275. * Specify custom behavior on keyup event.
  34276. *
  34277. * @element ANY
  34278. * @priority 0
  34279. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  34280. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  34281. *
  34282. * @example
  34283. <example>
  34284. <file name="index.html">
  34285. <p>Typing in the input box below updates the key count</p>
  34286. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  34287. <p>Typing in the input box below updates the keycode</p>
  34288. <input ng-keyup="event=$event">
  34289. <p>event keyCode: {{ event.keyCode }}</p>
  34290. <p>event altKey: {{ event.altKey }}</p>
  34291. </file>
  34292. </example>
  34293. */
  34294. /**
  34295. * @ngdoc directive
  34296. * @name ngKeypress
  34297. *
  34298. * @description
  34299. * Specify custom behavior on keypress event.
  34300. *
  34301. * @element ANY
  34302. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  34303. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  34304. * and can be interrogated for keyCode, altKey, etc.)
  34305. *
  34306. * @example
  34307. <example>
  34308. <file name="index.html">
  34309. <input ng-keypress="count = count + 1" ng-init="count=0">
  34310. key press count: {{count}}
  34311. </file>
  34312. </example>
  34313. */
  34314. /**
  34315. * @ngdoc directive
  34316. * @name ngSubmit
  34317. *
  34318. * @description
  34319. * Enables binding angular expressions to onsubmit events.
  34320. *
  34321. * Additionally it prevents the default action (which for form means sending the request to the
  34322. * server and reloading the current page), but only if the form does not contain `action`,
  34323. * `data-action`, or `x-action` attributes.
  34324. *
  34325. * <div class="alert alert-warning">
  34326. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  34327. * `ngSubmit` handlers together. See the
  34328. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  34329. * for a detailed discussion of when `ngSubmit` may be triggered.
  34330. * </div>
  34331. *
  34332. * @element form
  34333. * @priority 0
  34334. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  34335. * ({@link guide/expression#-event- Event object is available as `$event`})
  34336. *
  34337. * @example
  34338. <example module="submitExample">
  34339. <file name="index.html">
  34340. <script>
  34341. angular.module('submitExample', [])
  34342. .controller('ExampleController', ['$scope', function($scope) {
  34343. $scope.list = [];
  34344. $scope.text = 'hello';
  34345. $scope.submit = function() {
  34346. if ($scope.text) {
  34347. $scope.list.push(this.text);
  34348. $scope.text = '';
  34349. }
  34350. };
  34351. }]);
  34352. </script>
  34353. <form ng-submit="submit()" ng-controller="ExampleController">
  34354. Enter text and hit enter:
  34355. <input type="text" ng-model="text" name="text" />
  34356. <input type="submit" id="submit" value="Submit" />
  34357. <pre>list={{list}}</pre>
  34358. </form>
  34359. </file>
  34360. <file name="protractor.js" type="protractor">
  34361. it('should check ng-submit', function() {
  34362. expect(element(by.binding('list')).getText()).toBe('list=[]');
  34363. element(by.css('#submit')).click();
  34364. expect(element(by.binding('list')).getText()).toContain('hello');
  34365. expect(element(by.model('text')).getAttribute('value')).toBe('');
  34366. });
  34367. it('should ignore empty strings', function() {
  34368. expect(element(by.binding('list')).getText()).toBe('list=[]');
  34369. element(by.css('#submit')).click();
  34370. element(by.css('#submit')).click();
  34371. expect(element(by.binding('list')).getText()).toContain('hello');
  34372. });
  34373. </file>
  34374. </example>
  34375. */
  34376. /**
  34377. * @ngdoc directive
  34378. * @name ngFocus
  34379. *
  34380. * @description
  34381. * Specify custom behavior on focus event.
  34382. *
  34383. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  34384. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  34385. * during an `$apply` to ensure a consistent state.
  34386. *
  34387. * @element window, input, select, textarea, a
  34388. * @priority 0
  34389. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  34390. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  34391. *
  34392. * @example
  34393. * See {@link ng.directive:ngClick ngClick}
  34394. */
  34395. /**
  34396. * @ngdoc directive
  34397. * @name ngBlur
  34398. *
  34399. * @description
  34400. * Specify custom behavior on blur event.
  34401. *
  34402. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  34403. * an element has lost focus.
  34404. *
  34405. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  34406. * (e.g. removing a focussed input),
  34407. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  34408. * during an `$apply` to ensure a consistent state.
  34409. *
  34410. * @element window, input, select, textarea, a
  34411. * @priority 0
  34412. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  34413. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  34414. *
  34415. * @example
  34416. * See {@link ng.directive:ngClick ngClick}
  34417. */
  34418. /**
  34419. * @ngdoc directive
  34420. * @name ngCopy
  34421. *
  34422. * @description
  34423. * Specify custom behavior on copy event.
  34424. *
  34425. * @element window, input, select, textarea, a
  34426. * @priority 0
  34427. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  34428. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  34429. *
  34430. * @example
  34431. <example>
  34432. <file name="index.html">
  34433. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  34434. copied: {{copied}}
  34435. </file>
  34436. </example>
  34437. */
  34438. /**
  34439. * @ngdoc directive
  34440. * @name ngCut
  34441. *
  34442. * @description
  34443. * Specify custom behavior on cut event.
  34444. *
  34445. * @element window, input, select, textarea, a
  34446. * @priority 0
  34447. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  34448. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  34449. *
  34450. * @example
  34451. <example>
  34452. <file name="index.html">
  34453. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  34454. cut: {{cut}}
  34455. </file>
  34456. </example>
  34457. */
  34458. /**
  34459. * @ngdoc directive
  34460. * @name ngPaste
  34461. *
  34462. * @description
  34463. * Specify custom behavior on paste event.
  34464. *
  34465. * @element window, input, select, textarea, a
  34466. * @priority 0
  34467. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  34468. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  34469. *
  34470. * @example
  34471. <example>
  34472. <file name="index.html">
  34473. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  34474. pasted: {{paste}}
  34475. </file>
  34476. </example>
  34477. */
  34478. /**
  34479. * @ngdoc directive
  34480. * @name ngIf
  34481. * @restrict A
  34482. * @multiElement
  34483. *
  34484. * @description
  34485. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  34486. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  34487. * value then the element is removed from the DOM, otherwise a clone of the
  34488. * element is reinserted into the DOM.
  34489. *
  34490. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  34491. * element in the DOM rather than changing its visibility via the `display` css property. A common
  34492. * case when this difference is significant is when using css selectors that rely on an element's
  34493. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  34494. *
  34495. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  34496. * is created when the element is restored. The scope created within `ngIf` inherits from
  34497. * its parent scope using
  34498. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  34499. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  34500. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  34501. * variable within the child scope will override (hide) the value in the parent scope.
  34502. *
  34503. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  34504. * is if an element's class attribute is directly modified after it's compiled, using something like
  34505. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  34506. * the added class will be lost because the original compiled state is used to regenerate the element.
  34507. *
  34508. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  34509. * and `leave` effects.
  34510. *
  34511. * @animations
  34512. * | Animation | Occurs |
  34513. * |----------------------------------|-------------------------------------|
  34514. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  34515. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  34516. *
  34517. * @element ANY
  34518. * @scope
  34519. * @priority 600
  34520. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  34521. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  34522. * element is added to the DOM tree.
  34523. *
  34524. * @example
  34525. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  34526. <file name="index.html">
  34527. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  34528. Show when checked:
  34529. <span ng-if="checked" class="animate-if">
  34530. This is removed when the checkbox is unchecked.
  34531. </span>
  34532. </file>
  34533. <file name="animations.css">
  34534. .animate-if {
  34535. background:white;
  34536. border:1px solid black;
  34537. padding:10px;
  34538. }
  34539. .animate-if.ng-enter, .animate-if.ng-leave {
  34540. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  34541. }
  34542. .animate-if.ng-enter,
  34543. .animate-if.ng-leave.ng-leave-active {
  34544. opacity:0;
  34545. }
  34546. .animate-if.ng-leave,
  34547. .animate-if.ng-enter.ng-enter-active {
  34548. opacity:1;
  34549. }
  34550. </file>
  34551. </example>
  34552. */
  34553. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  34554. return {
  34555. multiElement: true,
  34556. transclude: 'element',
  34557. priority: 600,
  34558. terminal: true,
  34559. restrict: 'A',
  34560. $$tlb: true,
  34561. link: function($scope, $element, $attr, ctrl, $transclude) {
  34562. var block, childScope, previousElements;
  34563. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  34564. if (value) {
  34565. if (!childScope) {
  34566. $transclude(function(clone, newScope) {
  34567. childScope = newScope;
  34568. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  34569. // Note: We only need the first/last node of the cloned nodes.
  34570. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  34571. // by a directive with templateUrl when its template arrives.
  34572. block = {
  34573. clone: clone
  34574. };
  34575. $animate.enter(clone, $element.parent(), $element);
  34576. });
  34577. }
  34578. } else {
  34579. if (previousElements) {
  34580. previousElements.remove();
  34581. previousElements = null;
  34582. }
  34583. if (childScope) {
  34584. childScope.$destroy();
  34585. childScope = null;
  34586. }
  34587. if (block) {
  34588. previousElements = getBlockNodes(block.clone);
  34589. $animate.leave(previousElements).then(function() {
  34590. previousElements = null;
  34591. });
  34592. block = null;
  34593. }
  34594. }
  34595. });
  34596. }
  34597. };
  34598. }];
  34599. /**
  34600. * @ngdoc directive
  34601. * @name ngInclude
  34602. * @restrict ECA
  34603. *
  34604. * @description
  34605. * Fetches, compiles and includes an external HTML fragment.
  34606. *
  34607. * By default, the template URL is restricted to the same domain and protocol as the
  34608. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  34609. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  34610. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  34611. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  34612. * ng.$sce Strict Contextual Escaping}.
  34613. *
  34614. * In addition, the browser's
  34615. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  34616. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  34617. * policy may further restrict whether the template is successfully loaded.
  34618. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  34619. * access on some browsers.
  34620. *
  34621. * @animations
  34622. * | Animation | Occurs |
  34623. * |----------------------------------|-------------------------------------|
  34624. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  34625. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  34626. *
  34627. * The enter and leave animation occur concurrently.
  34628. *
  34629. * @scope
  34630. * @priority 400
  34631. *
  34632. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  34633. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  34634. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  34635. * <div class="alert alert-warning">
  34636. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  34637. * a function with the name on the window element, which will usually throw a
  34638. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  34639. * different form that {@link guide/directive#normalization matches} `onload`.
  34640. * </div>
  34641. *
  34642. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  34643. * $anchorScroll} to scroll the viewport after the content is loaded.
  34644. *
  34645. * - If the attribute is not set, disable scrolling.
  34646. * - If the attribute is set without value, enable scrolling.
  34647. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  34648. *
  34649. * @example
  34650. <example module="includeExample" deps="angular-animate.js" animations="true">
  34651. <file name="index.html">
  34652. <div ng-controller="ExampleController">
  34653. <select ng-model="template" ng-options="t.name for t in templates">
  34654. <option value="">(blank)</option>
  34655. </select>
  34656. url of the template: <code>{{template.url}}</code>
  34657. <hr/>
  34658. <div class="slide-animate-container">
  34659. <div class="slide-animate" ng-include="template.url"></div>
  34660. </div>
  34661. </div>
  34662. </file>
  34663. <file name="script.js">
  34664. angular.module('includeExample', ['ngAnimate'])
  34665. .controller('ExampleController', ['$scope', function($scope) {
  34666. $scope.templates =
  34667. [ { name: 'template1.html', url: 'template1.html'},
  34668. { name: 'template2.html', url: 'template2.html'} ];
  34669. $scope.template = $scope.templates[0];
  34670. }]);
  34671. </file>
  34672. <file name="template1.html">
  34673. Content of template1.html
  34674. </file>
  34675. <file name="template2.html">
  34676. Content of template2.html
  34677. </file>
  34678. <file name="animations.css">
  34679. .slide-animate-container {
  34680. position:relative;
  34681. background:white;
  34682. border:1px solid black;
  34683. height:40px;
  34684. overflow:hidden;
  34685. }
  34686. .slide-animate {
  34687. padding:10px;
  34688. }
  34689. .slide-animate.ng-enter, .slide-animate.ng-leave {
  34690. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  34691. position:absolute;
  34692. top:0;
  34693. left:0;
  34694. right:0;
  34695. bottom:0;
  34696. display:block;
  34697. padding:10px;
  34698. }
  34699. .slide-animate.ng-enter {
  34700. top:-50px;
  34701. }
  34702. .slide-animate.ng-enter.ng-enter-active {
  34703. top:0;
  34704. }
  34705. .slide-animate.ng-leave {
  34706. top:0;
  34707. }
  34708. .slide-animate.ng-leave.ng-leave-active {
  34709. top:50px;
  34710. }
  34711. </file>
  34712. <file name="protractor.js" type="protractor">
  34713. var templateSelect = element(by.model('template'));
  34714. var includeElem = element(by.css('[ng-include]'));
  34715. it('should load template1.html', function() {
  34716. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  34717. });
  34718. it('should load template2.html', function() {
  34719. if (browser.params.browser == 'firefox') {
  34720. // Firefox can't handle using selects
  34721. // See https://github.com/angular/protractor/issues/480
  34722. return;
  34723. }
  34724. templateSelect.click();
  34725. templateSelect.all(by.css('option')).get(2).click();
  34726. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  34727. });
  34728. it('should change to blank', function() {
  34729. if (browser.params.browser == 'firefox') {
  34730. // Firefox can't handle using selects
  34731. return;
  34732. }
  34733. templateSelect.click();
  34734. templateSelect.all(by.css('option')).get(0).click();
  34735. expect(includeElem.isPresent()).toBe(false);
  34736. });
  34737. </file>
  34738. </example>
  34739. */
  34740. /**
  34741. * @ngdoc event
  34742. * @name ngInclude#$includeContentRequested
  34743. * @eventType emit on the scope ngInclude was declared in
  34744. * @description
  34745. * Emitted every time the ngInclude content is requested.
  34746. *
  34747. * @param {Object} angularEvent Synthetic event object.
  34748. * @param {String} src URL of content to load.
  34749. */
  34750. /**
  34751. * @ngdoc event
  34752. * @name ngInclude#$includeContentLoaded
  34753. * @eventType emit on the current ngInclude scope
  34754. * @description
  34755. * Emitted every time the ngInclude content is reloaded.
  34756. *
  34757. * @param {Object} angularEvent Synthetic event object.
  34758. * @param {String} src URL of content to load.
  34759. */
  34760. /**
  34761. * @ngdoc event
  34762. * @name ngInclude#$includeContentError
  34763. * @eventType emit on the scope ngInclude was declared in
  34764. * @description
  34765. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  34766. *
  34767. * @param {Object} angularEvent Synthetic event object.
  34768. * @param {String} src URL of content to load.
  34769. */
  34770. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  34771. function($templateRequest, $anchorScroll, $animate) {
  34772. return {
  34773. restrict: 'ECA',
  34774. priority: 400,
  34775. terminal: true,
  34776. transclude: 'element',
  34777. controller: angular.noop,
  34778. compile: function(element, attr) {
  34779. var srcExp = attr.ngInclude || attr.src,
  34780. onloadExp = attr.onload || '',
  34781. autoScrollExp = attr.autoscroll;
  34782. return function(scope, $element, $attr, ctrl, $transclude) {
  34783. var changeCounter = 0,
  34784. currentScope,
  34785. previousElement,
  34786. currentElement;
  34787. var cleanupLastIncludeContent = function() {
  34788. if (previousElement) {
  34789. previousElement.remove();
  34790. previousElement = null;
  34791. }
  34792. if (currentScope) {
  34793. currentScope.$destroy();
  34794. currentScope = null;
  34795. }
  34796. if (currentElement) {
  34797. $animate.leave(currentElement).then(function() {
  34798. previousElement = null;
  34799. });
  34800. previousElement = currentElement;
  34801. currentElement = null;
  34802. }
  34803. };
  34804. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  34805. var afterAnimation = function() {
  34806. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  34807. $anchorScroll();
  34808. }
  34809. };
  34810. var thisChangeId = ++changeCounter;
  34811. if (src) {
  34812. //set the 2nd param to true to ignore the template request error so that the inner
  34813. //contents and scope can be cleaned up.
  34814. $templateRequest(src, true).then(function(response) {
  34815. if (scope.$$destroyed) return;
  34816. if (thisChangeId !== changeCounter) return;
  34817. var newScope = scope.$new();
  34818. ctrl.template = response;
  34819. // Note: This will also link all children of ng-include that were contained in the original
  34820. // html. If that content contains controllers, ... they could pollute/change the scope.
  34821. // However, using ng-include on an element with additional content does not make sense...
  34822. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  34823. // function is called before linking the content, which would apply child
  34824. // directives to non existing elements.
  34825. var clone = $transclude(newScope, function(clone) {
  34826. cleanupLastIncludeContent();
  34827. $animate.enter(clone, null, $element).then(afterAnimation);
  34828. });
  34829. currentScope = newScope;
  34830. currentElement = clone;
  34831. currentScope.$emit('$includeContentLoaded', src);
  34832. scope.$eval(onloadExp);
  34833. }, function() {
  34834. if (scope.$$destroyed) return;
  34835. if (thisChangeId === changeCounter) {
  34836. cleanupLastIncludeContent();
  34837. scope.$emit('$includeContentError', src);
  34838. }
  34839. });
  34840. scope.$emit('$includeContentRequested', src);
  34841. } else {
  34842. cleanupLastIncludeContent();
  34843. ctrl.template = null;
  34844. }
  34845. });
  34846. };
  34847. }
  34848. };
  34849. }];
  34850. // This directive is called during the $transclude call of the first `ngInclude` directive.
  34851. // It will replace and compile the content of the element with the loaded template.
  34852. // We need this directive so that the element content is already filled when
  34853. // the link function of another directive on the same element as ngInclude
  34854. // is called.
  34855. var ngIncludeFillContentDirective = ['$compile',
  34856. function($compile) {
  34857. return {
  34858. restrict: 'ECA',
  34859. priority: -400,
  34860. require: 'ngInclude',
  34861. link: function(scope, $element, $attr, ctrl) {
  34862. if (toString.call($element[0]).match(/SVG/)) {
  34863. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  34864. // support innerHTML, so detect this here and try to generate the contents
  34865. // specially.
  34866. $element.empty();
  34867. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  34868. function namespaceAdaptedClone(clone) {
  34869. $element.append(clone);
  34870. }, {futureParentElement: $element});
  34871. return;
  34872. }
  34873. $element.html(ctrl.template);
  34874. $compile($element.contents())(scope);
  34875. }
  34876. };
  34877. }];
  34878. /**
  34879. * @ngdoc directive
  34880. * @name ngInit
  34881. * @restrict AC
  34882. *
  34883. * @description
  34884. * The `ngInit` directive allows you to evaluate an expression in the
  34885. * current scope.
  34886. *
  34887. * <div class="alert alert-danger">
  34888. * This directive can be abused to add unnecessary amounts of logic into your templates.
  34889. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  34890. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  34891. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  34892. * rather than `ngInit` to initialize values on a scope.
  34893. * </div>
  34894. *
  34895. * <div class="alert alert-warning">
  34896. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  34897. * sure you have parentheses to ensure correct operator precedence:
  34898. * <pre class="prettyprint">
  34899. * `<div ng-init="test1 = ($index | toString)"></div>`
  34900. * </pre>
  34901. * </div>
  34902. *
  34903. * @priority 450
  34904. *
  34905. * @element ANY
  34906. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  34907. *
  34908. * @example
  34909. <example module="initExample">
  34910. <file name="index.html">
  34911. <script>
  34912. angular.module('initExample', [])
  34913. .controller('ExampleController', ['$scope', function($scope) {
  34914. $scope.list = [['a', 'b'], ['c', 'd']];
  34915. }]);
  34916. </script>
  34917. <div ng-controller="ExampleController">
  34918. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  34919. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  34920. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  34921. </div>
  34922. </div>
  34923. </div>
  34924. </file>
  34925. <file name="protractor.js" type="protractor">
  34926. it('should alias index positions', function() {
  34927. var elements = element.all(by.css('.example-init'));
  34928. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  34929. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  34930. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  34931. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  34932. });
  34933. </file>
  34934. </example>
  34935. */
  34936. var ngInitDirective = ngDirective({
  34937. priority: 450,
  34938. compile: function() {
  34939. return {
  34940. pre: function(scope, element, attrs) {
  34941. scope.$eval(attrs.ngInit);
  34942. }
  34943. };
  34944. }
  34945. });
  34946. /**
  34947. * @ngdoc directive
  34948. * @name ngList
  34949. *
  34950. * @description
  34951. * Text input that converts between a delimited string and an array of strings. The default
  34952. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  34953. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  34954. *
  34955. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  34956. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  34957. * list item is respected. This implies that the user of the directive is responsible for
  34958. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  34959. * tab or newline character.
  34960. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  34961. * when joining the list items back together) and whitespace around each list item is stripped
  34962. * before it is added to the model.
  34963. *
  34964. * ### Example with Validation
  34965. *
  34966. * <example name="ngList-directive" module="listExample">
  34967. * <file name="app.js">
  34968. * angular.module('listExample', [])
  34969. * .controller('ExampleController', ['$scope', function($scope) {
  34970. * $scope.names = ['morpheus', 'neo', 'trinity'];
  34971. * }]);
  34972. * </file>
  34973. * <file name="index.html">
  34974. * <form name="myForm" ng-controller="ExampleController">
  34975. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  34976. * <span role="alert">
  34977. * <span class="error" ng-show="myForm.namesInput.$error.required">
  34978. * Required!</span>
  34979. * </span>
  34980. * <br>
  34981. * <tt>names = {{names}}</tt><br/>
  34982. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  34983. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  34984. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  34985. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  34986. * </form>
  34987. * </file>
  34988. * <file name="protractor.js" type="protractor">
  34989. * var listInput = element(by.model('names'));
  34990. * var names = element(by.exactBinding('names'));
  34991. * var valid = element(by.binding('myForm.namesInput.$valid'));
  34992. * var error = element(by.css('span.error'));
  34993. *
  34994. * it('should initialize to model', function() {
  34995. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  34996. * expect(valid.getText()).toContain('true');
  34997. * expect(error.getCssValue('display')).toBe('none');
  34998. * });
  34999. *
  35000. * it('should be invalid if empty', function() {
  35001. * listInput.clear();
  35002. * listInput.sendKeys('');
  35003. *
  35004. * expect(names.getText()).toContain('');
  35005. * expect(valid.getText()).toContain('false');
  35006. * expect(error.getCssValue('display')).not.toBe('none');
  35007. * });
  35008. * </file>
  35009. * </example>
  35010. *
  35011. * ### Example - splitting on newline
  35012. * <example name="ngList-directive-newlines">
  35013. * <file name="index.html">
  35014. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  35015. * <pre>{{ list | json }}</pre>
  35016. * </file>
  35017. * <file name="protractor.js" type="protractor">
  35018. * it("should split the text by newlines", function() {
  35019. * var listInput = element(by.model('list'));
  35020. * var output = element(by.binding('list | json'));
  35021. * listInput.sendKeys('abc\ndef\nghi');
  35022. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  35023. * });
  35024. * </file>
  35025. * </example>
  35026. *
  35027. * @element input
  35028. * @param {string=} ngList optional delimiter that should be used to split the value.
  35029. */
  35030. var ngListDirective = function() {
  35031. return {
  35032. restrict: 'A',
  35033. priority: 100,
  35034. require: 'ngModel',
  35035. link: function(scope, element, attr, ctrl) {
  35036. // We want to control whitespace trimming so we use this convoluted approach
  35037. // to access the ngList attribute, which doesn't pre-trim the attribute
  35038. var ngList = element.attr(attr.$attr.ngList) || ', ';
  35039. var trimValues = attr.ngTrim !== 'false';
  35040. var separator = trimValues ? trim(ngList) : ngList;
  35041. var parse = function(viewValue) {
  35042. // If the viewValue is invalid (say required but empty) it will be `undefined`
  35043. if (isUndefined(viewValue)) return;
  35044. var list = [];
  35045. if (viewValue) {
  35046. forEach(viewValue.split(separator), function(value) {
  35047. if (value) list.push(trimValues ? trim(value) : value);
  35048. });
  35049. }
  35050. return list;
  35051. };
  35052. ctrl.$parsers.push(parse);
  35053. ctrl.$formatters.push(function(value) {
  35054. if (isArray(value)) {
  35055. return value.join(ngList);
  35056. }
  35057. return undefined;
  35058. });
  35059. // Override the standard $isEmpty because an empty array means the input is empty.
  35060. ctrl.$isEmpty = function(value) {
  35061. return !value || !value.length;
  35062. };
  35063. }
  35064. };
  35065. };
  35066. /* global VALID_CLASS: true,
  35067. INVALID_CLASS: true,
  35068. PRISTINE_CLASS: true,
  35069. DIRTY_CLASS: true,
  35070. UNTOUCHED_CLASS: true,
  35071. TOUCHED_CLASS: true,
  35072. */
  35073. var VALID_CLASS = 'ng-valid',
  35074. INVALID_CLASS = 'ng-invalid',
  35075. PRISTINE_CLASS = 'ng-pristine',
  35076. DIRTY_CLASS = 'ng-dirty',
  35077. UNTOUCHED_CLASS = 'ng-untouched',
  35078. TOUCHED_CLASS = 'ng-touched',
  35079. PENDING_CLASS = 'ng-pending',
  35080. EMPTY_CLASS = 'ng-empty',
  35081. NOT_EMPTY_CLASS = 'ng-not-empty';
  35082. var ngModelMinErr = minErr('ngModel');
  35083. /**
  35084. * @ngdoc type
  35085. * @name ngModel.NgModelController
  35086. *
  35087. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  35088. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  35089. * is set.
  35090. * @property {*} $modelValue The value in the model that the control is bound to.
  35091. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  35092. the control reads value from the DOM. The functions are called in array order, each passing
  35093. its return value through to the next. The last return value is forwarded to the
  35094. {@link ngModel.NgModelController#$validators `$validators`} collection.
  35095. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  35096. `$viewValue`}.
  35097. Returning `undefined` from a parser means a parse error occurred. In that case,
  35098. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  35099. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  35100. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  35101. *
  35102. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  35103. the model value changes. The functions are called in reverse array order, each passing the value through to the
  35104. next. The last return value is used as the actual DOM value.
  35105. Used to format / convert values for display in the control.
  35106. * ```js
  35107. * function formatter(value) {
  35108. * if (value) {
  35109. * return value.toUpperCase();
  35110. * }
  35111. * }
  35112. * ngModel.$formatters.push(formatter);
  35113. * ```
  35114. *
  35115. * @property {Object.<string, function>} $validators A collection of validators that are applied
  35116. * whenever the model value changes. The key value within the object refers to the name of the
  35117. * validator while the function refers to the validation operation. The validation operation is
  35118. * provided with the model value as an argument and must return a true or false value depending
  35119. * on the response of that validation.
  35120. *
  35121. * ```js
  35122. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  35123. * var value = modelValue || viewValue;
  35124. * return /[0-9]+/.test(value) &&
  35125. * /[a-z]+/.test(value) &&
  35126. * /[A-Z]+/.test(value) &&
  35127. * /\W+/.test(value);
  35128. * };
  35129. * ```
  35130. *
  35131. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  35132. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  35133. * is expected to return a promise when it is run during the model validation process. Once the promise
  35134. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  35135. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  35136. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  35137. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  35138. * will only run once all synchronous validators have passed.
  35139. *
  35140. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  35141. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  35142. *
  35143. * ```js
  35144. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  35145. * var value = modelValue || viewValue;
  35146. *
  35147. * // Lookup user by username
  35148. * return $http.get('/api/users/' + value).
  35149. * then(function resolved() {
  35150. * //username exists, this means validation fails
  35151. * return $q.reject('exists');
  35152. * }, function rejected() {
  35153. * //username does not exist, therefore this validation passes
  35154. * return true;
  35155. * });
  35156. * };
  35157. * ```
  35158. *
  35159. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  35160. * view value has changed. It is called with no arguments, and its return value is ignored.
  35161. * This can be used in place of additional $watches against the model value.
  35162. *
  35163. * @property {Object} $error An object hash with all failing validator ids as keys.
  35164. * @property {Object} $pending An object hash with all pending validator ids as keys.
  35165. *
  35166. * @property {boolean} $untouched True if control has not lost focus yet.
  35167. * @property {boolean} $touched True if control has lost focus.
  35168. * @property {boolean} $pristine True if user has not interacted with the control yet.
  35169. * @property {boolean} $dirty True if user has already interacted with the control.
  35170. * @property {boolean} $valid True if there is no error.
  35171. * @property {boolean} $invalid True if at least one error on the control.
  35172. * @property {string} $name The name attribute of the control.
  35173. *
  35174. * @description
  35175. *
  35176. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  35177. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  35178. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  35179. * listening to DOM events.
  35180. * Such DOM related logic should be provided by other directives which make use of
  35181. * `NgModelController` for data-binding to control elements.
  35182. * Angular provides this DOM logic for most {@link input `input`} elements.
  35183. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  35184. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  35185. *
  35186. * @example
  35187. * ### Custom Control Example
  35188. * This example shows how to use `NgModelController` with a custom control to achieve
  35189. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  35190. * collaborate together to achieve the desired result.
  35191. *
  35192. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  35193. * contents be edited in place by the user.
  35194. *
  35195. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  35196. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  35197. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  35198. * that content using the `$sce` service.
  35199. *
  35200. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  35201. <file name="style.css">
  35202. [contenteditable] {
  35203. border: 1px solid black;
  35204. background-color: white;
  35205. min-height: 20px;
  35206. }
  35207. .ng-invalid {
  35208. border: 1px solid red;
  35209. }
  35210. </file>
  35211. <file name="script.js">
  35212. angular.module('customControl', ['ngSanitize']).
  35213. directive('contenteditable', ['$sce', function($sce) {
  35214. return {
  35215. restrict: 'A', // only activate on element attribute
  35216. require: '?ngModel', // get a hold of NgModelController
  35217. link: function(scope, element, attrs, ngModel) {
  35218. if (!ngModel) return; // do nothing if no ng-model
  35219. // Specify how UI should be updated
  35220. ngModel.$render = function() {
  35221. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  35222. };
  35223. // Listen for change events to enable binding
  35224. element.on('blur keyup change', function() {
  35225. scope.$evalAsync(read);
  35226. });
  35227. read(); // initialize
  35228. // Write data to the model
  35229. function read() {
  35230. var html = element.html();
  35231. // When we clear the content editable the browser leaves a <br> behind
  35232. // If strip-br attribute is provided then we strip this out
  35233. if ( attrs.stripBr && html == '<br>' ) {
  35234. html = '';
  35235. }
  35236. ngModel.$setViewValue(html);
  35237. }
  35238. }
  35239. };
  35240. }]);
  35241. </file>
  35242. <file name="index.html">
  35243. <form name="myForm">
  35244. <div contenteditable
  35245. name="myWidget" ng-model="userContent"
  35246. strip-br="true"
  35247. required>Change me!</div>
  35248. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  35249. <hr>
  35250. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  35251. </form>
  35252. </file>
  35253. <file name="protractor.js" type="protractor">
  35254. it('should data-bind and become invalid', function() {
  35255. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  35256. // SafariDriver can't handle contenteditable
  35257. // and Firefox driver can't clear contenteditables very well
  35258. return;
  35259. }
  35260. var contentEditable = element(by.css('[contenteditable]'));
  35261. var content = 'Change me!';
  35262. expect(contentEditable.getText()).toEqual(content);
  35263. contentEditable.clear();
  35264. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  35265. expect(contentEditable.getText()).toEqual('');
  35266. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  35267. });
  35268. </file>
  35269. * </example>
  35270. *
  35271. *
  35272. */
  35273. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  35274. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  35275. this.$viewValue = Number.NaN;
  35276. this.$modelValue = Number.NaN;
  35277. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  35278. this.$validators = {};
  35279. this.$asyncValidators = {};
  35280. this.$parsers = [];
  35281. this.$formatters = [];
  35282. this.$viewChangeListeners = [];
  35283. this.$untouched = true;
  35284. this.$touched = false;
  35285. this.$pristine = true;
  35286. this.$dirty = false;
  35287. this.$valid = true;
  35288. this.$invalid = false;
  35289. this.$error = {}; // keep invalid keys here
  35290. this.$$success = {}; // keep valid keys here
  35291. this.$pending = undefined; // keep pending keys here
  35292. this.$name = $interpolate($attr.name || '', false)($scope);
  35293. this.$$parentForm = nullFormCtrl;
  35294. var parsedNgModel = $parse($attr.ngModel),
  35295. parsedNgModelAssign = parsedNgModel.assign,
  35296. ngModelGet = parsedNgModel,
  35297. ngModelSet = parsedNgModelAssign,
  35298. pendingDebounce = null,
  35299. parserValid,
  35300. ctrl = this;
  35301. this.$$setOptions = function(options) {
  35302. ctrl.$options = options;
  35303. if (options && options.getterSetter) {
  35304. var invokeModelGetter = $parse($attr.ngModel + '()'),
  35305. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  35306. ngModelGet = function($scope) {
  35307. var modelValue = parsedNgModel($scope);
  35308. if (isFunction(modelValue)) {
  35309. modelValue = invokeModelGetter($scope);
  35310. }
  35311. return modelValue;
  35312. };
  35313. ngModelSet = function($scope, newValue) {
  35314. if (isFunction(parsedNgModel($scope))) {
  35315. invokeModelSetter($scope, {$$$p: newValue});
  35316. } else {
  35317. parsedNgModelAssign($scope, newValue);
  35318. }
  35319. };
  35320. } else if (!parsedNgModel.assign) {
  35321. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  35322. $attr.ngModel, startingTag($element));
  35323. }
  35324. };
  35325. /**
  35326. * @ngdoc method
  35327. * @name ngModel.NgModelController#$render
  35328. *
  35329. * @description
  35330. * Called when the view needs to be updated. It is expected that the user of the ng-model
  35331. * directive will implement this method.
  35332. *
  35333. * The `$render()` method is invoked in the following situations:
  35334. *
  35335. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  35336. * committed value then `$render()` is called to update the input control.
  35337. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  35338. * the `$viewValue` are different from last time.
  35339. *
  35340. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  35341. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  35342. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  35343. * invoked if you only change a property on the objects.
  35344. */
  35345. this.$render = noop;
  35346. /**
  35347. * @ngdoc method
  35348. * @name ngModel.NgModelController#$isEmpty
  35349. *
  35350. * @description
  35351. * This is called when we need to determine if the value of an input is empty.
  35352. *
  35353. * For instance, the required directive does this to work out if the input has data or not.
  35354. *
  35355. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  35356. *
  35357. * You can override this for input directives whose concept of being empty is different from the
  35358. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  35359. * implies empty.
  35360. *
  35361. * @param {*} value The value of the input to check for emptiness.
  35362. * @returns {boolean} True if `value` is "empty".
  35363. */
  35364. this.$isEmpty = function(value) {
  35365. return isUndefined(value) || value === '' || value === null || value !== value;
  35366. };
  35367. this.$$updateEmptyClasses = function(value) {
  35368. if (ctrl.$isEmpty(value)) {
  35369. $animate.removeClass($element, NOT_EMPTY_CLASS);
  35370. $animate.addClass($element, EMPTY_CLASS);
  35371. } else {
  35372. $animate.removeClass($element, EMPTY_CLASS);
  35373. $animate.addClass($element, NOT_EMPTY_CLASS);
  35374. }
  35375. };
  35376. var currentValidationRunId = 0;
  35377. /**
  35378. * @ngdoc method
  35379. * @name ngModel.NgModelController#$setValidity
  35380. *
  35381. * @description
  35382. * Change the validity state, and notify the form.
  35383. *
  35384. * This method can be called within $parsers/$formatters or a custom validation implementation.
  35385. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  35386. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  35387. *
  35388. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  35389. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  35390. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  35391. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  35392. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  35393. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  35394. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  35395. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  35396. * Skipped is used by Angular when validators do not run because of parse errors and
  35397. * when `$asyncValidators` do not run because any of the `$validators` failed.
  35398. */
  35399. addSetValidityMethod({
  35400. ctrl: this,
  35401. $element: $element,
  35402. set: function(object, property) {
  35403. object[property] = true;
  35404. },
  35405. unset: function(object, property) {
  35406. delete object[property];
  35407. },
  35408. $animate: $animate
  35409. });
  35410. /**
  35411. * @ngdoc method
  35412. * @name ngModel.NgModelController#$setPristine
  35413. *
  35414. * @description
  35415. * Sets the control to its pristine state.
  35416. *
  35417. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  35418. * state (`ng-pristine` class). A model is considered to be pristine when the control
  35419. * has not been changed from when first compiled.
  35420. */
  35421. this.$setPristine = function() {
  35422. ctrl.$dirty = false;
  35423. ctrl.$pristine = true;
  35424. $animate.removeClass($element, DIRTY_CLASS);
  35425. $animate.addClass($element, PRISTINE_CLASS);
  35426. };
  35427. /**
  35428. * @ngdoc method
  35429. * @name ngModel.NgModelController#$setDirty
  35430. *
  35431. * @description
  35432. * Sets the control to its dirty state.
  35433. *
  35434. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  35435. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  35436. * from when first compiled.
  35437. */
  35438. this.$setDirty = function() {
  35439. ctrl.$dirty = true;
  35440. ctrl.$pristine = false;
  35441. $animate.removeClass($element, PRISTINE_CLASS);
  35442. $animate.addClass($element, DIRTY_CLASS);
  35443. ctrl.$$parentForm.$setDirty();
  35444. };
  35445. /**
  35446. * @ngdoc method
  35447. * @name ngModel.NgModelController#$setUntouched
  35448. *
  35449. * @description
  35450. * Sets the control to its untouched state.
  35451. *
  35452. * This method can be called to remove the `ng-touched` class and set the control to its
  35453. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  35454. * by default, however this function can be used to restore that state if the model has
  35455. * already been touched by the user.
  35456. */
  35457. this.$setUntouched = function() {
  35458. ctrl.$touched = false;
  35459. ctrl.$untouched = true;
  35460. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  35461. };
  35462. /**
  35463. * @ngdoc method
  35464. * @name ngModel.NgModelController#$setTouched
  35465. *
  35466. * @description
  35467. * Sets the control to its touched state.
  35468. *
  35469. * This method can be called to remove the `ng-untouched` class and set the control to its
  35470. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  35471. * first focused the control element and then shifted focus away from the control (blur event).
  35472. */
  35473. this.$setTouched = function() {
  35474. ctrl.$touched = true;
  35475. ctrl.$untouched = false;
  35476. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  35477. };
  35478. /**
  35479. * @ngdoc method
  35480. * @name ngModel.NgModelController#$rollbackViewValue
  35481. *
  35482. * @description
  35483. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  35484. * which may be caused by a pending debounced event or because the input is waiting for a some
  35485. * future event.
  35486. *
  35487. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  35488. * depend on special events such as blur, you can have a situation where there is a period when
  35489. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  35490. *
  35491. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  35492. * and reset the input to the last committed view value.
  35493. *
  35494. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  35495. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  35496. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  35497. *
  35498. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  35499. * input which may have such events pending. This is important in order to make sure that the
  35500. * input field will be updated with the new model value and any pending operations are cancelled.
  35501. *
  35502. * <example name="ng-model-cancel-update" module="cancel-update-example">
  35503. * <file name="app.js">
  35504. * angular.module('cancel-update-example', [])
  35505. *
  35506. * .controller('CancelUpdateController', ['$scope', function($scope) {
  35507. * $scope.model = {};
  35508. *
  35509. * $scope.setEmpty = function(e, value, rollback) {
  35510. * if (e.keyCode == 27) {
  35511. * e.preventDefault();
  35512. * if (rollback) {
  35513. * $scope.myForm[value].$rollbackViewValue();
  35514. * }
  35515. * $scope.model[value] = '';
  35516. * }
  35517. * };
  35518. * }]);
  35519. * </file>
  35520. * <file name="index.html">
  35521. * <div ng-controller="CancelUpdateController">
  35522. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  35523. * empty them. Follow these steps and observe the difference:</p>
  35524. * <ol>
  35525. * <li>Type something in the input. You will see that the model is not yet updated</li>
  35526. * <li>Press the Escape key.
  35527. * <ol>
  35528. * <li> In the first example, nothing happens, because the model is already '', and no
  35529. * update is detected. If you blur the input, the model will be set to the current view.
  35530. * </li>
  35531. * <li> In the second example, the pending update is cancelled, and the input is set back
  35532. * to the last committed view value (''). Blurring the input does nothing.
  35533. * </li>
  35534. * </ol>
  35535. * </li>
  35536. * </ol>
  35537. *
  35538. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  35539. * <div>
  35540. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  35541. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  35542. * ng-keydown="setEmpty($event, 'value1')">
  35543. * value1: "{{ model.value1 }}"
  35544. * </div>
  35545. *
  35546. * <div>
  35547. * <p id="inputDescription2">With $rollbackViewValue():</p>
  35548. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  35549. * ng-keydown="setEmpty($event, 'value2', true)">
  35550. * value2: "{{ model.value2 }}"
  35551. * </div>
  35552. * </form>
  35553. * </div>
  35554. * </file>
  35555. <file name="style.css">
  35556. div {
  35557. display: table-cell;
  35558. }
  35559. div:nth-child(1) {
  35560. padding-right: 30px;
  35561. }
  35562. </file>
  35563. * </example>
  35564. */
  35565. this.$rollbackViewValue = function() {
  35566. $timeout.cancel(pendingDebounce);
  35567. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  35568. ctrl.$render();
  35569. };
  35570. /**
  35571. * @ngdoc method
  35572. * @name ngModel.NgModelController#$validate
  35573. *
  35574. * @description
  35575. * Runs each of the registered validators (first synchronous validators and then
  35576. * asynchronous validators).
  35577. * If the validity changes to invalid, the model will be set to `undefined`,
  35578. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  35579. * If the validity changes to valid, it will set the model to the last available valid
  35580. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  35581. */
  35582. this.$validate = function() {
  35583. // ignore $validate before model is initialized
  35584. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  35585. return;
  35586. }
  35587. var viewValue = ctrl.$$lastCommittedViewValue;
  35588. // Note: we use the $$rawModelValue as $modelValue might have been
  35589. // set to undefined during a view -> model update that found validation
  35590. // errors. We can't parse the view here, since that could change
  35591. // the model although neither viewValue nor the model on the scope changed
  35592. var modelValue = ctrl.$$rawModelValue;
  35593. var prevValid = ctrl.$valid;
  35594. var prevModelValue = ctrl.$modelValue;
  35595. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  35596. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  35597. // If there was no change in validity, don't update the model
  35598. // This prevents changing an invalid modelValue to undefined
  35599. if (!allowInvalid && prevValid !== allValid) {
  35600. // Note: Don't check ctrl.$valid here, as we could have
  35601. // external validators (e.g. calculated on the server),
  35602. // that just call $setValidity and need the model value
  35603. // to calculate their validity.
  35604. ctrl.$modelValue = allValid ? modelValue : undefined;
  35605. if (ctrl.$modelValue !== prevModelValue) {
  35606. ctrl.$$writeModelToScope();
  35607. }
  35608. }
  35609. });
  35610. };
  35611. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  35612. currentValidationRunId++;
  35613. var localValidationRunId = currentValidationRunId;
  35614. // check parser error
  35615. if (!processParseErrors()) {
  35616. validationDone(false);
  35617. return;
  35618. }
  35619. if (!processSyncValidators()) {
  35620. validationDone(false);
  35621. return;
  35622. }
  35623. processAsyncValidators();
  35624. function processParseErrors() {
  35625. var errorKey = ctrl.$$parserName || 'parse';
  35626. if (isUndefined(parserValid)) {
  35627. setValidity(errorKey, null);
  35628. } else {
  35629. if (!parserValid) {
  35630. forEach(ctrl.$validators, function(v, name) {
  35631. setValidity(name, null);
  35632. });
  35633. forEach(ctrl.$asyncValidators, function(v, name) {
  35634. setValidity(name, null);
  35635. });
  35636. }
  35637. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  35638. setValidity(errorKey, parserValid);
  35639. return parserValid;
  35640. }
  35641. return true;
  35642. }
  35643. function processSyncValidators() {
  35644. var syncValidatorsValid = true;
  35645. forEach(ctrl.$validators, function(validator, name) {
  35646. var result = validator(modelValue, viewValue);
  35647. syncValidatorsValid = syncValidatorsValid && result;
  35648. setValidity(name, result);
  35649. });
  35650. if (!syncValidatorsValid) {
  35651. forEach(ctrl.$asyncValidators, function(v, name) {
  35652. setValidity(name, null);
  35653. });
  35654. return false;
  35655. }
  35656. return true;
  35657. }
  35658. function processAsyncValidators() {
  35659. var validatorPromises = [];
  35660. var allValid = true;
  35661. forEach(ctrl.$asyncValidators, function(validator, name) {
  35662. var promise = validator(modelValue, viewValue);
  35663. if (!isPromiseLike(promise)) {
  35664. throw ngModelMinErr('nopromise',
  35665. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  35666. }
  35667. setValidity(name, undefined);
  35668. validatorPromises.push(promise.then(function() {
  35669. setValidity(name, true);
  35670. }, function() {
  35671. allValid = false;
  35672. setValidity(name, false);
  35673. }));
  35674. });
  35675. if (!validatorPromises.length) {
  35676. validationDone(true);
  35677. } else {
  35678. $q.all(validatorPromises).then(function() {
  35679. validationDone(allValid);
  35680. }, noop);
  35681. }
  35682. }
  35683. function setValidity(name, isValid) {
  35684. if (localValidationRunId === currentValidationRunId) {
  35685. ctrl.$setValidity(name, isValid);
  35686. }
  35687. }
  35688. function validationDone(allValid) {
  35689. if (localValidationRunId === currentValidationRunId) {
  35690. doneCallback(allValid);
  35691. }
  35692. }
  35693. };
  35694. /**
  35695. * @ngdoc method
  35696. * @name ngModel.NgModelController#$commitViewValue
  35697. *
  35698. * @description
  35699. * Commit a pending update to the `$modelValue`.
  35700. *
  35701. * Updates may be pending by a debounced event or because the input is waiting for a some future
  35702. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  35703. * usually handles calling this in response to input events.
  35704. */
  35705. this.$commitViewValue = function() {
  35706. var viewValue = ctrl.$viewValue;
  35707. $timeout.cancel(pendingDebounce);
  35708. // If the view value has not changed then we should just exit, except in the case where there is
  35709. // a native validator on the element. In this case the validation state may have changed even though
  35710. // the viewValue has stayed empty.
  35711. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  35712. return;
  35713. }
  35714. ctrl.$$updateEmptyClasses(viewValue);
  35715. ctrl.$$lastCommittedViewValue = viewValue;
  35716. // change to dirty
  35717. if (ctrl.$pristine) {
  35718. this.$setDirty();
  35719. }
  35720. this.$$parseAndValidate();
  35721. };
  35722. this.$$parseAndValidate = function() {
  35723. var viewValue = ctrl.$$lastCommittedViewValue;
  35724. var modelValue = viewValue;
  35725. parserValid = isUndefined(modelValue) ? undefined : true;
  35726. if (parserValid) {
  35727. for (var i = 0; i < ctrl.$parsers.length; i++) {
  35728. modelValue = ctrl.$parsers[i](modelValue);
  35729. if (isUndefined(modelValue)) {
  35730. parserValid = false;
  35731. break;
  35732. }
  35733. }
  35734. }
  35735. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  35736. // ctrl.$modelValue has not been touched yet...
  35737. ctrl.$modelValue = ngModelGet($scope);
  35738. }
  35739. var prevModelValue = ctrl.$modelValue;
  35740. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  35741. ctrl.$$rawModelValue = modelValue;
  35742. if (allowInvalid) {
  35743. ctrl.$modelValue = modelValue;
  35744. writeToModelIfNeeded();
  35745. }
  35746. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  35747. // This can happen if e.g. $setViewValue is called from inside a parser
  35748. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  35749. if (!allowInvalid) {
  35750. // Note: Don't check ctrl.$valid here, as we could have
  35751. // external validators (e.g. calculated on the server),
  35752. // that just call $setValidity and need the model value
  35753. // to calculate their validity.
  35754. ctrl.$modelValue = allValid ? modelValue : undefined;
  35755. writeToModelIfNeeded();
  35756. }
  35757. });
  35758. function writeToModelIfNeeded() {
  35759. if (ctrl.$modelValue !== prevModelValue) {
  35760. ctrl.$$writeModelToScope();
  35761. }
  35762. }
  35763. };
  35764. this.$$writeModelToScope = function() {
  35765. ngModelSet($scope, ctrl.$modelValue);
  35766. forEach(ctrl.$viewChangeListeners, function(listener) {
  35767. try {
  35768. listener();
  35769. } catch (e) {
  35770. $exceptionHandler(e);
  35771. }
  35772. });
  35773. };
  35774. /**
  35775. * @ngdoc method
  35776. * @name ngModel.NgModelController#$setViewValue
  35777. *
  35778. * @description
  35779. * Update the view value.
  35780. *
  35781. * This method should be called when a control wants to change the view value; typically,
  35782. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  35783. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  35784. * calls it when an option is selected.
  35785. *
  35786. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  35787. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  35788. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  35789. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  35790. * in the `$viewChangeListeners` list, are called.
  35791. *
  35792. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  35793. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  35794. * `updateOn` events is triggered on the DOM element.
  35795. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  35796. * directive is used with a custom debounce for this particular event.
  35797. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  35798. * is specified, once the timer runs out.
  35799. *
  35800. * When used with standard inputs, the view value will always be a string (which is in some cases
  35801. * parsed into another type, such as a `Date` object for `input[date]`.)
  35802. * However, custom controls might also pass objects to this method. In this case, we should make
  35803. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  35804. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  35805. * the property of the object then ngModel will not realize that the object has changed and
  35806. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  35807. * not change properties of the copy once it has been passed to `$setViewValue`.
  35808. * Otherwise you may cause the model value on the scope to change incorrectly.
  35809. *
  35810. * <div class="alert alert-info">
  35811. * In any case, the value passed to the method should always reflect the current value
  35812. * of the control. For example, if you are calling `$setViewValue` for an input element,
  35813. * you should pass the input DOM value. Otherwise, the control and the scope model become
  35814. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  35815. * the control's DOM value in any way. If we want to change the control's DOM value
  35816. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  35817. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  35818. * to update the DOM, and finally call `$validate` on it.
  35819. * </div>
  35820. *
  35821. * @param {*} value value from the view.
  35822. * @param {string} trigger Event that triggered the update.
  35823. */
  35824. this.$setViewValue = function(value, trigger) {
  35825. ctrl.$viewValue = value;
  35826. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  35827. ctrl.$$debounceViewValueCommit(trigger);
  35828. }
  35829. };
  35830. this.$$debounceViewValueCommit = function(trigger) {
  35831. var debounceDelay = 0,
  35832. options = ctrl.$options,
  35833. debounce;
  35834. if (options && isDefined(options.debounce)) {
  35835. debounce = options.debounce;
  35836. if (isNumber(debounce)) {
  35837. debounceDelay = debounce;
  35838. } else if (isNumber(debounce[trigger])) {
  35839. debounceDelay = debounce[trigger];
  35840. } else if (isNumber(debounce['default'])) {
  35841. debounceDelay = debounce['default'];
  35842. }
  35843. }
  35844. $timeout.cancel(pendingDebounce);
  35845. if (debounceDelay) {
  35846. pendingDebounce = $timeout(function() {
  35847. ctrl.$commitViewValue();
  35848. }, debounceDelay);
  35849. } else if ($rootScope.$$phase) {
  35850. ctrl.$commitViewValue();
  35851. } else {
  35852. $scope.$apply(function() {
  35853. ctrl.$commitViewValue();
  35854. });
  35855. }
  35856. };
  35857. // model -> value
  35858. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  35859. // 1. scope value is 'a'
  35860. // 2. user enters 'b'
  35861. // 3. ng-change kicks in and reverts scope value to 'a'
  35862. // -> scope value did not change since the last digest as
  35863. // ng-change executes in apply phase
  35864. // 4. view should be changed back to 'a'
  35865. $scope.$watch(function ngModelWatch() {
  35866. var modelValue = ngModelGet($scope);
  35867. // if scope model value and ngModel value are out of sync
  35868. // TODO(perf): why not move this to the action fn?
  35869. if (modelValue !== ctrl.$modelValue &&
  35870. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  35871. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  35872. ) {
  35873. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  35874. parserValid = undefined;
  35875. var formatters = ctrl.$formatters,
  35876. idx = formatters.length;
  35877. var viewValue = modelValue;
  35878. while (idx--) {
  35879. viewValue = formatters[idx](viewValue);
  35880. }
  35881. if (ctrl.$viewValue !== viewValue) {
  35882. ctrl.$$updateEmptyClasses(viewValue);
  35883. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  35884. ctrl.$render();
  35885. ctrl.$$runValidators(modelValue, viewValue, noop);
  35886. }
  35887. }
  35888. return modelValue;
  35889. });
  35890. }];
  35891. /**
  35892. * @ngdoc directive
  35893. * @name ngModel
  35894. *
  35895. * @element input
  35896. * @priority 1
  35897. *
  35898. * @description
  35899. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  35900. * property on the scope using {@link ngModel.NgModelController NgModelController},
  35901. * which is created and exposed by this directive.
  35902. *
  35903. * `ngModel` is responsible for:
  35904. *
  35905. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  35906. * require.
  35907. * - Providing validation behavior (i.e. required, number, email, url).
  35908. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  35909. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  35910. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  35911. * - Registering the control with its parent {@link ng.directive:form form}.
  35912. *
  35913. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  35914. * current scope. If the property doesn't already exist on this scope, it will be created
  35915. * implicitly and added to the scope.
  35916. *
  35917. * For best practices on using `ngModel`, see:
  35918. *
  35919. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  35920. *
  35921. * For basic examples, how to use `ngModel`, see:
  35922. *
  35923. * - {@link ng.directive:input input}
  35924. * - {@link input[text] text}
  35925. * - {@link input[checkbox] checkbox}
  35926. * - {@link input[radio] radio}
  35927. * - {@link input[number] number}
  35928. * - {@link input[email] email}
  35929. * - {@link input[url] url}
  35930. * - {@link input[date] date}
  35931. * - {@link input[datetime-local] datetime-local}
  35932. * - {@link input[time] time}
  35933. * - {@link input[month] month}
  35934. * - {@link input[week] week}
  35935. * - {@link ng.directive:select select}
  35936. * - {@link ng.directive:textarea textarea}
  35937. *
  35938. * # Complex Models (objects or collections)
  35939. *
  35940. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  35941. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  35942. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  35943. *
  35944. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  35945. *
  35946. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  35947. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  35948. * if the select is given the `multiple` attribute.
  35949. *
  35950. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  35951. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  35952. * not trigger a re-rendering of the model.
  35953. *
  35954. * # CSS classes
  35955. * The following CSS classes are added and removed on the associated input/select/textarea element
  35956. * depending on the validity of the model.
  35957. *
  35958. * - `ng-valid`: the model is valid
  35959. * - `ng-invalid`: the model is invalid
  35960. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  35961. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  35962. * - `ng-pristine`: the control hasn't been interacted with yet
  35963. * - `ng-dirty`: the control has been interacted with
  35964. * - `ng-touched`: the control has been blurred
  35965. * - `ng-untouched`: the control hasn't been blurred
  35966. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  35967. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  35968. * by the {@link ngModel.NgModelController#$isEmpty} method
  35969. * - `ng-not-empty`: the view contains a non-empty value
  35970. *
  35971. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  35972. *
  35973. * ## Animation Hooks
  35974. *
  35975. * Animations within models are triggered when any of the associated CSS classes are added and removed
  35976. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  35977. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  35978. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  35979. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  35980. *
  35981. * The following example shows a simple way to utilize CSS transitions to style an input element
  35982. * that has been rendered as invalid after it has been validated:
  35983. *
  35984. * <pre>
  35985. * //be sure to include ngAnimate as a module to hook into more
  35986. * //advanced animations
  35987. * .my-input {
  35988. * transition:0.5s linear all;
  35989. * background: white;
  35990. * }
  35991. * .my-input.ng-invalid {
  35992. * background: red;
  35993. * color:white;
  35994. * }
  35995. * </pre>
  35996. *
  35997. * @example
  35998. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  35999. <file name="index.html">
  36000. <script>
  36001. angular.module('inputExample', [])
  36002. .controller('ExampleController', ['$scope', function($scope) {
  36003. $scope.val = '1';
  36004. }]);
  36005. </script>
  36006. <style>
  36007. .my-input {
  36008. transition:all linear 0.5s;
  36009. background: transparent;
  36010. }
  36011. .my-input.ng-invalid {
  36012. color:white;
  36013. background: red;
  36014. }
  36015. </style>
  36016. <p id="inputDescription">
  36017. Update input to see transitions when valid/invalid.
  36018. Integer is a valid value.
  36019. </p>
  36020. <form name="testForm" ng-controller="ExampleController">
  36021. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  36022. aria-describedby="inputDescription" />
  36023. </form>
  36024. </file>
  36025. * </example>
  36026. *
  36027. * ## Binding to a getter/setter
  36028. *
  36029. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  36030. * function that returns a representation of the model when called with zero arguments, and sets
  36031. * the internal state of a model when called with an argument. It's sometimes useful to use this
  36032. * for models that have an internal representation that's different from what the model exposes
  36033. * to the view.
  36034. *
  36035. * <div class="alert alert-success">
  36036. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  36037. * frequently than other parts of your code.
  36038. * </div>
  36039. *
  36040. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  36041. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  36042. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  36043. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  36044. *
  36045. * The following example shows how to use `ngModel` with a getter/setter:
  36046. *
  36047. * @example
  36048. * <example name="ngModel-getter-setter" module="getterSetterExample">
  36049. <file name="index.html">
  36050. <div ng-controller="ExampleController">
  36051. <form name="userForm">
  36052. <label>Name:
  36053. <input type="text" name="userName"
  36054. ng-model="user.name"
  36055. ng-model-options="{ getterSetter: true }" />
  36056. </label>
  36057. </form>
  36058. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  36059. </div>
  36060. </file>
  36061. <file name="app.js">
  36062. angular.module('getterSetterExample', [])
  36063. .controller('ExampleController', ['$scope', function($scope) {
  36064. var _name = 'Brian';
  36065. $scope.user = {
  36066. name: function(newName) {
  36067. // Note that newName can be undefined for two reasons:
  36068. // 1. Because it is called as a getter and thus called with no arguments
  36069. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  36070. // input is invalid
  36071. return arguments.length ? (_name = newName) : _name;
  36072. }
  36073. };
  36074. }]);
  36075. </file>
  36076. * </example>
  36077. */
  36078. var ngModelDirective = ['$rootScope', function($rootScope) {
  36079. return {
  36080. restrict: 'A',
  36081. require: ['ngModel', '^?form', '^?ngModelOptions'],
  36082. controller: NgModelController,
  36083. // Prelink needs to run before any input directive
  36084. // so that we can set the NgModelOptions in NgModelController
  36085. // before anyone else uses it.
  36086. priority: 1,
  36087. compile: function ngModelCompile(element) {
  36088. // Setup initial state of the control
  36089. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  36090. return {
  36091. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  36092. var modelCtrl = ctrls[0],
  36093. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  36094. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  36095. // notify others, especially parent forms
  36096. formCtrl.$addControl(modelCtrl);
  36097. attr.$observe('name', function(newValue) {
  36098. if (modelCtrl.$name !== newValue) {
  36099. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  36100. }
  36101. });
  36102. scope.$on('$destroy', function() {
  36103. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  36104. });
  36105. },
  36106. post: function ngModelPostLink(scope, element, attr, ctrls) {
  36107. var modelCtrl = ctrls[0];
  36108. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  36109. element.on(modelCtrl.$options.updateOn, function(ev) {
  36110. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  36111. });
  36112. }
  36113. element.on('blur', function() {
  36114. if (modelCtrl.$touched) return;
  36115. if ($rootScope.$$phase) {
  36116. scope.$evalAsync(modelCtrl.$setTouched);
  36117. } else {
  36118. scope.$apply(modelCtrl.$setTouched);
  36119. }
  36120. });
  36121. }
  36122. };
  36123. }
  36124. };
  36125. }];
  36126. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  36127. /**
  36128. * @ngdoc directive
  36129. * @name ngModelOptions
  36130. *
  36131. * @description
  36132. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  36133. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  36134. * takes place when a timer expires; this timer will be reset after another change takes place.
  36135. *
  36136. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  36137. * be different from the value in the actual model. This means that if you update the model you
  36138. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  36139. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  36140. *
  36141. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  36142. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  36143. * important because `form` controllers are published to the related scope under the name in their
  36144. * `name` attribute.
  36145. *
  36146. * Any pending changes will take place immediately when an enclosing form is submitted via the
  36147. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  36148. * to have access to the updated model.
  36149. *
  36150. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  36151. *
  36152. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  36153. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  36154. * events using an space delimited list. There is a special event called `default` that
  36155. * matches the default events belonging of the control.
  36156. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  36157. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  36158. * custom value for each event. For example:
  36159. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  36160. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  36161. * not validate correctly instead of the default behavior of setting the model to undefined.
  36162. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  36163. `ngModel` as getters/setters.
  36164. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  36165. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  36166. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  36167. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  36168. * If not specified, the timezone of the browser will be used.
  36169. *
  36170. * @example
  36171. The following example shows how to override immediate updates. Changes on the inputs within the
  36172. form will update the model only when the control loses focus (blur event). If `escape` key is
  36173. pressed while the input field is focused, the value is reset to the value in the current model.
  36174. <example name="ngModelOptions-directive-blur" module="optionsExample">
  36175. <file name="index.html">
  36176. <div ng-controller="ExampleController">
  36177. <form name="userForm">
  36178. <label>Name:
  36179. <input type="text" name="userName"
  36180. ng-model="user.name"
  36181. ng-model-options="{ updateOn: 'blur' }"
  36182. ng-keyup="cancel($event)" />
  36183. </label><br />
  36184. <label>Other data:
  36185. <input type="text" ng-model="user.data" />
  36186. </label><br />
  36187. </form>
  36188. <pre>user.name = <span ng-bind="user.name"></span></pre>
  36189. <pre>user.data = <span ng-bind="user.data"></span></pre>
  36190. </div>
  36191. </file>
  36192. <file name="app.js">
  36193. angular.module('optionsExample', [])
  36194. .controller('ExampleController', ['$scope', function($scope) {
  36195. $scope.user = { name: 'John', data: '' };
  36196. $scope.cancel = function(e) {
  36197. if (e.keyCode == 27) {
  36198. $scope.userForm.userName.$rollbackViewValue();
  36199. }
  36200. };
  36201. }]);
  36202. </file>
  36203. <file name="protractor.js" type="protractor">
  36204. var model = element(by.binding('user.name'));
  36205. var input = element(by.model('user.name'));
  36206. var other = element(by.model('user.data'));
  36207. it('should allow custom events', function() {
  36208. input.sendKeys(' Doe');
  36209. input.click();
  36210. expect(model.getText()).toEqual('John');
  36211. other.click();
  36212. expect(model.getText()).toEqual('John Doe');
  36213. });
  36214. it('should $rollbackViewValue when model changes', function() {
  36215. input.sendKeys(' Doe');
  36216. expect(input.getAttribute('value')).toEqual('John Doe');
  36217. input.sendKeys(protractor.Key.ESCAPE);
  36218. expect(input.getAttribute('value')).toEqual('John');
  36219. other.click();
  36220. expect(model.getText()).toEqual('John');
  36221. });
  36222. </file>
  36223. </example>
  36224. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  36225. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  36226. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  36227. <file name="index.html">
  36228. <div ng-controller="ExampleController">
  36229. <form name="userForm">
  36230. <label>Name:
  36231. <input type="text" name="userName"
  36232. ng-model="user.name"
  36233. ng-model-options="{ debounce: 1000 }" />
  36234. </label>
  36235. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  36236. <br />
  36237. </form>
  36238. <pre>user.name = <span ng-bind="user.name"></span></pre>
  36239. </div>
  36240. </file>
  36241. <file name="app.js">
  36242. angular.module('optionsExample', [])
  36243. .controller('ExampleController', ['$scope', function($scope) {
  36244. $scope.user = { name: 'Igor' };
  36245. }]);
  36246. </file>
  36247. </example>
  36248. This one shows how to bind to getter/setters:
  36249. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  36250. <file name="index.html">
  36251. <div ng-controller="ExampleController">
  36252. <form name="userForm">
  36253. <label>Name:
  36254. <input type="text" name="userName"
  36255. ng-model="user.name"
  36256. ng-model-options="{ getterSetter: true }" />
  36257. </label>
  36258. </form>
  36259. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  36260. </div>
  36261. </file>
  36262. <file name="app.js">
  36263. angular.module('getterSetterExample', [])
  36264. .controller('ExampleController', ['$scope', function($scope) {
  36265. var _name = 'Brian';
  36266. $scope.user = {
  36267. name: function(newName) {
  36268. // Note that newName can be undefined for two reasons:
  36269. // 1. Because it is called as a getter and thus called with no arguments
  36270. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  36271. // input is invalid
  36272. return arguments.length ? (_name = newName) : _name;
  36273. }
  36274. };
  36275. }]);
  36276. </file>
  36277. </example>
  36278. */
  36279. var ngModelOptionsDirective = function() {
  36280. return {
  36281. restrict: 'A',
  36282. controller: ['$scope', '$attrs', function($scope, $attrs) {
  36283. var that = this;
  36284. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  36285. // Allow adding/overriding bound events
  36286. if (isDefined(this.$options.updateOn)) {
  36287. this.$options.updateOnDefault = false;
  36288. // extract "default" pseudo-event from list of events that can trigger a model update
  36289. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  36290. that.$options.updateOnDefault = true;
  36291. return ' ';
  36292. }));
  36293. } else {
  36294. this.$options.updateOnDefault = true;
  36295. }
  36296. }]
  36297. };
  36298. };
  36299. // helper methods
  36300. function addSetValidityMethod(context) {
  36301. var ctrl = context.ctrl,
  36302. $element = context.$element,
  36303. classCache = {},
  36304. set = context.set,
  36305. unset = context.unset,
  36306. $animate = context.$animate;
  36307. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  36308. ctrl.$setValidity = setValidity;
  36309. function setValidity(validationErrorKey, state, controller) {
  36310. if (isUndefined(state)) {
  36311. createAndSet('$pending', validationErrorKey, controller);
  36312. } else {
  36313. unsetAndCleanup('$pending', validationErrorKey, controller);
  36314. }
  36315. if (!isBoolean(state)) {
  36316. unset(ctrl.$error, validationErrorKey, controller);
  36317. unset(ctrl.$$success, validationErrorKey, controller);
  36318. } else {
  36319. if (state) {
  36320. unset(ctrl.$error, validationErrorKey, controller);
  36321. set(ctrl.$$success, validationErrorKey, controller);
  36322. } else {
  36323. set(ctrl.$error, validationErrorKey, controller);
  36324. unset(ctrl.$$success, validationErrorKey, controller);
  36325. }
  36326. }
  36327. if (ctrl.$pending) {
  36328. cachedToggleClass(PENDING_CLASS, true);
  36329. ctrl.$valid = ctrl.$invalid = undefined;
  36330. toggleValidationCss('', null);
  36331. } else {
  36332. cachedToggleClass(PENDING_CLASS, false);
  36333. ctrl.$valid = isObjectEmpty(ctrl.$error);
  36334. ctrl.$invalid = !ctrl.$valid;
  36335. toggleValidationCss('', ctrl.$valid);
  36336. }
  36337. // re-read the state as the set/unset methods could have
  36338. // combined state in ctrl.$error[validationError] (used for forms),
  36339. // where setting/unsetting only increments/decrements the value,
  36340. // and does not replace it.
  36341. var combinedState;
  36342. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  36343. combinedState = undefined;
  36344. } else if (ctrl.$error[validationErrorKey]) {
  36345. combinedState = false;
  36346. } else if (ctrl.$$success[validationErrorKey]) {
  36347. combinedState = true;
  36348. } else {
  36349. combinedState = null;
  36350. }
  36351. toggleValidationCss(validationErrorKey, combinedState);
  36352. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  36353. }
  36354. function createAndSet(name, value, controller) {
  36355. if (!ctrl[name]) {
  36356. ctrl[name] = {};
  36357. }
  36358. set(ctrl[name], value, controller);
  36359. }
  36360. function unsetAndCleanup(name, value, controller) {
  36361. if (ctrl[name]) {
  36362. unset(ctrl[name], value, controller);
  36363. }
  36364. if (isObjectEmpty(ctrl[name])) {
  36365. ctrl[name] = undefined;
  36366. }
  36367. }
  36368. function cachedToggleClass(className, switchValue) {
  36369. if (switchValue && !classCache[className]) {
  36370. $animate.addClass($element, className);
  36371. classCache[className] = true;
  36372. } else if (!switchValue && classCache[className]) {
  36373. $animate.removeClass($element, className);
  36374. classCache[className] = false;
  36375. }
  36376. }
  36377. function toggleValidationCss(validationErrorKey, isValid) {
  36378. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  36379. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  36380. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  36381. }
  36382. }
  36383. function isObjectEmpty(obj) {
  36384. if (obj) {
  36385. for (var prop in obj) {
  36386. if (obj.hasOwnProperty(prop)) {
  36387. return false;
  36388. }
  36389. }
  36390. }
  36391. return true;
  36392. }
  36393. /**
  36394. * @ngdoc directive
  36395. * @name ngNonBindable
  36396. * @restrict AC
  36397. * @priority 1000
  36398. *
  36399. * @description
  36400. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  36401. * DOM element. This is useful if the element contains what appears to be Angular directives and
  36402. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  36403. * displays snippets of code, for instance.
  36404. *
  36405. * @element ANY
  36406. *
  36407. * @example
  36408. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  36409. * but the one wrapped in `ngNonBindable` is left alone.
  36410. *
  36411. * @example
  36412. <example>
  36413. <file name="index.html">
  36414. <div>Normal: {{1 + 2}}</div>
  36415. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  36416. </file>
  36417. <file name="protractor.js" type="protractor">
  36418. it('should check ng-non-bindable', function() {
  36419. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  36420. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  36421. });
  36422. </file>
  36423. </example>
  36424. */
  36425. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  36426. /* global jqLiteRemove */
  36427. var ngOptionsMinErr = minErr('ngOptions');
  36428. /**
  36429. * @ngdoc directive
  36430. * @name ngOptions
  36431. * @restrict A
  36432. *
  36433. * @description
  36434. *
  36435. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  36436. * elements for the `<select>` element using the array or object obtained by evaluating the
  36437. * `ngOptions` comprehension expression.
  36438. *
  36439. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  36440. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  36441. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  36442. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  36443. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  36444. * to a non-string value. This is because an option element can only be bound to string values at
  36445. * present.
  36446. *
  36447. * When an item in the `<select>` menu is selected, the array element or object property
  36448. * represented by the selected option will be bound to the model identified by the `ngModel`
  36449. * directive.
  36450. *
  36451. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  36452. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  36453. * option. See example below for demonstration.
  36454. *
  36455. * ## Complex Models (objects or collections)
  36456. *
  36457. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  36458. * binding the select to a model that is an object or a collection.
  36459. *
  36460. * One issue occurs if you want to preselect an option. For example, if you set
  36461. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  36462. * because the objects are not identical. So by default, you should always reference the item in your collection
  36463. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  36464. *
  36465. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  36466. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  36467. * collection items have an id property, you would `track by item.id`.
  36468. *
  36469. * A different issue with objects or collections is that ngModel won't detect if an object property or
  36470. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  36471. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  36472. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  36473. * has not changed identity, but only a property on the object or an item in the collection changes.
  36474. *
  36475. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  36476. * if the model is an array). This means that changing a property deeper than the first level inside the
  36477. * object/collection will not trigger a re-rendering.
  36478. *
  36479. * ## `select` **`as`**
  36480. *
  36481. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  36482. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  36483. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  36484. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  36485. *
  36486. *
  36487. * ### `select` **`as`** and **`track by`**
  36488. *
  36489. * <div class="alert alert-warning">
  36490. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  36491. * </div>
  36492. *
  36493. * Given this array of items on the $scope:
  36494. *
  36495. * ```js
  36496. * $scope.items = [{
  36497. * id: 1,
  36498. * label: 'aLabel',
  36499. * subItem: { name: 'aSubItem' }
  36500. * }, {
  36501. * id: 2,
  36502. * label: 'bLabel',
  36503. * subItem: { name: 'bSubItem' }
  36504. * }];
  36505. * ```
  36506. *
  36507. * This will work:
  36508. *
  36509. * ```html
  36510. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  36511. * ```
  36512. * ```js
  36513. * $scope.selected = $scope.items[0];
  36514. * ```
  36515. *
  36516. * but this will not work:
  36517. *
  36518. * ```html
  36519. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  36520. * ```
  36521. * ```js
  36522. * $scope.selected = $scope.items[0].subItem;
  36523. * ```
  36524. *
  36525. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  36526. * `items` array. Because the selected option has been set programmatically in the controller, the
  36527. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  36528. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  36529. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  36530. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  36531. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  36532. *
  36533. *
  36534. * @param {string} ngModel Assignable angular expression to data-bind to.
  36535. * @param {string=} name Property name of the form under which the control is published.
  36536. * @param {string=} required The control is considered valid only if value is entered.
  36537. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  36538. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  36539. * `required` when you want to data-bind to the `required` attribute.
  36540. * @param {comprehension_expression=} ngOptions in one of the following forms:
  36541. *
  36542. * * for array data sources:
  36543. * * `label` **`for`** `value` **`in`** `array`
  36544. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  36545. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  36546. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  36547. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  36548. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  36549. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  36550. * (for including a filter with `track by`)
  36551. * * for object data sources:
  36552. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  36553. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  36554. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  36555. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  36556. * * `select` **`as`** `label` **`group by`** `group`
  36557. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  36558. * * `select` **`as`** `label` **`disable when`** `disable`
  36559. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  36560. *
  36561. * Where:
  36562. *
  36563. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  36564. * * `value`: local variable which will refer to each item in the `array` or each property value
  36565. * of `object` during iteration.
  36566. * * `key`: local variable which will refer to a property name in `object` during iteration.
  36567. * * `label`: The result of this expression will be the label for `<option>` element. The
  36568. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  36569. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  36570. * element. If not specified, `select` expression will default to `value`.
  36571. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  36572. * DOM element.
  36573. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  36574. * element. Return `true` to disable.
  36575. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  36576. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  36577. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  36578. * even when the options are recreated (e.g. reloaded from the server).
  36579. *
  36580. * @example
  36581. <example module="selectExample">
  36582. <file name="index.html">
  36583. <script>
  36584. angular.module('selectExample', [])
  36585. .controller('ExampleController', ['$scope', function($scope) {
  36586. $scope.colors = [
  36587. {name:'black', shade:'dark'},
  36588. {name:'white', shade:'light', notAnOption: true},
  36589. {name:'red', shade:'dark'},
  36590. {name:'blue', shade:'dark', notAnOption: true},
  36591. {name:'yellow', shade:'light', notAnOption: false}
  36592. ];
  36593. $scope.myColor = $scope.colors[2]; // red
  36594. }]);
  36595. </script>
  36596. <div ng-controller="ExampleController">
  36597. <ul>
  36598. <li ng-repeat="color in colors">
  36599. <label>Name: <input ng-model="color.name"></label>
  36600. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  36601. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  36602. </li>
  36603. <li>
  36604. <button ng-click="colors.push({})">add</button>
  36605. </li>
  36606. </ul>
  36607. <hr/>
  36608. <label>Color (null not allowed):
  36609. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  36610. </label><br/>
  36611. <label>Color (null allowed):
  36612. <span class="nullable">
  36613. <select ng-model="myColor" ng-options="color.name for color in colors">
  36614. <option value="">-- choose color --</option>
  36615. </select>
  36616. </span></label><br/>
  36617. <label>Color grouped by shade:
  36618. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  36619. </select>
  36620. </label><br/>
  36621. <label>Color grouped by shade, with some disabled:
  36622. <select ng-model="myColor"
  36623. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  36624. </select>
  36625. </label><br/>
  36626. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  36627. <br/>
  36628. <hr/>
  36629. Currently selected: {{ {selected_color:myColor} }}
  36630. <div style="border:solid 1px black; height:20px"
  36631. ng-style="{'background-color':myColor.name}">
  36632. </div>
  36633. </div>
  36634. </file>
  36635. <file name="protractor.js" type="protractor">
  36636. it('should check ng-options', function() {
  36637. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  36638. element.all(by.model('myColor')).first().click();
  36639. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  36640. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  36641. element(by.css('.nullable select[ng-model="myColor"]')).click();
  36642. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  36643. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  36644. });
  36645. </file>
  36646. </example>
  36647. */
  36648. // jshint maxlen: false
  36649. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  36650. 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]+?))?$/;
  36651. // 1: value expression (valueFn)
  36652. // 2: label expression (displayFn)
  36653. // 3: group by expression (groupByFn)
  36654. // 4: disable when expression (disableWhenFn)
  36655. // 5: array item variable name
  36656. // 6: object item key variable name
  36657. // 7: object item value variable name
  36658. // 8: collection expression
  36659. // 9: track by expression
  36660. // jshint maxlen: 100
  36661. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  36662. function parseOptionsExpression(optionsExp, selectElement, scope) {
  36663. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  36664. if (!(match)) {
  36665. throw ngOptionsMinErr('iexp',
  36666. "Expected expression in form of " +
  36667. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  36668. " but got '{0}'. Element: {1}",
  36669. optionsExp, startingTag(selectElement));
  36670. }
  36671. // Extract the parts from the ngOptions expression
  36672. // The variable name for the value of the item in the collection
  36673. var valueName = match[5] || match[7];
  36674. // The variable name for the key of the item in the collection
  36675. var keyName = match[6];
  36676. // An expression that generates the viewValue for an option if there is a label expression
  36677. var selectAs = / as /.test(match[0]) && match[1];
  36678. // An expression that is used to track the id of each object in the options collection
  36679. var trackBy = match[9];
  36680. // An expression that generates the viewValue for an option if there is no label expression
  36681. var valueFn = $parse(match[2] ? match[1] : valueName);
  36682. var selectAsFn = selectAs && $parse(selectAs);
  36683. var viewValueFn = selectAsFn || valueFn;
  36684. var trackByFn = trackBy && $parse(trackBy);
  36685. // Get the value by which we are going to track the option
  36686. // if we have a trackFn then use that (passing scope and locals)
  36687. // otherwise just hash the given viewValue
  36688. var getTrackByValueFn = trackBy ?
  36689. function(value, locals) { return trackByFn(scope, locals); } :
  36690. function getHashOfValue(value) { return hashKey(value); };
  36691. var getTrackByValue = function(value, key) {
  36692. return getTrackByValueFn(value, getLocals(value, key));
  36693. };
  36694. var displayFn = $parse(match[2] || match[1]);
  36695. var groupByFn = $parse(match[3] || '');
  36696. var disableWhenFn = $parse(match[4] || '');
  36697. var valuesFn = $parse(match[8]);
  36698. var locals = {};
  36699. var getLocals = keyName ? function(value, key) {
  36700. locals[keyName] = key;
  36701. locals[valueName] = value;
  36702. return locals;
  36703. } : function(value) {
  36704. locals[valueName] = value;
  36705. return locals;
  36706. };
  36707. function Option(selectValue, viewValue, label, group, disabled) {
  36708. this.selectValue = selectValue;
  36709. this.viewValue = viewValue;
  36710. this.label = label;
  36711. this.group = group;
  36712. this.disabled = disabled;
  36713. }
  36714. function getOptionValuesKeys(optionValues) {
  36715. var optionValuesKeys;
  36716. if (!keyName && isArrayLike(optionValues)) {
  36717. optionValuesKeys = optionValues;
  36718. } else {
  36719. // if object, extract keys, in enumeration order, unsorted
  36720. optionValuesKeys = [];
  36721. for (var itemKey in optionValues) {
  36722. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  36723. optionValuesKeys.push(itemKey);
  36724. }
  36725. }
  36726. }
  36727. return optionValuesKeys;
  36728. }
  36729. return {
  36730. trackBy: trackBy,
  36731. getTrackByValue: getTrackByValue,
  36732. getWatchables: $parse(valuesFn, function(optionValues) {
  36733. // Create a collection of things that we would like to watch (watchedArray)
  36734. // so that they can all be watched using a single $watchCollection
  36735. // that only runs the handler once if anything changes
  36736. var watchedArray = [];
  36737. optionValues = optionValues || [];
  36738. var optionValuesKeys = getOptionValuesKeys(optionValues);
  36739. var optionValuesLength = optionValuesKeys.length;
  36740. for (var index = 0; index < optionValuesLength; index++) {
  36741. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  36742. var value = optionValues[key];
  36743. var locals = getLocals(value, key);
  36744. var selectValue = getTrackByValueFn(value, locals);
  36745. watchedArray.push(selectValue);
  36746. // Only need to watch the displayFn if there is a specific label expression
  36747. if (match[2] || match[1]) {
  36748. var label = displayFn(scope, locals);
  36749. watchedArray.push(label);
  36750. }
  36751. // Only need to watch the disableWhenFn if there is a specific disable expression
  36752. if (match[4]) {
  36753. var disableWhen = disableWhenFn(scope, locals);
  36754. watchedArray.push(disableWhen);
  36755. }
  36756. }
  36757. return watchedArray;
  36758. }),
  36759. getOptions: function() {
  36760. var optionItems = [];
  36761. var selectValueMap = {};
  36762. // The option values were already computed in the `getWatchables` fn,
  36763. // which must have been called to trigger `getOptions`
  36764. var optionValues = valuesFn(scope) || [];
  36765. var optionValuesKeys = getOptionValuesKeys(optionValues);
  36766. var optionValuesLength = optionValuesKeys.length;
  36767. for (var index = 0; index < optionValuesLength; index++) {
  36768. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  36769. var value = optionValues[key];
  36770. var locals = getLocals(value, key);
  36771. var viewValue = viewValueFn(scope, locals);
  36772. var selectValue = getTrackByValueFn(viewValue, locals);
  36773. var label = displayFn(scope, locals);
  36774. var group = groupByFn(scope, locals);
  36775. var disabled = disableWhenFn(scope, locals);
  36776. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  36777. optionItems.push(optionItem);
  36778. selectValueMap[selectValue] = optionItem;
  36779. }
  36780. return {
  36781. items: optionItems,
  36782. selectValueMap: selectValueMap,
  36783. getOptionFromViewValue: function(value) {
  36784. return selectValueMap[getTrackByValue(value)];
  36785. },
  36786. getViewValueFromOption: function(option) {
  36787. // If the viewValue could be an object that may be mutated by the application,
  36788. // we need to make a copy and not return the reference to the value on the option.
  36789. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  36790. }
  36791. };
  36792. }
  36793. };
  36794. }
  36795. // we can't just jqLite('<option>') since jqLite is not smart enough
  36796. // to create it in <select> and IE barfs otherwise.
  36797. var optionTemplate = document.createElement('option'),
  36798. optGroupTemplate = document.createElement('optgroup');
  36799. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  36800. var selectCtrl = ctrls[0];
  36801. var ngModelCtrl = ctrls[1];
  36802. var multiple = attr.multiple;
  36803. // The emptyOption allows the application developer to provide their own custom "empty"
  36804. // option when the viewValue does not match any of the option values.
  36805. var emptyOption;
  36806. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  36807. if (children[i].value === '') {
  36808. emptyOption = children.eq(i);
  36809. break;
  36810. }
  36811. }
  36812. var providedEmptyOption = !!emptyOption;
  36813. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  36814. unknownOption.val('?');
  36815. var options;
  36816. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  36817. var renderEmptyOption = function() {
  36818. if (!providedEmptyOption) {
  36819. selectElement.prepend(emptyOption);
  36820. }
  36821. selectElement.val('');
  36822. emptyOption.prop('selected', true); // needed for IE
  36823. emptyOption.attr('selected', true);
  36824. };
  36825. var removeEmptyOption = function() {
  36826. if (!providedEmptyOption) {
  36827. emptyOption.remove();
  36828. }
  36829. };
  36830. var renderUnknownOption = function() {
  36831. selectElement.prepend(unknownOption);
  36832. selectElement.val('?');
  36833. unknownOption.prop('selected', true); // needed for IE
  36834. unknownOption.attr('selected', true);
  36835. };
  36836. var removeUnknownOption = function() {
  36837. unknownOption.remove();
  36838. };
  36839. // Update the controller methods for multiple selectable options
  36840. if (!multiple) {
  36841. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  36842. var option = options.getOptionFromViewValue(value);
  36843. if (option && !option.disabled) {
  36844. // Don't update the option when it is already selected.
  36845. // For example, the browser will select the first option by default. In that case,
  36846. // most properties are set automatically - except the `selected` attribute, which we
  36847. // set always
  36848. if (selectElement[0].value !== option.selectValue) {
  36849. removeUnknownOption();
  36850. removeEmptyOption();
  36851. selectElement[0].value = option.selectValue;
  36852. option.element.selected = true;
  36853. }
  36854. option.element.setAttribute('selected', 'selected');
  36855. } else {
  36856. if (value === null || providedEmptyOption) {
  36857. removeUnknownOption();
  36858. renderEmptyOption();
  36859. } else {
  36860. removeEmptyOption();
  36861. renderUnknownOption();
  36862. }
  36863. }
  36864. };
  36865. selectCtrl.readValue = function readNgOptionsValue() {
  36866. var selectedOption = options.selectValueMap[selectElement.val()];
  36867. if (selectedOption && !selectedOption.disabled) {
  36868. removeEmptyOption();
  36869. removeUnknownOption();
  36870. return options.getViewValueFromOption(selectedOption);
  36871. }
  36872. return null;
  36873. };
  36874. // If we are using `track by` then we must watch the tracked value on the model
  36875. // since ngModel only watches for object identity change
  36876. if (ngOptions.trackBy) {
  36877. scope.$watch(
  36878. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  36879. function() { ngModelCtrl.$render(); }
  36880. );
  36881. }
  36882. } else {
  36883. ngModelCtrl.$isEmpty = function(value) {
  36884. return !value || value.length === 0;
  36885. };
  36886. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  36887. options.items.forEach(function(option) {
  36888. option.element.selected = false;
  36889. });
  36890. if (value) {
  36891. value.forEach(function(item) {
  36892. var option = options.getOptionFromViewValue(item);
  36893. if (option && !option.disabled) option.element.selected = true;
  36894. });
  36895. }
  36896. };
  36897. selectCtrl.readValue = function readNgOptionsMultiple() {
  36898. var selectedValues = selectElement.val() || [],
  36899. selections = [];
  36900. forEach(selectedValues, function(value) {
  36901. var option = options.selectValueMap[value];
  36902. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  36903. });
  36904. return selections;
  36905. };
  36906. // If we are using `track by` then we must watch these tracked values on the model
  36907. // since ngModel only watches for object identity change
  36908. if (ngOptions.trackBy) {
  36909. scope.$watchCollection(function() {
  36910. if (isArray(ngModelCtrl.$viewValue)) {
  36911. return ngModelCtrl.$viewValue.map(function(value) {
  36912. return ngOptions.getTrackByValue(value);
  36913. });
  36914. }
  36915. }, function() {
  36916. ngModelCtrl.$render();
  36917. });
  36918. }
  36919. }
  36920. if (providedEmptyOption) {
  36921. // we need to remove it before calling selectElement.empty() because otherwise IE will
  36922. // remove the label from the element. wtf?
  36923. emptyOption.remove();
  36924. // compile the element since there might be bindings in it
  36925. $compile(emptyOption)(scope);
  36926. // remove the class, which is added automatically because we recompile the element and it
  36927. // becomes the compilation root
  36928. emptyOption.removeClass('ng-scope');
  36929. } else {
  36930. emptyOption = jqLite(optionTemplate.cloneNode(false));
  36931. }
  36932. // We need to do this here to ensure that the options object is defined
  36933. // when we first hit it in writeNgOptionsValue
  36934. updateOptions();
  36935. // We will re-render the option elements if the option values or labels change
  36936. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  36937. // ------------------------------------------------------------------ //
  36938. function updateOptionElement(option, element) {
  36939. option.element = element;
  36940. element.disabled = option.disabled;
  36941. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  36942. // selects in certain circumstances when multiple selects are next to each other and display
  36943. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  36944. // See https://github.com/angular/angular.js/issues/11314 for more info.
  36945. // This is unfortunately untestable with unit / e2e tests
  36946. if (option.label !== element.label) {
  36947. element.label = option.label;
  36948. element.textContent = option.label;
  36949. }
  36950. if (option.value !== element.value) element.value = option.selectValue;
  36951. }
  36952. function addOrReuseElement(parent, current, type, templateElement) {
  36953. var element;
  36954. // Check whether we can reuse the next element
  36955. if (current && lowercase(current.nodeName) === type) {
  36956. // The next element is the right type so reuse it
  36957. element = current;
  36958. } else {
  36959. // The next element is not the right type so create a new one
  36960. element = templateElement.cloneNode(false);
  36961. if (!current) {
  36962. // There are no more elements so just append it to the select
  36963. parent.appendChild(element);
  36964. } else {
  36965. // The next element is not a group so insert the new one
  36966. parent.insertBefore(element, current);
  36967. }
  36968. }
  36969. return element;
  36970. }
  36971. function removeExcessElements(current) {
  36972. var next;
  36973. while (current) {
  36974. next = current.nextSibling;
  36975. jqLiteRemove(current);
  36976. current = next;
  36977. }
  36978. }
  36979. function skipEmptyAndUnknownOptions(current) {
  36980. var emptyOption_ = emptyOption && emptyOption[0];
  36981. var unknownOption_ = unknownOption && unknownOption[0];
  36982. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  36983. // because the compiled empty option might have been replaced by a comment because
  36984. // it had an "element" transclusion directive on it (such as ngIf)
  36985. if (emptyOption_ || unknownOption_) {
  36986. while (current &&
  36987. (current === emptyOption_ ||
  36988. current === unknownOption_ ||
  36989. current.nodeType === NODE_TYPE_COMMENT ||
  36990. (nodeName_(current) === 'option' && current.value === ''))) {
  36991. current = current.nextSibling;
  36992. }
  36993. }
  36994. return current;
  36995. }
  36996. function updateOptions() {
  36997. var previousValue = options && selectCtrl.readValue();
  36998. options = ngOptions.getOptions();
  36999. var groupMap = {};
  37000. var currentElement = selectElement[0].firstChild;
  37001. // Ensure that the empty option is always there if it was explicitly provided
  37002. if (providedEmptyOption) {
  37003. selectElement.prepend(emptyOption);
  37004. }
  37005. currentElement = skipEmptyAndUnknownOptions(currentElement);
  37006. options.items.forEach(function updateOption(option) {
  37007. var group;
  37008. var groupElement;
  37009. var optionElement;
  37010. if (isDefined(option.group)) {
  37011. // This option is to live in a group
  37012. // See if we have already created this group
  37013. group = groupMap[option.group];
  37014. if (!group) {
  37015. // We have not already created this group
  37016. groupElement = addOrReuseElement(selectElement[0],
  37017. currentElement,
  37018. 'optgroup',
  37019. optGroupTemplate);
  37020. // Move to the next element
  37021. currentElement = groupElement.nextSibling;
  37022. // Update the label on the group element
  37023. groupElement.label = option.group;
  37024. // Store it for use later
  37025. group = groupMap[option.group] = {
  37026. groupElement: groupElement,
  37027. currentOptionElement: groupElement.firstChild
  37028. };
  37029. }
  37030. // So now we have a group for this option we add the option to the group
  37031. optionElement = addOrReuseElement(group.groupElement,
  37032. group.currentOptionElement,
  37033. 'option',
  37034. optionTemplate);
  37035. updateOptionElement(option, optionElement);
  37036. // Move to the next element
  37037. group.currentOptionElement = optionElement.nextSibling;
  37038. } else {
  37039. // This option is not in a group
  37040. optionElement = addOrReuseElement(selectElement[0],
  37041. currentElement,
  37042. 'option',
  37043. optionTemplate);
  37044. updateOptionElement(option, optionElement);
  37045. // Move to the next element
  37046. currentElement = optionElement.nextSibling;
  37047. }
  37048. });
  37049. // Now remove all excess options and group
  37050. Object.keys(groupMap).forEach(function(key) {
  37051. removeExcessElements(groupMap[key].currentOptionElement);
  37052. });
  37053. removeExcessElements(currentElement);
  37054. ngModelCtrl.$render();
  37055. // Check to see if the value has changed due to the update to the options
  37056. if (!ngModelCtrl.$isEmpty(previousValue)) {
  37057. var nextValue = selectCtrl.readValue();
  37058. var isNotPrimitive = ngOptions.trackBy || multiple;
  37059. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  37060. ngModelCtrl.$setViewValue(nextValue);
  37061. ngModelCtrl.$render();
  37062. }
  37063. }
  37064. }
  37065. }
  37066. return {
  37067. restrict: 'A',
  37068. terminal: true,
  37069. require: ['select', 'ngModel'],
  37070. link: {
  37071. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  37072. // Deactivate the SelectController.register method to prevent
  37073. // option directives from accidentally registering themselves
  37074. // (and unwanted $destroy handlers etc.)
  37075. ctrls[0].registerOption = noop;
  37076. },
  37077. post: ngOptionsPostLink
  37078. }
  37079. };
  37080. }];
  37081. /**
  37082. * @ngdoc directive
  37083. * @name ngPluralize
  37084. * @restrict EA
  37085. *
  37086. * @description
  37087. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  37088. * These rules are bundled with angular.js, but can be overridden
  37089. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  37090. * by specifying the mappings between
  37091. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  37092. * and the strings to be displayed.
  37093. *
  37094. * # Plural categories and explicit number rules
  37095. * There are two
  37096. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  37097. * in Angular's default en-US locale: "one" and "other".
  37098. *
  37099. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  37100. * any number that is not 1), an explicit number rule can only match one number. For example, the
  37101. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  37102. * and explicit number rules throughout the rest of this documentation.
  37103. *
  37104. * # Configuring ngPluralize
  37105. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  37106. * You can also provide an optional attribute, `offset`.
  37107. *
  37108. * The value of the `count` attribute can be either a string or an {@link guide/expression
  37109. * Angular expression}; these are evaluated on the current scope for its bound value.
  37110. *
  37111. * The `when` attribute specifies the mappings between plural categories and the actual
  37112. * string to be displayed. The value of the attribute should be a JSON object.
  37113. *
  37114. * The following example shows how to configure ngPluralize:
  37115. *
  37116. * ```html
  37117. * <ng-pluralize count="personCount"
  37118. when="{'0': 'Nobody is viewing.',
  37119. * 'one': '1 person is viewing.',
  37120. * 'other': '{} people are viewing.'}">
  37121. * </ng-pluralize>
  37122. *```
  37123. *
  37124. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  37125. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  37126. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  37127. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  37128. * show "a dozen people are viewing".
  37129. *
  37130. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  37131. * into pluralized strings. In the previous example, Angular will replace `{}` with
  37132. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  37133. * for <span ng-non-bindable>{{numberExpression}}</span>.
  37134. *
  37135. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  37136. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  37137. *
  37138. * # Configuring ngPluralize with offset
  37139. * The `offset` attribute allows further customization of pluralized text, which can result in
  37140. * a better user experience. For example, instead of the message "4 people are viewing this document",
  37141. * you might display "John, Kate and 2 others are viewing this document".
  37142. * The offset attribute allows you to offset a number by any desired value.
  37143. * Let's take a look at an example:
  37144. *
  37145. * ```html
  37146. * <ng-pluralize count="personCount" offset=2
  37147. * when="{'0': 'Nobody is viewing.',
  37148. * '1': '{{person1}} is viewing.',
  37149. * '2': '{{person1}} and {{person2}} are viewing.',
  37150. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  37151. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  37152. * </ng-pluralize>
  37153. * ```
  37154. *
  37155. * Notice that we are still using two plural categories(one, other), but we added
  37156. * three explicit number rules 0, 1 and 2.
  37157. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  37158. * When three people view the document, no explicit number rule is found, so
  37159. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  37160. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  37161. * is shown.
  37162. *
  37163. * Note that when you specify offsets, you must provide explicit number rules for
  37164. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  37165. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  37166. * plural categories "one" and "other".
  37167. *
  37168. * @param {string|expression} count The variable to be bound to.
  37169. * @param {string} when The mapping between plural category to its corresponding strings.
  37170. * @param {number=} offset Offset to deduct from the total number.
  37171. *
  37172. * @example
  37173. <example module="pluralizeExample">
  37174. <file name="index.html">
  37175. <script>
  37176. angular.module('pluralizeExample', [])
  37177. .controller('ExampleController', ['$scope', function($scope) {
  37178. $scope.person1 = 'Igor';
  37179. $scope.person2 = 'Misko';
  37180. $scope.personCount = 1;
  37181. }]);
  37182. </script>
  37183. <div ng-controller="ExampleController">
  37184. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  37185. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  37186. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  37187. <!--- Example with simple pluralization rules for en locale --->
  37188. Without Offset:
  37189. <ng-pluralize count="personCount"
  37190. when="{'0': 'Nobody is viewing.',
  37191. 'one': '1 person is viewing.',
  37192. 'other': '{} people are viewing.'}">
  37193. </ng-pluralize><br>
  37194. <!--- Example with offset --->
  37195. With Offset(2):
  37196. <ng-pluralize count="personCount" offset=2
  37197. when="{'0': 'Nobody is viewing.',
  37198. '1': '{{person1}} is viewing.',
  37199. '2': '{{person1}} and {{person2}} are viewing.',
  37200. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  37201. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  37202. </ng-pluralize>
  37203. </div>
  37204. </file>
  37205. <file name="protractor.js" type="protractor">
  37206. it('should show correct pluralized string', function() {
  37207. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  37208. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  37209. var countInput = element(by.model('personCount'));
  37210. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  37211. expect(withOffset.getText()).toEqual('Igor is viewing.');
  37212. countInput.clear();
  37213. countInput.sendKeys('0');
  37214. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  37215. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  37216. countInput.clear();
  37217. countInput.sendKeys('2');
  37218. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  37219. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  37220. countInput.clear();
  37221. countInput.sendKeys('3');
  37222. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  37223. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  37224. countInput.clear();
  37225. countInput.sendKeys('4');
  37226. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  37227. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  37228. });
  37229. it('should show data-bound names', function() {
  37230. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  37231. var personCount = element(by.model('personCount'));
  37232. var person1 = element(by.model('person1'));
  37233. var person2 = element(by.model('person2'));
  37234. personCount.clear();
  37235. personCount.sendKeys('4');
  37236. person1.clear();
  37237. person1.sendKeys('Di');
  37238. person2.clear();
  37239. person2.sendKeys('Vojta');
  37240. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  37241. });
  37242. </file>
  37243. </example>
  37244. */
  37245. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  37246. var BRACE = /{}/g,
  37247. IS_WHEN = /^when(Minus)?(.+)$/;
  37248. return {
  37249. link: function(scope, element, attr) {
  37250. var numberExp = attr.count,
  37251. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  37252. offset = attr.offset || 0,
  37253. whens = scope.$eval(whenExp) || {},
  37254. whensExpFns = {},
  37255. startSymbol = $interpolate.startSymbol(),
  37256. endSymbol = $interpolate.endSymbol(),
  37257. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  37258. watchRemover = angular.noop,
  37259. lastCount;
  37260. forEach(attr, function(expression, attributeName) {
  37261. var tmpMatch = IS_WHEN.exec(attributeName);
  37262. if (tmpMatch) {
  37263. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  37264. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  37265. }
  37266. });
  37267. forEach(whens, function(expression, key) {
  37268. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  37269. });
  37270. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  37271. var count = parseFloat(newVal);
  37272. var countIsNaN = isNaN(count);
  37273. if (!countIsNaN && !(count in whens)) {
  37274. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  37275. // Otherwise, check it against pluralization rules in $locale service.
  37276. count = $locale.pluralCat(count - offset);
  37277. }
  37278. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  37279. // In JS `NaN !== NaN`, so we have to explicitly check.
  37280. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  37281. watchRemover();
  37282. var whenExpFn = whensExpFns[count];
  37283. if (isUndefined(whenExpFn)) {
  37284. if (newVal != null) {
  37285. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  37286. }
  37287. watchRemover = noop;
  37288. updateElementText();
  37289. } else {
  37290. watchRemover = scope.$watch(whenExpFn, updateElementText);
  37291. }
  37292. lastCount = count;
  37293. }
  37294. });
  37295. function updateElementText(newText) {
  37296. element.text(newText || '');
  37297. }
  37298. }
  37299. };
  37300. }];
  37301. /**
  37302. * @ngdoc directive
  37303. * @name ngRepeat
  37304. * @multiElement
  37305. *
  37306. * @description
  37307. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  37308. * instance gets its own scope, where the given loop variable is set to the current collection item,
  37309. * and `$index` is set to the item index or key.
  37310. *
  37311. * Special properties are exposed on the local scope of each template instance, including:
  37312. *
  37313. * | Variable | Type | Details |
  37314. * |-----------|-----------------|-----------------------------------------------------------------------------|
  37315. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  37316. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  37317. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  37318. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  37319. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  37320. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  37321. *
  37322. * <div class="alert alert-info">
  37323. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  37324. * This may be useful when, for instance, nesting ngRepeats.
  37325. * </div>
  37326. *
  37327. *
  37328. * # Iterating over object properties
  37329. *
  37330. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  37331. * syntax:
  37332. *
  37333. * ```js
  37334. * <div ng-repeat="(key, value) in myObj"> ... </div>
  37335. * ```
  37336. *
  37337. * However, there are a limitations compared to array iteration:
  37338. *
  37339. * - The JavaScript specification does not define the order of keys
  37340. * returned for an object, so Angular relies on the order returned by the browser
  37341. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  37342. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  37343. * and reinstated. See the
  37344. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  37345. *
  37346. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  37347. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  37348. *
  37349. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  37350. * objects, and will throw if used with one.
  37351. *
  37352. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  37353. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  37354. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  37355. * or implement a `$watch` on the object yourself.
  37356. *
  37357. *
  37358. * # Tracking and Duplicates
  37359. *
  37360. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  37361. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  37362. *
  37363. * * When an item is added, a new instance of the template is added to the DOM.
  37364. * * When an item is removed, its template instance is removed from the DOM.
  37365. * * When items are reordered, their respective templates are reordered in the DOM.
  37366. *
  37367. * To minimize creation of DOM elements, `ngRepeat` uses a function
  37368. * to "keep track" of all items in the collection and their corresponding DOM elements.
  37369. * For example, if an item is added to the collection, ngRepeat will know that all other items
  37370. * already have DOM elements, and will not re-render them.
  37371. *
  37372. * The default tracking function (which tracks items by their identity) does not allow
  37373. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  37374. * to maintain a one-to-one mapping between collection items and DOM elements.
  37375. *
  37376. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  37377. * with your own using the `track by` expression.
  37378. *
  37379. * For example, you may track items by the index of each item in the collection, using the
  37380. * special scope property `$index`:
  37381. * ```html
  37382. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  37383. * {{n}}
  37384. * </div>
  37385. * ```
  37386. *
  37387. * You may also use arbitrary expressions in `track by`, including references to custom functions
  37388. * on the scope:
  37389. * ```html
  37390. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  37391. * {{n}}
  37392. * </div>
  37393. * ```
  37394. *
  37395. * <div class="alert alert-success">
  37396. * If you are working with objects that have an identifier property, you should track
  37397. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  37398. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  37399. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  37400. * this significantly improves rendering performance. If you don't have a unique identifier,
  37401. * `track by $index` can also provide a performance boost.
  37402. * </div>
  37403. * ```html
  37404. * <div ng-repeat="model in collection track by model.id">
  37405. * {{model.name}}
  37406. * </div>
  37407. * ```
  37408. *
  37409. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  37410. * `$id` function, which tracks items by their identity:
  37411. * ```html
  37412. * <div ng-repeat="obj in collection track by $id(obj)">
  37413. * {{obj.prop}}
  37414. * </div>
  37415. * ```
  37416. *
  37417. * <div class="alert alert-warning">
  37418. * **Note:** `track by` must always be the last expression:
  37419. * </div>
  37420. * ```
  37421. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  37422. * {{model.name}}
  37423. * </div>
  37424. * ```
  37425. *
  37426. * # Special repeat start and end points
  37427. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  37428. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  37429. * 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)
  37430. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  37431. *
  37432. * The example below makes use of this feature:
  37433. * ```html
  37434. * <header ng-repeat-start="item in items">
  37435. * Header {{ item }}
  37436. * </header>
  37437. * <div class="body">
  37438. * Body {{ item }}
  37439. * </div>
  37440. * <footer ng-repeat-end>
  37441. * Footer {{ item }}
  37442. * </footer>
  37443. * ```
  37444. *
  37445. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  37446. * ```html
  37447. * <header>
  37448. * Header A
  37449. * </header>
  37450. * <div class="body">
  37451. * Body A
  37452. * </div>
  37453. * <footer>
  37454. * Footer A
  37455. * </footer>
  37456. * <header>
  37457. * Header B
  37458. * </header>
  37459. * <div class="body">
  37460. * Body B
  37461. * </div>
  37462. * <footer>
  37463. * Footer B
  37464. * </footer>
  37465. * ```
  37466. *
  37467. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  37468. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  37469. *
  37470. * @animations
  37471. * | Animation | Occurs |
  37472. * |----------------------------------|-------------------------------------|
  37473. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  37474. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  37475. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  37476. *
  37477. * See the example below for defining CSS animations with ngRepeat.
  37478. *
  37479. * @element ANY
  37480. * @scope
  37481. * @priority 1000
  37482. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  37483. * formats are currently supported:
  37484. *
  37485. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  37486. * is a scope expression giving the collection to enumerate.
  37487. *
  37488. * For example: `album in artist.albums`.
  37489. *
  37490. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  37491. * and `expression` is the scope expression giving the collection to enumerate.
  37492. *
  37493. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  37494. *
  37495. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  37496. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  37497. * is specified, ng-repeat associates elements by identity. It is an error to have
  37498. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  37499. * mapped to the same DOM element, which is not possible.)
  37500. *
  37501. * Note that the tracking expression must come last, after any filters, and the alias expression.
  37502. *
  37503. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  37504. * will be associated by item identity in the array.
  37505. *
  37506. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  37507. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  37508. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  37509. * element in the same way in the DOM.
  37510. *
  37511. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  37512. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  37513. * property is same.
  37514. *
  37515. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  37516. * to items in conjunction with a tracking expression.
  37517. *
  37518. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  37519. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  37520. * when a filter is active on the repeater, but the filtered result set is empty.
  37521. *
  37522. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  37523. * the items have been processed through the filter.
  37524. *
  37525. * 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
  37526. * (and not as operator, inside an expression).
  37527. *
  37528. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  37529. *
  37530. * @example
  37531. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  37532. * results by name. New (entering) and removed (leaving) items are animated.
  37533. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  37534. <file name="index.html">
  37535. <div ng-controller="repeatController">
  37536. I have {{friends.length}} friends. They are:
  37537. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  37538. <ul class="example-animate-container">
  37539. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  37540. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  37541. </li>
  37542. <li class="animate-repeat" ng-if="results.length == 0">
  37543. <strong>No results found...</strong>
  37544. </li>
  37545. </ul>
  37546. </div>
  37547. </file>
  37548. <file name="script.js">
  37549. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  37550. $scope.friends = [
  37551. {name:'John', age:25, gender:'boy'},
  37552. {name:'Jessie', age:30, gender:'girl'},
  37553. {name:'Johanna', age:28, gender:'girl'},
  37554. {name:'Joy', age:15, gender:'girl'},
  37555. {name:'Mary', age:28, gender:'girl'},
  37556. {name:'Peter', age:95, gender:'boy'},
  37557. {name:'Sebastian', age:50, gender:'boy'},
  37558. {name:'Erika', age:27, gender:'girl'},
  37559. {name:'Patrick', age:40, gender:'boy'},
  37560. {name:'Samantha', age:60, gender:'girl'}
  37561. ];
  37562. });
  37563. </file>
  37564. <file name="animations.css">
  37565. .example-animate-container {
  37566. background:white;
  37567. border:1px solid black;
  37568. list-style:none;
  37569. margin:0;
  37570. padding:0 10px;
  37571. }
  37572. .animate-repeat {
  37573. line-height:30px;
  37574. list-style:none;
  37575. box-sizing:border-box;
  37576. }
  37577. .animate-repeat.ng-move,
  37578. .animate-repeat.ng-enter,
  37579. .animate-repeat.ng-leave {
  37580. transition:all linear 0.5s;
  37581. }
  37582. .animate-repeat.ng-leave.ng-leave-active,
  37583. .animate-repeat.ng-move,
  37584. .animate-repeat.ng-enter {
  37585. opacity:0;
  37586. max-height:0;
  37587. }
  37588. .animate-repeat.ng-leave,
  37589. .animate-repeat.ng-move.ng-move-active,
  37590. .animate-repeat.ng-enter.ng-enter-active {
  37591. opacity:1;
  37592. max-height:30px;
  37593. }
  37594. </file>
  37595. <file name="protractor.js" type="protractor">
  37596. var friends = element.all(by.repeater('friend in friends'));
  37597. it('should render initial data set', function() {
  37598. expect(friends.count()).toBe(10);
  37599. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  37600. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  37601. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  37602. expect(element(by.binding('friends.length')).getText())
  37603. .toMatch("I have 10 friends. They are:");
  37604. });
  37605. it('should update repeater when filter predicate changes', function() {
  37606. expect(friends.count()).toBe(10);
  37607. element(by.model('q')).sendKeys('ma');
  37608. expect(friends.count()).toBe(2);
  37609. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  37610. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  37611. });
  37612. </file>
  37613. </example>
  37614. */
  37615. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  37616. var NG_REMOVED = '$$NG_REMOVED';
  37617. var ngRepeatMinErr = minErr('ngRepeat');
  37618. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  37619. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  37620. scope[valueIdentifier] = value;
  37621. if (keyIdentifier) scope[keyIdentifier] = key;
  37622. scope.$index = index;
  37623. scope.$first = (index === 0);
  37624. scope.$last = (index === (arrayLength - 1));
  37625. scope.$middle = !(scope.$first || scope.$last);
  37626. // jshint bitwise: false
  37627. scope.$odd = !(scope.$even = (index&1) === 0);
  37628. // jshint bitwise: true
  37629. };
  37630. var getBlockStart = function(block) {
  37631. return block.clone[0];
  37632. };
  37633. var getBlockEnd = function(block) {
  37634. return block.clone[block.clone.length - 1];
  37635. };
  37636. return {
  37637. restrict: 'A',
  37638. multiElement: true,
  37639. transclude: 'element',
  37640. priority: 1000,
  37641. terminal: true,
  37642. $$tlb: true,
  37643. compile: function ngRepeatCompile($element, $attr) {
  37644. var expression = $attr.ngRepeat;
  37645. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  37646. 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*$/);
  37647. if (!match) {
  37648. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  37649. expression);
  37650. }
  37651. var lhs = match[1];
  37652. var rhs = match[2];
  37653. var aliasAs = match[3];
  37654. var trackByExp = match[4];
  37655. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  37656. if (!match) {
  37657. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  37658. lhs);
  37659. }
  37660. var valueIdentifier = match[3] || match[1];
  37661. var keyIdentifier = match[2];
  37662. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  37663. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  37664. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  37665. aliasAs);
  37666. }
  37667. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  37668. var hashFnLocals = {$id: hashKey};
  37669. if (trackByExp) {
  37670. trackByExpGetter = $parse(trackByExp);
  37671. } else {
  37672. trackByIdArrayFn = function(key, value) {
  37673. return hashKey(value);
  37674. };
  37675. trackByIdObjFn = function(key) {
  37676. return key;
  37677. };
  37678. }
  37679. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  37680. if (trackByExpGetter) {
  37681. trackByIdExpFn = function(key, value, index) {
  37682. // assign key, value, and $index to the locals so that they can be used in hash functions
  37683. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  37684. hashFnLocals[valueIdentifier] = value;
  37685. hashFnLocals.$index = index;
  37686. return trackByExpGetter($scope, hashFnLocals);
  37687. };
  37688. }
  37689. // Store a list of elements from previous run. This is a hash where key is the item from the
  37690. // iterator, and the value is objects with following properties.
  37691. // - scope: bound scope
  37692. // - element: previous element.
  37693. // - index: position
  37694. //
  37695. // We are using no-proto object so that we don't need to guard against inherited props via
  37696. // hasOwnProperty.
  37697. var lastBlockMap = createMap();
  37698. //watch props
  37699. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  37700. var index, length,
  37701. previousNode = $element[0], // node that cloned nodes should be inserted after
  37702. // initialized to the comment node anchor
  37703. nextNode,
  37704. // Same as lastBlockMap but it has the current state. It will become the
  37705. // lastBlockMap on the next iteration.
  37706. nextBlockMap = createMap(),
  37707. collectionLength,
  37708. key, value, // key/value of iteration
  37709. trackById,
  37710. trackByIdFn,
  37711. collectionKeys,
  37712. block, // last object information {scope, element, id}
  37713. nextBlockOrder,
  37714. elementsToRemove;
  37715. if (aliasAs) {
  37716. $scope[aliasAs] = collection;
  37717. }
  37718. if (isArrayLike(collection)) {
  37719. collectionKeys = collection;
  37720. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  37721. } else {
  37722. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  37723. // if object, extract keys, in enumeration order, unsorted
  37724. collectionKeys = [];
  37725. for (var itemKey in collection) {
  37726. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  37727. collectionKeys.push(itemKey);
  37728. }
  37729. }
  37730. }
  37731. collectionLength = collectionKeys.length;
  37732. nextBlockOrder = new Array(collectionLength);
  37733. // locate existing items
  37734. for (index = 0; index < collectionLength; index++) {
  37735. key = (collection === collectionKeys) ? index : collectionKeys[index];
  37736. value = collection[key];
  37737. trackById = trackByIdFn(key, value, index);
  37738. if (lastBlockMap[trackById]) {
  37739. // found previously seen block
  37740. block = lastBlockMap[trackById];
  37741. delete lastBlockMap[trackById];
  37742. nextBlockMap[trackById] = block;
  37743. nextBlockOrder[index] = block;
  37744. } else if (nextBlockMap[trackById]) {
  37745. // if collision detected. restore lastBlockMap and throw an error
  37746. forEach(nextBlockOrder, function(block) {
  37747. if (block && block.scope) lastBlockMap[block.id] = block;
  37748. });
  37749. throw ngRepeatMinErr('dupes',
  37750. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  37751. expression, trackById, value);
  37752. } else {
  37753. // new never before seen block
  37754. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  37755. nextBlockMap[trackById] = true;
  37756. }
  37757. }
  37758. // remove leftover items
  37759. for (var blockKey in lastBlockMap) {
  37760. block = lastBlockMap[blockKey];
  37761. elementsToRemove = getBlockNodes(block.clone);
  37762. $animate.leave(elementsToRemove);
  37763. if (elementsToRemove[0].parentNode) {
  37764. // if the element was not removed yet because of pending animation, mark it as deleted
  37765. // so that we can ignore it later
  37766. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  37767. elementsToRemove[index][NG_REMOVED] = true;
  37768. }
  37769. }
  37770. block.scope.$destroy();
  37771. }
  37772. // we are not using forEach for perf reasons (trying to avoid #call)
  37773. for (index = 0; index < collectionLength; index++) {
  37774. key = (collection === collectionKeys) ? index : collectionKeys[index];
  37775. value = collection[key];
  37776. block = nextBlockOrder[index];
  37777. if (block.scope) {
  37778. // if we have already seen this object, then we need to reuse the
  37779. // associated scope/element
  37780. nextNode = previousNode;
  37781. // skip nodes that are already pending removal via leave animation
  37782. do {
  37783. nextNode = nextNode.nextSibling;
  37784. } while (nextNode && nextNode[NG_REMOVED]);
  37785. if (getBlockStart(block) != nextNode) {
  37786. // existing item which got moved
  37787. $animate.move(getBlockNodes(block.clone), null, previousNode);
  37788. }
  37789. previousNode = getBlockEnd(block);
  37790. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  37791. } else {
  37792. // new item which we don't know about
  37793. $transclude(function ngRepeatTransclude(clone, scope) {
  37794. block.scope = scope;
  37795. // http://jsperf.com/clone-vs-createcomment
  37796. var endNode = ngRepeatEndComment.cloneNode(false);
  37797. clone[clone.length++] = endNode;
  37798. $animate.enter(clone, null, previousNode);
  37799. previousNode = endNode;
  37800. // Note: We only need the first/last node of the cloned nodes.
  37801. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  37802. // by a directive with templateUrl when its template arrives.
  37803. block.clone = clone;
  37804. nextBlockMap[block.id] = block;
  37805. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  37806. });
  37807. }
  37808. }
  37809. lastBlockMap = nextBlockMap;
  37810. });
  37811. };
  37812. }
  37813. };
  37814. }];
  37815. var NG_HIDE_CLASS = 'ng-hide';
  37816. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  37817. /**
  37818. * @ngdoc directive
  37819. * @name ngShow
  37820. * @multiElement
  37821. *
  37822. * @description
  37823. * The `ngShow` directive shows or hides the given HTML element based on the expression
  37824. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  37825. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  37826. * in AngularJS and sets the display style to none (using an !important flag).
  37827. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  37828. *
  37829. * ```html
  37830. * <!-- when $scope.myValue is truthy (element is visible) -->
  37831. * <div ng-show="myValue"></div>
  37832. *
  37833. * <!-- when $scope.myValue is falsy (element is hidden) -->
  37834. * <div ng-show="myValue" class="ng-hide"></div>
  37835. * ```
  37836. *
  37837. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  37838. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  37839. * from the element causing the element not to appear hidden.
  37840. *
  37841. * ## Why is !important used?
  37842. *
  37843. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  37844. * can be easily overridden by heavier selectors. For example, something as simple
  37845. * as changing the display style on a HTML list item would make hidden elements appear visible.
  37846. * This also becomes a bigger issue when dealing with CSS frameworks.
  37847. *
  37848. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  37849. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  37850. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  37851. *
  37852. * ### Overriding `.ng-hide`
  37853. *
  37854. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  37855. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  37856. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  37857. * with extra animation classes that can be added.
  37858. *
  37859. * ```css
  37860. * .ng-hide:not(.ng-hide-animate) {
  37861. * /&#42; this is just another form of hiding an element &#42;/
  37862. * display: block!important;
  37863. * position: absolute;
  37864. * top: -9999px;
  37865. * left: -9999px;
  37866. * }
  37867. * ```
  37868. *
  37869. * By default you don't need to override in CSS anything and the animations will work around the display style.
  37870. *
  37871. * ## A note about animations with `ngShow`
  37872. *
  37873. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  37874. * is true and false. This system works like the animation system present with ngClass except that
  37875. * you must also include the !important flag to override the display property
  37876. * so that you can perform an animation when the element is hidden during the time of the animation.
  37877. *
  37878. * ```css
  37879. * //
  37880. * //a working example can be found at the bottom of this page
  37881. * //
  37882. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  37883. * /&#42; this is required as of 1.3x to properly
  37884. * apply all styling in a show/hide animation &#42;/
  37885. * transition: 0s linear all;
  37886. * }
  37887. *
  37888. * .my-element.ng-hide-add-active,
  37889. * .my-element.ng-hide-remove-active {
  37890. * /&#42; the transition is defined in the active class &#42;/
  37891. * transition: 1s linear all;
  37892. * }
  37893. *
  37894. * .my-element.ng-hide-add { ... }
  37895. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  37896. * .my-element.ng-hide-remove { ... }
  37897. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  37898. * ```
  37899. *
  37900. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  37901. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  37902. *
  37903. * @animations
  37904. * | Animation | Occurs |
  37905. * |----------------------------------|-------------------------------------|
  37906. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden |
  37907. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  37908. *
  37909. * @element ANY
  37910. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  37911. * then the element is shown or hidden respectively.
  37912. *
  37913. * @example
  37914. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  37915. <file name="index.html">
  37916. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  37917. <div>
  37918. Show:
  37919. <div class="check-element animate-show" ng-show="checked">
  37920. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  37921. </div>
  37922. </div>
  37923. <div>
  37924. Hide:
  37925. <div class="check-element animate-show" ng-hide="checked">
  37926. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  37927. </div>
  37928. </div>
  37929. </file>
  37930. <file name="glyphicons.css">
  37931. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  37932. </file>
  37933. <file name="animations.css">
  37934. .animate-show {
  37935. line-height: 20px;
  37936. opacity: 1;
  37937. padding: 10px;
  37938. border: 1px solid black;
  37939. background: white;
  37940. }
  37941. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  37942. transition: all linear 0.5s;
  37943. }
  37944. .animate-show.ng-hide {
  37945. line-height: 0;
  37946. opacity: 0;
  37947. padding: 0 10px;
  37948. }
  37949. .check-element {
  37950. padding: 10px;
  37951. border: 1px solid black;
  37952. background: white;
  37953. }
  37954. </file>
  37955. <file name="protractor.js" type="protractor">
  37956. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  37957. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  37958. it('should check ng-show / ng-hide', function() {
  37959. expect(thumbsUp.isDisplayed()).toBeFalsy();
  37960. expect(thumbsDown.isDisplayed()).toBeTruthy();
  37961. element(by.model('checked')).click();
  37962. expect(thumbsUp.isDisplayed()).toBeTruthy();
  37963. expect(thumbsDown.isDisplayed()).toBeFalsy();
  37964. });
  37965. </file>
  37966. </example>
  37967. */
  37968. var ngShowDirective = ['$animate', function($animate) {
  37969. return {
  37970. restrict: 'A',
  37971. multiElement: true,
  37972. link: function(scope, element, attr) {
  37973. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  37974. // we're adding a temporary, animation-specific class for ng-hide since this way
  37975. // we can control when the element is actually displayed on screen without having
  37976. // to have a global/greedy CSS selector that breaks when other animations are run.
  37977. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  37978. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  37979. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  37980. });
  37981. });
  37982. }
  37983. };
  37984. }];
  37985. /**
  37986. * @ngdoc directive
  37987. * @name ngHide
  37988. * @multiElement
  37989. *
  37990. * @description
  37991. * The `ngHide` directive shows or hides the given HTML element based on the expression
  37992. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  37993. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  37994. * in AngularJS and sets the display style to none (using an !important flag).
  37995. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  37996. *
  37997. * ```html
  37998. * <!-- when $scope.myValue is truthy (element is hidden) -->
  37999. * <div ng-hide="myValue" class="ng-hide"></div>
  38000. *
  38001. * <!-- when $scope.myValue is falsy (element is visible) -->
  38002. * <div ng-hide="myValue"></div>
  38003. * ```
  38004. *
  38005. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  38006. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  38007. * from the element causing the element not to appear hidden.
  38008. *
  38009. * ## Why is !important used?
  38010. *
  38011. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  38012. * can be easily overridden by heavier selectors. For example, something as simple
  38013. * as changing the display style on a HTML list item would make hidden elements appear visible.
  38014. * This also becomes a bigger issue when dealing with CSS frameworks.
  38015. *
  38016. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  38017. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  38018. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  38019. *
  38020. * ### Overriding `.ng-hide`
  38021. *
  38022. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  38023. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  38024. * class in CSS:
  38025. *
  38026. * ```css
  38027. * .ng-hide {
  38028. * /&#42; this is just another form of hiding an element &#42;/
  38029. * display: block!important;
  38030. * position: absolute;
  38031. * top: -9999px;
  38032. * left: -9999px;
  38033. * }
  38034. * ```
  38035. *
  38036. * By default you don't need to override in CSS anything and the animations will work around the display style.
  38037. *
  38038. * ## A note about animations with `ngHide`
  38039. *
  38040. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  38041. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  38042. * CSS class is added and removed for you instead of your own CSS class.
  38043. *
  38044. * ```css
  38045. * //
  38046. * //a working example can be found at the bottom of this page
  38047. * //
  38048. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  38049. * transition: 0.5s linear all;
  38050. * }
  38051. *
  38052. * .my-element.ng-hide-add { ... }
  38053. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  38054. * .my-element.ng-hide-remove { ... }
  38055. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  38056. * ```
  38057. *
  38058. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  38059. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  38060. *
  38061. * @animations
  38062. * | Animation | Occurs |
  38063. * |----------------------------------|-------------------------------------|
  38064. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  38065. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  38066. *
  38067. *
  38068. * @element ANY
  38069. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  38070. * the element is shown or hidden respectively.
  38071. *
  38072. * @example
  38073. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  38074. <file name="index.html">
  38075. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  38076. <div>
  38077. Show:
  38078. <div class="check-element animate-hide" ng-show="checked">
  38079. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  38080. </div>
  38081. </div>
  38082. <div>
  38083. Hide:
  38084. <div class="check-element animate-hide" ng-hide="checked">
  38085. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  38086. </div>
  38087. </div>
  38088. </file>
  38089. <file name="glyphicons.css">
  38090. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  38091. </file>
  38092. <file name="animations.css">
  38093. .animate-hide {
  38094. transition: all linear 0.5s;
  38095. line-height: 20px;
  38096. opacity: 1;
  38097. padding: 10px;
  38098. border: 1px solid black;
  38099. background: white;
  38100. }
  38101. .animate-hide.ng-hide {
  38102. line-height: 0;
  38103. opacity: 0;
  38104. padding: 0 10px;
  38105. }
  38106. .check-element {
  38107. padding: 10px;
  38108. border: 1px solid black;
  38109. background: white;
  38110. }
  38111. </file>
  38112. <file name="protractor.js" type="protractor">
  38113. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  38114. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  38115. it('should check ng-show / ng-hide', function() {
  38116. expect(thumbsUp.isDisplayed()).toBeFalsy();
  38117. expect(thumbsDown.isDisplayed()).toBeTruthy();
  38118. element(by.model('checked')).click();
  38119. expect(thumbsUp.isDisplayed()).toBeTruthy();
  38120. expect(thumbsDown.isDisplayed()).toBeFalsy();
  38121. });
  38122. </file>
  38123. </example>
  38124. */
  38125. var ngHideDirective = ['$animate', function($animate) {
  38126. return {
  38127. restrict: 'A',
  38128. multiElement: true,
  38129. link: function(scope, element, attr) {
  38130. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  38131. // The comment inside of the ngShowDirective explains why we add and
  38132. // remove a temporary class for the show/hide animation
  38133. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  38134. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  38135. });
  38136. });
  38137. }
  38138. };
  38139. }];
  38140. /**
  38141. * @ngdoc directive
  38142. * @name ngStyle
  38143. * @restrict AC
  38144. *
  38145. * @description
  38146. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  38147. *
  38148. * @element ANY
  38149. * @param {expression} ngStyle
  38150. *
  38151. * {@link guide/expression Expression} which evals to an
  38152. * object whose keys are CSS style names and values are corresponding values for those CSS
  38153. * keys.
  38154. *
  38155. * Since some CSS style names are not valid keys for an object, they must be quoted.
  38156. * See the 'background-color' style in the example below.
  38157. *
  38158. * @example
  38159. <example>
  38160. <file name="index.html">
  38161. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  38162. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  38163. <input type="button" value="clear" ng-click="myStyle={}">
  38164. <br/>
  38165. <span ng-style="myStyle">Sample Text</span>
  38166. <pre>myStyle={{myStyle}}</pre>
  38167. </file>
  38168. <file name="style.css">
  38169. span {
  38170. color: black;
  38171. }
  38172. </file>
  38173. <file name="protractor.js" type="protractor">
  38174. var colorSpan = element(by.css('span'));
  38175. it('should check ng-style', function() {
  38176. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  38177. element(by.css('input[value=\'set color\']')).click();
  38178. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  38179. element(by.css('input[value=clear]')).click();
  38180. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  38181. });
  38182. </file>
  38183. </example>
  38184. */
  38185. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  38186. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  38187. if (oldStyles && (newStyles !== oldStyles)) {
  38188. forEach(oldStyles, function(val, style) { element.css(style, '');});
  38189. }
  38190. if (newStyles) element.css(newStyles);
  38191. }, true);
  38192. });
  38193. /**
  38194. * @ngdoc directive
  38195. * @name ngSwitch
  38196. * @restrict EA
  38197. *
  38198. * @description
  38199. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  38200. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  38201. * as specified in the template.
  38202. *
  38203. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  38204. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  38205. * matches the value obtained from the evaluated expression. In other words, you define a container element
  38206. * (where you place the directive), place an expression on the **`on="..."` attribute**
  38207. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  38208. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  38209. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  38210. * attribute is displayed.
  38211. *
  38212. * <div class="alert alert-info">
  38213. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  38214. * as literal string values to match against.
  38215. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  38216. * value of the expression `$scope.someVal`.
  38217. * </div>
  38218. * @animations
  38219. * | Animation | Occurs |
  38220. * |----------------------------------|-------------------------------------|
  38221. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  38222. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  38223. *
  38224. * @usage
  38225. *
  38226. * ```
  38227. * <ANY ng-switch="expression">
  38228. * <ANY ng-switch-when="matchValue1">...</ANY>
  38229. * <ANY ng-switch-when="matchValue2">...</ANY>
  38230. * <ANY ng-switch-default>...</ANY>
  38231. * </ANY>
  38232. * ```
  38233. *
  38234. *
  38235. * @scope
  38236. * @priority 1200
  38237. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  38238. * On child elements add:
  38239. *
  38240. * * `ngSwitchWhen`: the case statement to match against. If match then this
  38241. * case will be displayed. If the same match appears multiple times, all the
  38242. * elements will be displayed.
  38243. * * `ngSwitchDefault`: the default case when no other case match. If there
  38244. * are multiple default cases, all of them will be displayed when no other
  38245. * case match.
  38246. *
  38247. *
  38248. * @example
  38249. <example module="switchExample" deps="angular-animate.js" animations="true">
  38250. <file name="index.html">
  38251. <div ng-controller="ExampleController">
  38252. <select ng-model="selection" ng-options="item for item in items">
  38253. </select>
  38254. <code>selection={{selection}}</code>
  38255. <hr/>
  38256. <div class="animate-switch-container"
  38257. ng-switch on="selection">
  38258. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  38259. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  38260. <div class="animate-switch" ng-switch-default>default</div>
  38261. </div>
  38262. </div>
  38263. </file>
  38264. <file name="script.js">
  38265. angular.module('switchExample', ['ngAnimate'])
  38266. .controller('ExampleController', ['$scope', function($scope) {
  38267. $scope.items = ['settings', 'home', 'other'];
  38268. $scope.selection = $scope.items[0];
  38269. }]);
  38270. </file>
  38271. <file name="animations.css">
  38272. .animate-switch-container {
  38273. position:relative;
  38274. background:white;
  38275. border:1px solid black;
  38276. height:40px;
  38277. overflow:hidden;
  38278. }
  38279. .animate-switch {
  38280. padding:10px;
  38281. }
  38282. .animate-switch.ng-animate {
  38283. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  38284. position:absolute;
  38285. top:0;
  38286. left:0;
  38287. right:0;
  38288. bottom:0;
  38289. }
  38290. .animate-switch.ng-leave.ng-leave-active,
  38291. .animate-switch.ng-enter {
  38292. top:-50px;
  38293. }
  38294. .animate-switch.ng-leave,
  38295. .animate-switch.ng-enter.ng-enter-active {
  38296. top:0;
  38297. }
  38298. </file>
  38299. <file name="protractor.js" type="protractor">
  38300. var switchElem = element(by.css('[ng-switch]'));
  38301. var select = element(by.model('selection'));
  38302. it('should start in settings', function() {
  38303. expect(switchElem.getText()).toMatch(/Settings Div/);
  38304. });
  38305. it('should change to home', function() {
  38306. select.all(by.css('option')).get(1).click();
  38307. expect(switchElem.getText()).toMatch(/Home Span/);
  38308. });
  38309. it('should select default', function() {
  38310. select.all(by.css('option')).get(2).click();
  38311. expect(switchElem.getText()).toMatch(/default/);
  38312. });
  38313. </file>
  38314. </example>
  38315. */
  38316. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  38317. return {
  38318. require: 'ngSwitch',
  38319. // asks for $scope to fool the BC controller module
  38320. controller: ['$scope', function ngSwitchController() {
  38321. this.cases = {};
  38322. }],
  38323. link: function(scope, element, attr, ngSwitchController) {
  38324. var watchExpr = attr.ngSwitch || attr.on,
  38325. selectedTranscludes = [],
  38326. selectedElements = [],
  38327. previousLeaveAnimations = [],
  38328. selectedScopes = [];
  38329. var spliceFactory = function(array, index) {
  38330. return function() { array.splice(index, 1); };
  38331. };
  38332. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  38333. var i, ii;
  38334. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  38335. $animate.cancel(previousLeaveAnimations[i]);
  38336. }
  38337. previousLeaveAnimations.length = 0;
  38338. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  38339. var selected = getBlockNodes(selectedElements[i].clone);
  38340. selectedScopes[i].$destroy();
  38341. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  38342. promise.then(spliceFactory(previousLeaveAnimations, i));
  38343. }
  38344. selectedElements.length = 0;
  38345. selectedScopes.length = 0;
  38346. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  38347. forEach(selectedTranscludes, function(selectedTransclude) {
  38348. selectedTransclude.transclude(function(caseElement, selectedScope) {
  38349. selectedScopes.push(selectedScope);
  38350. var anchor = selectedTransclude.element;
  38351. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  38352. var block = { clone: caseElement };
  38353. selectedElements.push(block);
  38354. $animate.enter(caseElement, anchor.parent(), anchor);
  38355. });
  38356. });
  38357. }
  38358. });
  38359. }
  38360. };
  38361. }];
  38362. var ngSwitchWhenDirective = ngDirective({
  38363. transclude: 'element',
  38364. priority: 1200,
  38365. require: '^ngSwitch',
  38366. multiElement: true,
  38367. link: function(scope, element, attrs, ctrl, $transclude) {
  38368. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  38369. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  38370. }
  38371. });
  38372. var ngSwitchDefaultDirective = ngDirective({
  38373. transclude: 'element',
  38374. priority: 1200,
  38375. require: '^ngSwitch',
  38376. multiElement: true,
  38377. link: function(scope, element, attr, ctrl, $transclude) {
  38378. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  38379. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  38380. }
  38381. });
  38382. /**
  38383. * @ngdoc directive
  38384. * @name ngTransclude
  38385. * @restrict EAC
  38386. *
  38387. * @description
  38388. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  38389. *
  38390. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  38391. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  38392. *
  38393. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  38394. * content of this element will be removed before the transcluded content is inserted.
  38395. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  38396. * that no transcluded content is provided.
  38397. *
  38398. * @element ANY
  38399. *
  38400. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  38401. * or its value is the same as the name of the attribute then the default slot is used.
  38402. *
  38403. * @example
  38404. * ### Basic transclusion
  38405. * This example demonstrates basic transclusion of content into a component directive.
  38406. * <example name="simpleTranscludeExample" module="transcludeExample">
  38407. * <file name="index.html">
  38408. * <script>
  38409. * angular.module('transcludeExample', [])
  38410. * .directive('pane', function(){
  38411. * return {
  38412. * restrict: 'E',
  38413. * transclude: true,
  38414. * scope: { title:'@' },
  38415. * template: '<div style="border: 1px solid black;">' +
  38416. * '<div style="background-color: gray">{{title}}</div>' +
  38417. * '<ng-transclude></ng-transclude>' +
  38418. * '</div>'
  38419. * };
  38420. * })
  38421. * .controller('ExampleController', ['$scope', function($scope) {
  38422. * $scope.title = 'Lorem Ipsum';
  38423. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  38424. * }]);
  38425. * </script>
  38426. * <div ng-controller="ExampleController">
  38427. * <input ng-model="title" aria-label="title"> <br/>
  38428. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  38429. * <pane title="{{title}}">{{text}}</pane>
  38430. * </div>
  38431. * </file>
  38432. * <file name="protractor.js" type="protractor">
  38433. * it('should have transcluded', function() {
  38434. * var titleElement = element(by.model('title'));
  38435. * titleElement.clear();
  38436. * titleElement.sendKeys('TITLE');
  38437. * var textElement = element(by.model('text'));
  38438. * textElement.clear();
  38439. * textElement.sendKeys('TEXT');
  38440. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  38441. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  38442. * });
  38443. * </file>
  38444. * </example>
  38445. *
  38446. * @example
  38447. * ### Transclude fallback content
  38448. * This example shows how to use `NgTransclude` with fallback content, that
  38449. * is displayed if no transcluded content is provided.
  38450. *
  38451. * <example module="transcludeFallbackContentExample">
  38452. * <file name="index.html">
  38453. * <script>
  38454. * angular.module('transcludeFallbackContentExample', [])
  38455. * .directive('myButton', function(){
  38456. * return {
  38457. * restrict: 'E',
  38458. * transclude: true,
  38459. * scope: true,
  38460. * template: '<button style="cursor: pointer;">' +
  38461. * '<ng-transclude>' +
  38462. * '<b style="color: red;">Button1</b>' +
  38463. * '</ng-transclude>' +
  38464. * '</button>'
  38465. * };
  38466. * });
  38467. * </script>
  38468. * <!-- fallback button content -->
  38469. * <my-button id="fallback"></my-button>
  38470. * <!-- modified button content -->
  38471. * <my-button id="modified">
  38472. * <i style="color: green;">Button2</i>
  38473. * </my-button>
  38474. * </file>
  38475. * <file name="protractor.js" type="protractor">
  38476. * it('should have different transclude element content', function() {
  38477. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  38478. * expect(element(by.id('modified')).getText()).toBe('Button2');
  38479. * });
  38480. * </file>
  38481. * </example>
  38482. *
  38483. * @example
  38484. * ### Multi-slot transclusion
  38485. * This example demonstrates using multi-slot transclusion in a component directive.
  38486. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  38487. * <file name="index.html">
  38488. * <style>
  38489. * .title, .footer {
  38490. * background-color: gray
  38491. * }
  38492. * </style>
  38493. * <div ng-controller="ExampleController">
  38494. * <input ng-model="title" aria-label="title"> <br/>
  38495. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  38496. * <pane>
  38497. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  38498. * <pane-body><p>{{text}}</p></pane-body>
  38499. * </pane>
  38500. * </div>
  38501. * </file>
  38502. * <file name="app.js">
  38503. * angular.module('multiSlotTranscludeExample', [])
  38504. * .directive('pane', function(){
  38505. * return {
  38506. * restrict: 'E',
  38507. * transclude: {
  38508. * 'title': '?paneTitle',
  38509. * 'body': 'paneBody',
  38510. * 'footer': '?paneFooter'
  38511. * },
  38512. * template: '<div style="border: 1px solid black;">' +
  38513. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  38514. * '<div ng-transclude="body"></div>' +
  38515. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  38516. * '</div>'
  38517. * };
  38518. * })
  38519. * .controller('ExampleController', ['$scope', function($scope) {
  38520. * $scope.title = 'Lorem Ipsum';
  38521. * $scope.link = "https://google.com";
  38522. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  38523. * }]);
  38524. * </file>
  38525. * <file name="protractor.js" type="protractor">
  38526. * it('should have transcluded the title and the body', function() {
  38527. * var titleElement = element(by.model('title'));
  38528. * titleElement.clear();
  38529. * titleElement.sendKeys('TITLE');
  38530. * var textElement = element(by.model('text'));
  38531. * textElement.clear();
  38532. * textElement.sendKeys('TEXT');
  38533. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  38534. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  38535. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  38536. * });
  38537. * </file>
  38538. * </example>
  38539. */
  38540. var ngTranscludeMinErr = minErr('ngTransclude');
  38541. var ngTranscludeDirective = ngDirective({
  38542. restrict: 'EAC',
  38543. link: function($scope, $element, $attrs, controller, $transclude) {
  38544. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  38545. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  38546. // then treat it like the default
  38547. $attrs.ngTransclude = '';
  38548. }
  38549. function ngTranscludeCloneAttachFn(clone) {
  38550. if (clone.length) {
  38551. $element.empty();
  38552. $element.append(clone);
  38553. }
  38554. }
  38555. if (!$transclude) {
  38556. throw ngTranscludeMinErr('orphan',
  38557. 'Illegal use of ngTransclude directive in the template! ' +
  38558. 'No parent directive that requires a transclusion found. ' +
  38559. 'Element: {0}',
  38560. startingTag($element));
  38561. }
  38562. // If there is no slot name defined or the slot name is not optional
  38563. // then transclude the slot
  38564. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  38565. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  38566. }
  38567. });
  38568. /**
  38569. * @ngdoc directive
  38570. * @name script
  38571. * @restrict E
  38572. *
  38573. * @description
  38574. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  38575. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  38576. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  38577. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  38578. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  38579. *
  38580. * @param {string} type Must be set to `'text/ng-template'`.
  38581. * @param {string} id Cache name of the template.
  38582. *
  38583. * @example
  38584. <example>
  38585. <file name="index.html">
  38586. <script type="text/ng-template" id="/tpl.html">
  38587. Content of the template.
  38588. </script>
  38589. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  38590. <div id="tpl-content" ng-include src="currentTpl"></div>
  38591. </file>
  38592. <file name="protractor.js" type="protractor">
  38593. it('should load template defined inside script tag', function() {
  38594. element(by.css('#tpl-link')).click();
  38595. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  38596. });
  38597. </file>
  38598. </example>
  38599. */
  38600. var scriptDirective = ['$templateCache', function($templateCache) {
  38601. return {
  38602. restrict: 'E',
  38603. terminal: true,
  38604. compile: function(element, attr) {
  38605. if (attr.type == 'text/ng-template') {
  38606. var templateUrl = attr.id,
  38607. text = element[0].text;
  38608. $templateCache.put(templateUrl, text);
  38609. }
  38610. }
  38611. };
  38612. }];
  38613. var noopNgModelController = { $setViewValue: noop, $render: noop };
  38614. function chromeHack(optionElement) {
  38615. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  38616. // Adding an <option selected="selected"> element to a <select required="required"> should
  38617. // automatically select the new element
  38618. if (optionElement[0].hasAttribute('selected')) {
  38619. optionElement[0].selected = true;
  38620. }
  38621. }
  38622. /**
  38623. * @ngdoc type
  38624. * @name select.SelectController
  38625. * @description
  38626. * The controller for the `<select>` directive. This provides support for reading
  38627. * and writing the selected value(s) of the control and also coordinates dynamically
  38628. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  38629. */
  38630. var SelectController =
  38631. ['$element', '$scope', function($element, $scope) {
  38632. var self = this,
  38633. optionsMap = new HashMap();
  38634. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  38635. self.ngModelCtrl = noopNgModelController;
  38636. // The "unknown" option is one that is prepended to the list if the viewValue
  38637. // does not match any of the options. When it is rendered the value of the unknown
  38638. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  38639. //
  38640. // We can't just jqLite('<option>') since jqLite is not smart enough
  38641. // to create it in <select> and IE barfs otherwise.
  38642. self.unknownOption = jqLite(document.createElement('option'));
  38643. self.renderUnknownOption = function(val) {
  38644. var unknownVal = '? ' + hashKey(val) + ' ?';
  38645. self.unknownOption.val(unknownVal);
  38646. $element.prepend(self.unknownOption);
  38647. $element.val(unknownVal);
  38648. };
  38649. $scope.$on('$destroy', function() {
  38650. // disable unknown option so that we don't do work when the whole select is being destroyed
  38651. self.renderUnknownOption = noop;
  38652. });
  38653. self.removeUnknownOption = function() {
  38654. if (self.unknownOption.parent()) self.unknownOption.remove();
  38655. };
  38656. // Read the value of the select control, the implementation of this changes depending
  38657. // upon whether the select can have multiple values and whether ngOptions is at work.
  38658. self.readValue = function readSingleValue() {
  38659. self.removeUnknownOption();
  38660. return $element.val();
  38661. };
  38662. // Write the value to the select control, the implementation of this changes depending
  38663. // upon whether the select can have multiple values and whether ngOptions is at work.
  38664. self.writeValue = function writeSingleValue(value) {
  38665. if (self.hasOption(value)) {
  38666. self.removeUnknownOption();
  38667. $element.val(value);
  38668. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  38669. } else {
  38670. if (value == null && self.emptyOption) {
  38671. self.removeUnknownOption();
  38672. $element.val('');
  38673. } else {
  38674. self.renderUnknownOption(value);
  38675. }
  38676. }
  38677. };
  38678. // Tell the select control that an option, with the given value, has been added
  38679. self.addOption = function(value, element) {
  38680. // Skip comment nodes, as they only pollute the `optionsMap`
  38681. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  38682. assertNotHasOwnProperty(value, '"option value"');
  38683. if (value === '') {
  38684. self.emptyOption = element;
  38685. }
  38686. var count = optionsMap.get(value) || 0;
  38687. optionsMap.put(value, count + 1);
  38688. self.ngModelCtrl.$render();
  38689. chromeHack(element);
  38690. };
  38691. // Tell the select control that an option, with the given value, has been removed
  38692. self.removeOption = function(value) {
  38693. var count = optionsMap.get(value);
  38694. if (count) {
  38695. if (count === 1) {
  38696. optionsMap.remove(value);
  38697. if (value === '') {
  38698. self.emptyOption = undefined;
  38699. }
  38700. } else {
  38701. optionsMap.put(value, count - 1);
  38702. }
  38703. }
  38704. };
  38705. // Check whether the select control has an option matching the given value
  38706. self.hasOption = function(value) {
  38707. return !!optionsMap.get(value);
  38708. };
  38709. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  38710. if (interpolateValueFn) {
  38711. // The value attribute is interpolated
  38712. var oldVal;
  38713. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  38714. if (isDefined(oldVal)) {
  38715. self.removeOption(oldVal);
  38716. }
  38717. oldVal = newVal;
  38718. self.addOption(newVal, optionElement);
  38719. });
  38720. } else if (interpolateTextFn) {
  38721. // The text content is interpolated
  38722. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  38723. optionAttrs.$set('value', newVal);
  38724. if (oldVal !== newVal) {
  38725. self.removeOption(oldVal);
  38726. }
  38727. self.addOption(newVal, optionElement);
  38728. });
  38729. } else {
  38730. // The value attribute is static
  38731. self.addOption(optionAttrs.value, optionElement);
  38732. }
  38733. optionElement.on('$destroy', function() {
  38734. self.removeOption(optionAttrs.value);
  38735. self.ngModelCtrl.$render();
  38736. });
  38737. };
  38738. }];
  38739. /**
  38740. * @ngdoc directive
  38741. * @name select
  38742. * @restrict E
  38743. *
  38744. * @description
  38745. * HTML `SELECT` element with angular data-binding.
  38746. *
  38747. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  38748. * between the scope and the `<select>` control (including setting default values).
  38749. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  38750. * {@link ngOptions `ngOptions`} directives.
  38751. *
  38752. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  38753. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  38754. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  38755. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  38756. *
  38757. * <div class="alert alert-warning">
  38758. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  38759. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  38760. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  38761. * This is because an option element can only be bound to string values at present.
  38762. * </div>
  38763. *
  38764. * If the viewValue of `ngModel` does not match any of the options, then the control
  38765. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  38766. *
  38767. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  38768. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  38769. * option. See example below for demonstration.
  38770. *
  38771. * <div class="alert alert-info">
  38772. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  38773. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  38774. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  38775. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  38776. * a new scope for each repeated instance.
  38777. * </div>
  38778. *
  38779. *
  38780. * @param {string} ngModel Assignable angular expression to data-bind to.
  38781. * @param {string=} name Property name of the form under which the control is published.
  38782. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  38783. * bound to the model as an array.
  38784. * @param {string=} required Sets `required` validation error key if the value is not entered.
  38785. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  38786. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  38787. * when you want to data-bind to the required attribute.
  38788. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  38789. * interaction with the select element.
  38790. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  38791. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  38792. *
  38793. * @example
  38794. * ### Simple `select` elements with static options
  38795. *
  38796. * <example name="static-select" module="staticSelect">
  38797. * <file name="index.html">
  38798. * <div ng-controller="ExampleController">
  38799. * <form name="myForm">
  38800. * <label for="singleSelect"> Single select: </label><br>
  38801. * <select name="singleSelect" ng-model="data.singleSelect">
  38802. * <option value="option-1">Option 1</option>
  38803. * <option value="option-2">Option 2</option>
  38804. * </select><br>
  38805. *
  38806. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  38807. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  38808. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  38809. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  38810. * <option value="option-2">Option 2</option>
  38811. * </select><br>
  38812. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  38813. * <tt>singleSelect = {{data.singleSelect}}</tt>
  38814. *
  38815. * <hr>
  38816. * <label for="multipleSelect"> Multiple select: </label><br>
  38817. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  38818. * <option value="option-1">Option 1</option>
  38819. * <option value="option-2">Option 2</option>
  38820. * <option value="option-3">Option 3</option>
  38821. * </select><br>
  38822. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  38823. * </form>
  38824. * </div>
  38825. * </file>
  38826. * <file name="app.js">
  38827. * angular.module('staticSelect', [])
  38828. * .controller('ExampleController', ['$scope', function($scope) {
  38829. * $scope.data = {
  38830. * singleSelect: null,
  38831. * multipleSelect: [],
  38832. * option1: 'option-1',
  38833. * };
  38834. *
  38835. * $scope.forceUnknownOption = function() {
  38836. * $scope.data.singleSelect = 'nonsense';
  38837. * };
  38838. * }]);
  38839. * </file>
  38840. *</example>
  38841. *
  38842. * ### Using `ngRepeat` to generate `select` options
  38843. * <example name="ngrepeat-select" module="ngrepeatSelect">
  38844. * <file name="index.html">
  38845. * <div ng-controller="ExampleController">
  38846. * <form name="myForm">
  38847. * <label for="repeatSelect"> Repeat select: </label>
  38848. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  38849. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  38850. * </select>
  38851. * </form>
  38852. * <hr>
  38853. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  38854. * </div>
  38855. * </file>
  38856. * <file name="app.js">
  38857. * angular.module('ngrepeatSelect', [])
  38858. * .controller('ExampleController', ['$scope', function($scope) {
  38859. * $scope.data = {
  38860. * repeatSelect: null,
  38861. * availableOptions: [
  38862. * {id: '1', name: 'Option A'},
  38863. * {id: '2', name: 'Option B'},
  38864. * {id: '3', name: 'Option C'}
  38865. * ],
  38866. * };
  38867. * }]);
  38868. * </file>
  38869. *</example>
  38870. *
  38871. *
  38872. * ### Using `select` with `ngOptions` and setting a default value
  38873. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  38874. *
  38875. * <example name="select-with-default-values" module="defaultValueSelect">
  38876. * <file name="index.html">
  38877. * <div ng-controller="ExampleController">
  38878. * <form name="myForm">
  38879. * <label for="mySelect">Make a choice:</label>
  38880. * <select name="mySelect" id="mySelect"
  38881. * ng-options="option.name for option in data.availableOptions track by option.id"
  38882. * ng-model="data.selectedOption"></select>
  38883. * </form>
  38884. * <hr>
  38885. * <tt>option = {{data.selectedOption}}</tt><br/>
  38886. * </div>
  38887. * </file>
  38888. * <file name="app.js">
  38889. * angular.module('defaultValueSelect', [])
  38890. * .controller('ExampleController', ['$scope', function($scope) {
  38891. * $scope.data = {
  38892. * availableOptions: [
  38893. * {id: '1', name: 'Option A'},
  38894. * {id: '2', name: 'Option B'},
  38895. * {id: '3', name: 'Option C'}
  38896. * ],
  38897. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  38898. * };
  38899. * }]);
  38900. * </file>
  38901. *</example>
  38902. *
  38903. *
  38904. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  38905. *
  38906. * <example name="select-with-non-string-options" module="nonStringSelect">
  38907. * <file name="index.html">
  38908. * <select ng-model="model.id" convert-to-number>
  38909. * <option value="0">Zero</option>
  38910. * <option value="1">One</option>
  38911. * <option value="2">Two</option>
  38912. * </select>
  38913. * {{ model }}
  38914. * </file>
  38915. * <file name="app.js">
  38916. * angular.module('nonStringSelect', [])
  38917. * .run(function($rootScope) {
  38918. * $rootScope.model = { id: 2 };
  38919. * })
  38920. * .directive('convertToNumber', function() {
  38921. * return {
  38922. * require: 'ngModel',
  38923. * link: function(scope, element, attrs, ngModel) {
  38924. * ngModel.$parsers.push(function(val) {
  38925. * return parseInt(val, 10);
  38926. * });
  38927. * ngModel.$formatters.push(function(val) {
  38928. * return '' + val;
  38929. * });
  38930. * }
  38931. * };
  38932. * });
  38933. * </file>
  38934. * <file name="protractor.js" type="protractor">
  38935. * it('should initialize to model', function() {
  38936. * var select = element(by.css('select'));
  38937. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  38938. * });
  38939. * </file>
  38940. * </example>
  38941. *
  38942. */
  38943. var selectDirective = function() {
  38944. return {
  38945. restrict: 'E',
  38946. require: ['select', '?ngModel'],
  38947. controller: SelectController,
  38948. priority: 1,
  38949. link: {
  38950. pre: selectPreLink,
  38951. post: selectPostLink
  38952. }
  38953. };
  38954. function selectPreLink(scope, element, attr, ctrls) {
  38955. // if ngModel is not defined, we don't need to do anything
  38956. var ngModelCtrl = ctrls[1];
  38957. if (!ngModelCtrl) return;
  38958. var selectCtrl = ctrls[0];
  38959. selectCtrl.ngModelCtrl = ngModelCtrl;
  38960. // When the selected item(s) changes we delegate getting the value of the select control
  38961. // to the `readValue` method, which can be changed if the select can have multiple
  38962. // selected values or if the options are being generated by `ngOptions`
  38963. element.on('change', function() {
  38964. scope.$apply(function() {
  38965. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  38966. });
  38967. });
  38968. // If the select allows multiple values then we need to modify how we read and write
  38969. // values from and to the control; also what it means for the value to be empty and
  38970. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  38971. // doesn't trigger rendering if only an item in the array changes.
  38972. if (attr.multiple) {
  38973. // Read value now needs to check each option to see if it is selected
  38974. selectCtrl.readValue = function readMultipleValue() {
  38975. var array = [];
  38976. forEach(element.find('option'), function(option) {
  38977. if (option.selected) {
  38978. array.push(option.value);
  38979. }
  38980. });
  38981. return array;
  38982. };
  38983. // Write value now needs to set the selected property of each matching option
  38984. selectCtrl.writeValue = function writeMultipleValue(value) {
  38985. var items = new HashMap(value);
  38986. forEach(element.find('option'), function(option) {
  38987. option.selected = isDefined(items.get(option.value));
  38988. });
  38989. };
  38990. // we have to do it on each watch since ngModel watches reference, but
  38991. // we need to work of an array, so we need to see if anything was inserted/removed
  38992. var lastView, lastViewRef = NaN;
  38993. scope.$watch(function selectMultipleWatch() {
  38994. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  38995. lastView = shallowCopy(ngModelCtrl.$viewValue);
  38996. ngModelCtrl.$render();
  38997. }
  38998. lastViewRef = ngModelCtrl.$viewValue;
  38999. });
  39000. // If we are a multiple select then value is now a collection
  39001. // so the meaning of $isEmpty changes
  39002. ngModelCtrl.$isEmpty = function(value) {
  39003. return !value || value.length === 0;
  39004. };
  39005. }
  39006. }
  39007. function selectPostLink(scope, element, attrs, ctrls) {
  39008. // if ngModel is not defined, we don't need to do anything
  39009. var ngModelCtrl = ctrls[1];
  39010. if (!ngModelCtrl) return;
  39011. var selectCtrl = ctrls[0];
  39012. // We delegate rendering to the `writeValue` method, which can be changed
  39013. // if the select can have multiple selected values or if the options are being
  39014. // generated by `ngOptions`.
  39015. // This must be done in the postLink fn to prevent $render to be called before
  39016. // all nodes have been linked correctly.
  39017. ngModelCtrl.$render = function() {
  39018. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  39019. };
  39020. }
  39021. };
  39022. // The option directive is purely designed to communicate the existence (or lack of)
  39023. // of dynamically created (and destroyed) option elements to their containing select
  39024. // directive via its controller.
  39025. var optionDirective = ['$interpolate', function($interpolate) {
  39026. return {
  39027. restrict: 'E',
  39028. priority: 100,
  39029. compile: function(element, attr) {
  39030. if (isDefined(attr.value)) {
  39031. // If the value attribute is defined, check if it contains an interpolation
  39032. var interpolateValueFn = $interpolate(attr.value, true);
  39033. } else {
  39034. // If the value attribute is not defined then we fall back to the
  39035. // text content of the option element, which may be interpolated
  39036. var interpolateTextFn = $interpolate(element.text(), true);
  39037. if (!interpolateTextFn) {
  39038. attr.$set('value', element.text());
  39039. }
  39040. }
  39041. return function(scope, element, attr) {
  39042. // This is an optimization over using ^^ since we don't want to have to search
  39043. // all the way to the root of the DOM for every single option element
  39044. var selectCtrlName = '$selectController',
  39045. parent = element.parent(),
  39046. selectCtrl = parent.data(selectCtrlName) ||
  39047. parent.parent().data(selectCtrlName); // in case we are in optgroup
  39048. if (selectCtrl) {
  39049. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  39050. }
  39051. };
  39052. }
  39053. };
  39054. }];
  39055. var styleDirective = valueFn({
  39056. restrict: 'E',
  39057. terminal: false
  39058. });
  39059. /**
  39060. * @ngdoc directive
  39061. * @name ngRequired
  39062. *
  39063. * @description
  39064. *
  39065. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39066. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  39067. * applied to custom controls.
  39068. *
  39069. * The directive sets the `required` attribute on the element if the Angular expression inside
  39070. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  39071. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  39072. * for more info.
  39073. *
  39074. * The validator will set the `required` error key to true if the `required` attribute is set and
  39075. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  39076. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  39077. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  39078. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  39079. *
  39080. * @example
  39081. * <example name="ngRequiredDirective" module="ngRequiredExample">
  39082. * <file name="index.html">
  39083. * <script>
  39084. * angular.module('ngRequiredExample', [])
  39085. * .controller('ExampleController', ['$scope', function($scope) {
  39086. * $scope.required = true;
  39087. * }]);
  39088. * </script>
  39089. * <div ng-controller="ExampleController">
  39090. * <form name="form">
  39091. * <label for="required">Toggle required: </label>
  39092. * <input type="checkbox" ng-model="required" id="required" />
  39093. * <br>
  39094. * <label for="input">This input must be filled if `required` is true: </label>
  39095. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  39096. * <hr>
  39097. * required error set? = <code>{{form.input.$error.required}}</code><br>
  39098. * model = <code>{{model}}</code>
  39099. * </form>
  39100. * </div>
  39101. * </file>
  39102. * <file name="protractor.js" type="protractor">
  39103. var required = element(by.binding('form.input.$error.required'));
  39104. var model = element(by.binding('model'));
  39105. var input = element(by.id('input'));
  39106. it('should set the required error', function() {
  39107. expect(required.getText()).toContain('true');
  39108. input.sendKeys('123');
  39109. expect(required.getText()).not.toContain('true');
  39110. expect(model.getText()).toContain('123');
  39111. });
  39112. * </file>
  39113. * </example>
  39114. */
  39115. var requiredDirective = function() {
  39116. return {
  39117. restrict: 'A',
  39118. require: '?ngModel',
  39119. link: function(scope, elm, attr, ctrl) {
  39120. if (!ctrl) return;
  39121. attr.required = true; // force truthy in case we are on non input element
  39122. ctrl.$validators.required = function(modelValue, viewValue) {
  39123. return !attr.required || !ctrl.$isEmpty(viewValue);
  39124. };
  39125. attr.$observe('required', function() {
  39126. ctrl.$validate();
  39127. });
  39128. }
  39129. };
  39130. };
  39131. /**
  39132. * @ngdoc directive
  39133. * @name ngPattern
  39134. *
  39135. * @description
  39136. *
  39137. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39138. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39139. *
  39140. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39141. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  39142. * `ngPattern` attribute value:
  39143. * * If the expression evaluates to a RegExp object, then this is used directly.
  39144. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  39145. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  39146. *
  39147. * <div class="alert alert-info">
  39148. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  39149. * start at the index of the last search's match, thus not taking the whole input value into
  39150. * account.
  39151. * </div>
  39152. *
  39153. * <div class="alert alert-info">
  39154. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  39155. * differences:
  39156. * <ol>
  39157. * <li>
  39158. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  39159. * not available.
  39160. * </li>
  39161. * <li>
  39162. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  39163. * interpolated.
  39164. * </li>
  39165. * </ol>
  39166. * </div>
  39167. *
  39168. * @example
  39169. * <example name="ngPatternDirective" module="ngPatternExample">
  39170. * <file name="index.html">
  39171. * <script>
  39172. * angular.module('ngPatternExample', [])
  39173. * .controller('ExampleController', ['$scope', function($scope) {
  39174. * $scope.regex = '\\d+';
  39175. * }]);
  39176. * </script>
  39177. * <div ng-controller="ExampleController">
  39178. * <form name="form">
  39179. * <label for="regex">Set a pattern (regex string): </label>
  39180. * <input type="text" ng-model="regex" id="regex" />
  39181. * <br>
  39182. * <label for="input">This input is restricted by the current pattern: </label>
  39183. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  39184. * <hr>
  39185. * input valid? = <code>{{form.input.$valid}}</code><br>
  39186. * model = <code>{{model}}</code>
  39187. * </form>
  39188. * </div>
  39189. * </file>
  39190. * <file name="protractor.js" type="protractor">
  39191. var model = element(by.binding('model'));
  39192. var input = element(by.id('input'));
  39193. it('should validate the input with the default pattern', function() {
  39194. input.sendKeys('aaa');
  39195. expect(model.getText()).not.toContain('aaa');
  39196. input.clear().then(function() {
  39197. input.sendKeys('123');
  39198. expect(model.getText()).toContain('123');
  39199. });
  39200. });
  39201. * </file>
  39202. * </example>
  39203. */
  39204. var patternDirective = function() {
  39205. return {
  39206. restrict: 'A',
  39207. require: '?ngModel',
  39208. link: function(scope, elm, attr, ctrl) {
  39209. if (!ctrl) return;
  39210. var regexp, patternExp = attr.ngPattern || attr.pattern;
  39211. attr.$observe('pattern', function(regex) {
  39212. if (isString(regex) && regex.length > 0) {
  39213. regex = new RegExp('^' + regex + '$');
  39214. }
  39215. if (regex && !regex.test) {
  39216. throw minErr('ngPattern')('noregexp',
  39217. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  39218. regex, startingTag(elm));
  39219. }
  39220. regexp = regex || undefined;
  39221. ctrl.$validate();
  39222. });
  39223. ctrl.$validators.pattern = function(modelValue, viewValue) {
  39224. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  39225. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  39226. };
  39227. }
  39228. };
  39229. };
  39230. /**
  39231. * @ngdoc directive
  39232. * @name ngMaxlength
  39233. *
  39234. * @description
  39235. *
  39236. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39237. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39238. *
  39239. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39240. * is longer than the integer obtained by evaluating the Angular expression given in the
  39241. * `ngMaxlength` attribute value.
  39242. *
  39243. * <div class="alert alert-info">
  39244. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  39245. * differences:
  39246. * <ol>
  39247. * <li>
  39248. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  39249. * validation is not available.
  39250. * </li>
  39251. * <li>
  39252. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  39253. * interpolated.
  39254. * </li>
  39255. * </ol>
  39256. * </div>
  39257. *
  39258. * @example
  39259. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  39260. * <file name="index.html">
  39261. * <script>
  39262. * angular.module('ngMaxlengthExample', [])
  39263. * .controller('ExampleController', ['$scope', function($scope) {
  39264. * $scope.maxlength = 5;
  39265. * }]);
  39266. * </script>
  39267. * <div ng-controller="ExampleController">
  39268. * <form name="form">
  39269. * <label for="maxlength">Set a maxlength: </label>
  39270. * <input type="number" ng-model="maxlength" id="maxlength" />
  39271. * <br>
  39272. * <label for="input">This input is restricted by the current maxlength: </label>
  39273. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  39274. * <hr>
  39275. * input valid? = <code>{{form.input.$valid}}</code><br>
  39276. * model = <code>{{model}}</code>
  39277. * </form>
  39278. * </div>
  39279. * </file>
  39280. * <file name="protractor.js" type="protractor">
  39281. var model = element(by.binding('model'));
  39282. var input = element(by.id('input'));
  39283. it('should validate the input with the default maxlength', function() {
  39284. input.sendKeys('abcdef');
  39285. expect(model.getText()).not.toContain('abcdef');
  39286. input.clear().then(function() {
  39287. input.sendKeys('abcde');
  39288. expect(model.getText()).toContain('abcde');
  39289. });
  39290. });
  39291. * </file>
  39292. * </example>
  39293. */
  39294. var maxlengthDirective = function() {
  39295. return {
  39296. restrict: 'A',
  39297. require: '?ngModel',
  39298. link: function(scope, elm, attr, ctrl) {
  39299. if (!ctrl) return;
  39300. var maxlength = -1;
  39301. attr.$observe('maxlength', function(value) {
  39302. var intVal = toInt(value);
  39303. maxlength = isNaN(intVal) ? -1 : intVal;
  39304. ctrl.$validate();
  39305. });
  39306. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  39307. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  39308. };
  39309. }
  39310. };
  39311. };
  39312. /**
  39313. * @ngdoc directive
  39314. * @name ngMinlength
  39315. *
  39316. * @description
  39317. *
  39318. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39319. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39320. *
  39321. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39322. * is shorter than the integer obtained by evaluating the Angular expression given in the
  39323. * `ngMinlength` attribute value.
  39324. *
  39325. * <div class="alert alert-info">
  39326. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  39327. * differences:
  39328. * <ol>
  39329. * <li>
  39330. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  39331. * validation is not available.
  39332. * </li>
  39333. * <li>
  39334. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  39335. * interpolated.
  39336. * </li>
  39337. * </ol>
  39338. * </div>
  39339. *
  39340. * @example
  39341. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  39342. * <file name="index.html">
  39343. * <script>
  39344. * angular.module('ngMinlengthExample', [])
  39345. * .controller('ExampleController', ['$scope', function($scope) {
  39346. * $scope.minlength = 3;
  39347. * }]);
  39348. * </script>
  39349. * <div ng-controller="ExampleController">
  39350. * <form name="form">
  39351. * <label for="minlength">Set a minlength: </label>
  39352. * <input type="number" ng-model="minlength" id="minlength" />
  39353. * <br>
  39354. * <label for="input">This input is restricted by the current minlength: </label>
  39355. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  39356. * <hr>
  39357. * input valid? = <code>{{form.input.$valid}}</code><br>
  39358. * model = <code>{{model}}</code>
  39359. * </form>
  39360. * </div>
  39361. * </file>
  39362. * <file name="protractor.js" type="protractor">
  39363. var model = element(by.binding('model'));
  39364. var input = element(by.id('input'));
  39365. it('should validate the input with the default minlength', function() {
  39366. input.sendKeys('ab');
  39367. expect(model.getText()).not.toContain('ab');
  39368. input.sendKeys('abc');
  39369. expect(model.getText()).toContain('abc');
  39370. });
  39371. * </file>
  39372. * </example>
  39373. */
  39374. var minlengthDirective = function() {
  39375. return {
  39376. restrict: 'A',
  39377. require: '?ngModel',
  39378. link: function(scope, elm, attr, ctrl) {
  39379. if (!ctrl) return;
  39380. var minlength = 0;
  39381. attr.$observe('minlength', function(value) {
  39382. minlength = toInt(value) || 0;
  39383. ctrl.$validate();
  39384. });
  39385. ctrl.$validators.minlength = function(modelValue, viewValue) {
  39386. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  39387. };
  39388. }
  39389. };
  39390. };
  39391. if (window.angular.bootstrap) {
  39392. //AngularJS is already loaded, so we can return here...
  39393. if (window.console) {
  39394. console.log('WARNING: Tried to load angular more than once.');
  39395. }
  39396. return;
  39397. }
  39398. //try to bind to jquery now so that one can write jqLite(document).ready()
  39399. //but we will rebind on bootstrap again.
  39400. bindJQuery();
  39401. publishExternalAPI(angular);
  39402. angular.module("ngLocale", [], ["$provide", function($provide) {
  39403. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  39404. function getDecimals(n) {
  39405. n = n + '';
  39406. var i = n.indexOf('.');
  39407. return (i == -1) ? 0 : n.length - i - 1;
  39408. }
  39409. function getVF(n, opt_precision) {
  39410. var v = opt_precision;
  39411. if (undefined === v) {
  39412. v = Math.min(getDecimals(n), 3);
  39413. }
  39414. var base = Math.pow(10, v);
  39415. var f = ((n * base) | 0) % base;
  39416. return {v: v, f: f};
  39417. }
  39418. $provide.value("$locale", {
  39419. "DATETIME_FORMATS": {
  39420. "AMPMS": [
  39421. "AM",
  39422. "PM"
  39423. ],
  39424. "DAY": [
  39425. "Sunday",
  39426. "Monday",
  39427. "Tuesday",
  39428. "Wednesday",
  39429. "Thursday",
  39430. "Friday",
  39431. "Saturday"
  39432. ],
  39433. "ERANAMES": [
  39434. "Before Christ",
  39435. "Anno Domini"
  39436. ],
  39437. "ERAS": [
  39438. "BC",
  39439. "AD"
  39440. ],
  39441. "FIRSTDAYOFWEEK": 6,
  39442. "MONTH": [
  39443. "January",
  39444. "February",
  39445. "March",
  39446. "April",
  39447. "May",
  39448. "June",
  39449. "July",
  39450. "August",
  39451. "September",
  39452. "October",
  39453. "November",
  39454. "December"
  39455. ],
  39456. "SHORTDAY": [
  39457. "Sun",
  39458. "Mon",
  39459. "Tue",
  39460. "Wed",
  39461. "Thu",
  39462. "Fri",
  39463. "Sat"
  39464. ],
  39465. "SHORTMONTH": [
  39466. "Jan",
  39467. "Feb",
  39468. "Mar",
  39469. "Apr",
  39470. "May",
  39471. "Jun",
  39472. "Jul",
  39473. "Aug",
  39474. "Sep",
  39475. "Oct",
  39476. "Nov",
  39477. "Dec"
  39478. ],
  39479. "STANDALONEMONTH": [
  39480. "January",
  39481. "February",
  39482. "March",
  39483. "April",
  39484. "May",
  39485. "June",
  39486. "July",
  39487. "August",
  39488. "September",
  39489. "October",
  39490. "November",
  39491. "December"
  39492. ],
  39493. "WEEKENDRANGE": [
  39494. 5,
  39495. 6
  39496. ],
  39497. "fullDate": "EEEE, MMMM d, y",
  39498. "longDate": "MMMM d, y",
  39499. "medium": "MMM d, y h:mm:ss a",
  39500. "mediumDate": "MMM d, y",
  39501. "mediumTime": "h:mm:ss a",
  39502. "short": "M/d/yy h:mm a",
  39503. "shortDate": "M/d/yy",
  39504. "shortTime": "h:mm a"
  39505. },
  39506. "NUMBER_FORMATS": {
  39507. "CURRENCY_SYM": "$",
  39508. "DECIMAL_SEP": ".",
  39509. "GROUP_SEP": ",",
  39510. "PATTERNS": [
  39511. {
  39512. "gSize": 3,
  39513. "lgSize": 3,
  39514. "maxFrac": 3,
  39515. "minFrac": 0,
  39516. "minInt": 1,
  39517. "negPre": "-",
  39518. "negSuf": "",
  39519. "posPre": "",
  39520. "posSuf": ""
  39521. },
  39522. {
  39523. "gSize": 3,
  39524. "lgSize": 3,
  39525. "maxFrac": 2,
  39526. "minFrac": 2,
  39527. "minInt": 1,
  39528. "negPre": "-\u00a4",
  39529. "negSuf": "",
  39530. "posPre": "\u00a4",
  39531. "posSuf": ""
  39532. }
  39533. ]
  39534. },
  39535. "id": "en-us",
  39536. "localeID": "en_US",
  39537. "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;}
  39538. });
  39539. }]);
  39540. jqLite(document).ready(function() {
  39541. angularInit(document, bootstrap);
  39542. });
  39543. })(window, document);
  39544. !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>');
  39545. /*!
  39546. * ionic.bundle.js is a concatenation of:
  39547. * ionic.js, angular.js, angular-animate.js,
  39548. * angular-sanitize.js, angular-ui-router.js,
  39549. * and ionic-angular.js
  39550. */
  39551. /**
  39552. * @license AngularJS v1.5.3
  39553. * (c) 2010-2016 Google, Inc. http://angularjs.org
  39554. * License: MIT
  39555. */
  39556. (function(window, angular, undefined) {'use strict';
  39557. /* jshint ignore:start */
  39558. var noop = angular.noop;
  39559. var copy = angular.copy;
  39560. var extend = angular.extend;
  39561. var jqLite = angular.element;
  39562. var forEach = angular.forEach;
  39563. var isArray = angular.isArray;
  39564. var isString = angular.isString;
  39565. var isObject = angular.isObject;
  39566. var isUndefined = angular.isUndefined;
  39567. var isDefined = angular.isDefined;
  39568. var isFunction = angular.isFunction;
  39569. var isElement = angular.isElement;
  39570. var ELEMENT_NODE = 1;
  39571. var COMMENT_NODE = 8;
  39572. var ADD_CLASS_SUFFIX = '-add';
  39573. var REMOVE_CLASS_SUFFIX = '-remove';
  39574. var EVENT_CLASS_PREFIX = 'ng-';
  39575. var ACTIVE_CLASS_SUFFIX = '-active';
  39576. var PREPARE_CLASS_SUFFIX = '-prepare';
  39577. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  39578. var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
  39579. // Detect proper transitionend/animationend event names.
  39580. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
  39581. // If unprefixed events are not supported but webkit-prefixed are, use the latter.
  39582. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
  39583. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
  39584. // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
  39585. // Register both events in case `window.onanimationend` is not supported because of that,
  39586. // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
  39587. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
  39588. // therefore there is no reason to test anymore for other vendor prefixes:
  39589. // http://caniuse.com/#search=transition
  39590. if (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {
  39591. CSS_PREFIX = '-webkit-';
  39592. TRANSITION_PROP = 'WebkitTransition';
  39593. TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
  39594. } else {
  39595. TRANSITION_PROP = 'transition';
  39596. TRANSITIONEND_EVENT = 'transitionend';
  39597. }
  39598. if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {
  39599. CSS_PREFIX = '-webkit-';
  39600. ANIMATION_PROP = 'WebkitAnimation';
  39601. ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
  39602. } else {
  39603. ANIMATION_PROP = 'animation';
  39604. ANIMATIONEND_EVENT = 'animationend';
  39605. }
  39606. var DURATION_KEY = 'Duration';
  39607. var PROPERTY_KEY = 'Property';
  39608. var DELAY_KEY = 'Delay';
  39609. var TIMING_KEY = 'TimingFunction';
  39610. var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
  39611. var ANIMATION_PLAYSTATE_KEY = 'PlayState';
  39612. var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
  39613. var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
  39614. var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
  39615. var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
  39616. var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
  39617. var isPromiseLike = function(p) {
  39618. return p && p.then ? true : false;
  39619. };
  39620. var ngMinErr = angular.$$minErr('ng');
  39621. function assertArg(arg, name, reason) {
  39622. if (!arg) {
  39623. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  39624. }
  39625. return arg;
  39626. }
  39627. function mergeClasses(a,b) {
  39628. if (!a && !b) return '';
  39629. if (!a) return b;
  39630. if (!b) return a;
  39631. if (isArray(a)) a = a.join(' ');
  39632. if (isArray(b)) b = b.join(' ');
  39633. return a + ' ' + b;
  39634. }
  39635. function packageStyles(options) {
  39636. var styles = {};
  39637. if (options && (options.to || options.from)) {
  39638. styles.to = options.to;
  39639. styles.from = options.from;
  39640. }
  39641. return styles;
  39642. }
  39643. function pendClasses(classes, fix, isPrefix) {
  39644. var className = '';
  39645. classes = isArray(classes)
  39646. ? classes
  39647. : classes && isString(classes) && classes.length
  39648. ? classes.split(/\s+/)
  39649. : [];
  39650. forEach(classes, function(klass, i) {
  39651. if (klass && klass.length > 0) {
  39652. className += (i > 0) ? ' ' : '';
  39653. className += isPrefix ? fix + klass
  39654. : klass + fix;
  39655. }
  39656. });
  39657. return className;
  39658. }
  39659. function removeFromArray(arr, val) {
  39660. var index = arr.indexOf(val);
  39661. if (val >= 0) {
  39662. arr.splice(index, 1);
  39663. }
  39664. }
  39665. function stripCommentsFromElement(element) {
  39666. if (element instanceof jqLite) {
  39667. switch (element.length) {
  39668. case 0:
  39669. return [];
  39670. break;
  39671. case 1:
  39672. // there is no point of stripping anything if the element
  39673. // is the only element within the jqLite wrapper.
  39674. // (it's important that we retain the element instance.)
  39675. if (element[0].nodeType === ELEMENT_NODE) {
  39676. return element;
  39677. }
  39678. break;
  39679. default:
  39680. return jqLite(extractElementNode(element));
  39681. break;
  39682. }
  39683. }
  39684. if (element.nodeType === ELEMENT_NODE) {
  39685. return jqLite(element);
  39686. }
  39687. }
  39688. function extractElementNode(element) {
  39689. if (!element[0]) return element;
  39690. for (var i = 0; i < element.length; i++) {
  39691. var elm = element[i];
  39692. if (elm.nodeType == ELEMENT_NODE) {
  39693. return elm;
  39694. }
  39695. }
  39696. }
  39697. function $$addClass($$jqLite, element, className) {
  39698. forEach(element, function(elm) {
  39699. $$jqLite.addClass(elm, className);
  39700. });
  39701. }
  39702. function $$removeClass($$jqLite, element, className) {
  39703. forEach(element, function(elm) {
  39704. $$jqLite.removeClass(elm, className);
  39705. });
  39706. }
  39707. function applyAnimationClassesFactory($$jqLite) {
  39708. return function(element, options) {
  39709. if (options.addClass) {
  39710. $$addClass($$jqLite, element, options.addClass);
  39711. options.addClass = null;
  39712. }
  39713. if (options.removeClass) {
  39714. $$removeClass($$jqLite, element, options.removeClass);
  39715. options.removeClass = null;
  39716. }
  39717. }
  39718. }
  39719. function prepareAnimationOptions(options) {
  39720. options = options || {};
  39721. if (!options.$$prepared) {
  39722. var domOperation = options.domOperation || noop;
  39723. options.domOperation = function() {
  39724. options.$$domOperationFired = true;
  39725. domOperation();
  39726. domOperation = noop;
  39727. };
  39728. options.$$prepared = true;
  39729. }
  39730. return options;
  39731. }
  39732. function applyAnimationStyles(element, options) {
  39733. applyAnimationFromStyles(element, options);
  39734. applyAnimationToStyles(element, options);
  39735. }
  39736. function applyAnimationFromStyles(element, options) {
  39737. if (options.from) {
  39738. element.css(options.from);
  39739. options.from = null;
  39740. }
  39741. }
  39742. function applyAnimationToStyles(element, options) {
  39743. if (options.to) {
  39744. element.css(options.to);
  39745. options.to = null;
  39746. }
  39747. }
  39748. function mergeAnimationDetails(element, oldAnimation, newAnimation) {
  39749. var target = oldAnimation.options || {};
  39750. var newOptions = newAnimation.options || {};
  39751. var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
  39752. var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
  39753. var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
  39754. if (newOptions.preparationClasses) {
  39755. target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
  39756. delete newOptions.preparationClasses;
  39757. }
  39758. // noop is basically when there is no callback; otherwise something has been set
  39759. var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
  39760. extend(target, newOptions);
  39761. // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.
  39762. if (realDomOperation) {
  39763. target.domOperation = realDomOperation;
  39764. }
  39765. if (classes.addClass) {
  39766. target.addClass = classes.addClass;
  39767. } else {
  39768. target.addClass = null;
  39769. }
  39770. if (classes.removeClass) {
  39771. target.removeClass = classes.removeClass;
  39772. } else {
  39773. target.removeClass = null;
  39774. }
  39775. oldAnimation.addClass = target.addClass;
  39776. oldAnimation.removeClass = target.removeClass;
  39777. return target;
  39778. }
  39779. function resolveElementClasses(existing, toAdd, toRemove) {
  39780. var ADD_CLASS = 1;
  39781. var REMOVE_CLASS = -1;
  39782. var flags = {};
  39783. existing = splitClassesToLookup(existing);
  39784. toAdd = splitClassesToLookup(toAdd);
  39785. forEach(toAdd, function(value, key) {
  39786. flags[key] = ADD_CLASS;
  39787. });
  39788. toRemove = splitClassesToLookup(toRemove);
  39789. forEach(toRemove, function(value, key) {
  39790. flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
  39791. });
  39792. var classes = {
  39793. addClass: '',
  39794. removeClass: ''
  39795. };
  39796. forEach(flags, function(val, klass) {
  39797. var prop, allow;
  39798. if (val === ADD_CLASS) {
  39799. prop = 'addClass';
  39800. allow = !existing[klass];
  39801. } else if (val === REMOVE_CLASS) {
  39802. prop = 'removeClass';
  39803. allow = existing[klass];
  39804. }
  39805. if (allow) {
  39806. if (classes[prop].length) {
  39807. classes[prop] += ' ';
  39808. }
  39809. classes[prop] += klass;
  39810. }
  39811. });
  39812. function splitClassesToLookup(classes) {
  39813. if (isString(classes)) {
  39814. classes = classes.split(' ');
  39815. }
  39816. var obj = {};
  39817. forEach(classes, function(klass) {
  39818. // sometimes the split leaves empty string values
  39819. // incase extra spaces were applied to the options
  39820. if (klass.length) {
  39821. obj[klass] = true;
  39822. }
  39823. });
  39824. return obj;
  39825. }
  39826. return classes;
  39827. }
  39828. function getDomNode(element) {
  39829. return (element instanceof angular.element) ? element[0] : element;
  39830. }
  39831. function applyGeneratedPreparationClasses(element, event, options) {
  39832. var classes = '';
  39833. if (event) {
  39834. classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
  39835. }
  39836. if (options.addClass) {
  39837. classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
  39838. }
  39839. if (options.removeClass) {
  39840. classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
  39841. }
  39842. if (classes.length) {
  39843. options.preparationClasses = classes;
  39844. element.addClass(classes);
  39845. }
  39846. }
  39847. function clearGeneratedClasses(element, options) {
  39848. if (options.preparationClasses) {
  39849. element.removeClass(options.preparationClasses);
  39850. options.preparationClasses = null;
  39851. }
  39852. if (options.activeClasses) {
  39853. element.removeClass(options.activeClasses);
  39854. options.activeClasses = null;
  39855. }
  39856. }
  39857. function blockTransitions(node, duration) {
  39858. // we use a negative delay value since it performs blocking
  39859. // yet it doesn't kill any existing transitions running on the
  39860. // same element which makes this safe for class-based animations
  39861. var value = duration ? '-' + duration + 's' : '';
  39862. applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
  39863. return [TRANSITION_DELAY_PROP, value];
  39864. }
  39865. function blockKeyframeAnimations(node, applyBlock) {
  39866. var value = applyBlock ? 'paused' : '';
  39867. var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
  39868. applyInlineStyle(node, [key, value]);
  39869. return [key, value];
  39870. }
  39871. function applyInlineStyle(node, styleTuple) {
  39872. var prop = styleTuple[0];
  39873. var value = styleTuple[1];
  39874. node.style[prop] = value;
  39875. }
  39876. function concatWithSpace(a,b) {
  39877. if (!a) return b;
  39878. if (!b) return a;
  39879. return a + ' ' + b;
  39880. }
  39881. var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
  39882. var queue, cancelFn;
  39883. function scheduler(tasks) {
  39884. // we make a copy since RAFScheduler mutates the state
  39885. // of the passed in array variable and this would be difficult
  39886. // to track down on the outside code
  39887. queue = queue.concat(tasks);
  39888. nextTick();
  39889. }
  39890. queue = scheduler.queue = [];
  39891. /* waitUntilQuiet does two things:
  39892. * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
  39893. * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
  39894. *
  39895. * The motivation here is that animation code can request more time from the scheduler
  39896. * before the next wave runs. This allows for certain DOM properties such as classes to
  39897. * be resolved in time for the next animation to run.
  39898. */
  39899. scheduler.waitUntilQuiet = function(fn) {
  39900. if (cancelFn) cancelFn();
  39901. cancelFn = $$rAF(function() {
  39902. cancelFn = null;
  39903. fn();
  39904. nextTick();
  39905. });
  39906. };
  39907. return scheduler;
  39908. function nextTick() {
  39909. if (!queue.length) return;
  39910. var items = queue.shift();
  39911. for (var i = 0; i < items.length; i++) {
  39912. items[i]();
  39913. }
  39914. if (!cancelFn) {
  39915. $$rAF(function() {
  39916. if (!cancelFn) nextTick();
  39917. });
  39918. }
  39919. }
  39920. }];
  39921. /**
  39922. * @ngdoc directive
  39923. * @name ngAnimateChildren
  39924. * @restrict AE
  39925. * @element ANY
  39926. *
  39927. * @description
  39928. *
  39929. * ngAnimateChildren allows you to specify that children of this element should animate even if any
  39930. * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
  39931. * (structural) animation, child elements that also have an active structural animation are not animated.
  39932. *
  39933. * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
  39934. *
  39935. *
  39936. * @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
  39937. * then child animations are allowed. If the value is `false`, child animations are not allowed.
  39938. *
  39939. * @example
  39940. * <example module="ngAnimateChildren" name="ngAnimateChildren" deps="angular-animate.js" animations="true">
  39941. <file name="index.html">
  39942. <div ng-controller="mainController as main">
  39943. <label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
  39944. <label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
  39945. <hr>
  39946. <div ng-animate-children="{{main.animateChildren}}">
  39947. <div ng-if="main.enterElement" class="container">
  39948. List of items:
  39949. <div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
  39950. </div>
  39951. </div>
  39952. </div>
  39953. </file>
  39954. <file name="animations.css">
  39955. .container.ng-enter,
  39956. .container.ng-leave {
  39957. transition: all ease 1.5s;
  39958. }
  39959. .container.ng-enter,
  39960. .container.ng-leave-active {
  39961. opacity: 0;
  39962. }
  39963. .container.ng-leave,
  39964. .container.ng-enter-active {
  39965. opacity: 1;
  39966. }
  39967. .item {
  39968. background: firebrick;
  39969. color: #FFF;
  39970. margin-bottom: 10px;
  39971. }
  39972. .item.ng-enter,
  39973. .item.ng-leave {
  39974. transition: transform 1.5s ease;
  39975. }
  39976. .item.ng-enter {
  39977. transform: translateX(50px);
  39978. }
  39979. .item.ng-enter-active {
  39980. transform: translateX(0);
  39981. }
  39982. </file>
  39983. <file name="script.js">
  39984. angular.module('ngAnimateChildren', ['ngAnimate'])
  39985. .controller('mainController', function() {
  39986. this.animateChildren = false;
  39987. this.enterElement = false;
  39988. });
  39989. </file>
  39990. </example>
  39991. */
  39992. var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
  39993. return {
  39994. link: function(scope, element, attrs) {
  39995. var val = attrs.ngAnimateChildren;
  39996. if (angular.isString(val) && val.length === 0) { //empty attribute
  39997. element.data(NG_ANIMATE_CHILDREN_DATA, true);
  39998. } else {
  39999. // Interpolate and set the value, so that it is available to
  40000. // animations that run right after compilation
  40001. setData($interpolate(val)(scope));
  40002. attrs.$observe('ngAnimateChildren', setData);
  40003. }
  40004. function setData(value) {
  40005. value = value === 'on' || value === 'true';
  40006. element.data(NG_ANIMATE_CHILDREN_DATA, value);
  40007. }
  40008. }
  40009. };
  40010. }];
  40011. var ANIMATE_TIMER_KEY = '$$animateCss';
  40012. /**
  40013. * @ngdoc service
  40014. * @name $animateCss
  40015. * @kind object
  40016. *
  40017. * @description
  40018. * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
  40019. * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
  40020. * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
  40021. * directives to create more complex animations that can be purely driven using CSS code.
  40022. *
  40023. * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
  40024. * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
  40025. *
  40026. * ## Usage
  40027. * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
  40028. * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
  40029. * any automatic control over cancelling animations and/or preventing animations from being run on
  40030. * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
  40031. * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
  40032. * the CSS animation.
  40033. *
  40034. * The example below shows how we can create a folding animation on an element using `ng-if`:
  40035. *
  40036. * ```html
  40037. * <!-- notice the `fold-animation` CSS class -->
  40038. * <div ng-if="onOff" class="fold-animation">
  40039. * This element will go BOOM
  40040. * </div>
  40041. * <button ng-click="onOff=true">Fold In</button>
  40042. * ```
  40043. *
  40044. * Now we create the **JavaScript animation** that will trigger the CSS transition:
  40045. *
  40046. * ```js
  40047. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  40048. * return {
  40049. * enter: function(element, doneFn) {
  40050. * var height = element[0].offsetHeight;
  40051. * return $animateCss(element, {
  40052. * from: { height:'0px' },
  40053. * to: { height:height + 'px' },
  40054. * duration: 1 // one second
  40055. * });
  40056. * }
  40057. * }
  40058. * }]);
  40059. * ```
  40060. *
  40061. * ## More Advanced Uses
  40062. *
  40063. * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
  40064. * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
  40065. *
  40066. * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
  40067. * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
  40068. * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
  40069. * to provide a working animation that will run in CSS.
  40070. *
  40071. * The example below showcases a more advanced version of the `.fold-animation` from the example above:
  40072. *
  40073. * ```js
  40074. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  40075. * return {
  40076. * enter: function(element, doneFn) {
  40077. * var height = element[0].offsetHeight;
  40078. * return $animateCss(element, {
  40079. * addClass: 'red large-text pulse-twice',
  40080. * easing: 'ease-out',
  40081. * from: { height:'0px' },
  40082. * to: { height:height + 'px' },
  40083. * duration: 1 // one second
  40084. * });
  40085. * }
  40086. * }
  40087. * }]);
  40088. * ```
  40089. *
  40090. * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
  40091. *
  40092. * ```css
  40093. * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
  40094. * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
  40095. * .red { background:red; }
  40096. * .large-text { font-size:20px; }
  40097. *
  40098. * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
  40099. * .pulse-twice {
  40100. * animation: 0.5s pulse linear 2;
  40101. * -webkit-animation: 0.5s pulse linear 2;
  40102. * }
  40103. *
  40104. * @keyframes pulse {
  40105. * from { transform: scale(0.5); }
  40106. * to { transform: scale(1.5); }
  40107. * }
  40108. *
  40109. * @-webkit-keyframes pulse {
  40110. * from { -webkit-transform: scale(0.5); }
  40111. * to { -webkit-transform: scale(1.5); }
  40112. * }
  40113. * ```
  40114. *
  40115. * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
  40116. *
  40117. * ## How the Options are handled
  40118. *
  40119. * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
  40120. * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline
  40121. * styles using the `from` and `to` properties.
  40122. *
  40123. * ```js
  40124. * var animator = $animateCss(element, {
  40125. * from: { background:'red' },
  40126. * to: { background:'blue' }
  40127. * });
  40128. * animator.start();
  40129. * ```
  40130. *
  40131. * ```css
  40132. * .rotating-animation {
  40133. * animation:0.5s rotate linear;
  40134. * -webkit-animation:0.5s rotate linear;
  40135. * }
  40136. *
  40137. * @keyframes rotate {
  40138. * from { transform: rotate(0deg); }
  40139. * to { transform: rotate(360deg); }
  40140. * }
  40141. *
  40142. * @-webkit-keyframes rotate {
  40143. * from { -webkit-transform: rotate(0deg); }
  40144. * to { -webkit-transform: rotate(360deg); }
  40145. * }
  40146. * ```
  40147. *
  40148. * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is
  40149. * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
  40150. * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition
  40151. * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied
  40152. * and spread across the transition and keyframe animation.
  40153. *
  40154. * ## What is returned
  40155. *
  40156. * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
  40157. * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are
  40158. * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
  40159. *
  40160. * ```js
  40161. * var animator = $animateCss(element, { ... });
  40162. * ```
  40163. *
  40164. * Now what do the contents of our `animator` variable look like:
  40165. *
  40166. * ```js
  40167. * {
  40168. * // starts the animation
  40169. * start: Function,
  40170. *
  40171. * // ends (aborts) the animation
  40172. * end: Function
  40173. * }
  40174. * ```
  40175. *
  40176. * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.
  40177. * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and styles may have been
  40178. * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
  40179. * and that changing them will not reconfigure the parameters of the animation.
  40180. *
  40181. * ### runner.done() vs runner.then()
  40182. * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the
  40183. * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
  40184. * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
  40185. * unless you really need a digest to kick off afterwards.
  40186. *
  40187. * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss
  40188. * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
  40189. * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
  40190. *
  40191. * @param {DOMElement} element the element that will be animated
  40192. * @param {object} options the animation-related options that will be applied during the animation
  40193. *
  40194. * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied
  40195. * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)
  40196. * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
  40197. * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
  40198. * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
  40199. * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
  40200. * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
  40201. * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
  40202. * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
  40203. * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
  40204. * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
  40205. * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`
  40206. * is provided then the animation will be skipped entirely.
  40207. * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is
  40208. * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value
  40209. * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same
  40210. * CSS delay value.
  40211. * * `stagger` - A numeric time value representing the delay between successively animated elements
  40212. * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
  40213. * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a
  40214. * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
  40215. * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occurring on the classes being added and removed.)
  40216. * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
  40217. * the animation is closed. This is useful for when the styles are used purely for the sake of
  40218. * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
  40219. * By default this value is set to `false`.
  40220. *
  40221. * @return {object} an object with start and end methods and details about the animation.
  40222. *
  40223. * * `start` - The method to start the animation. This will return a `Promise` when called.
  40224. * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
  40225. */
  40226. var ONE_SECOND = 1000;
  40227. var BASE_TEN = 10;
  40228. var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
  40229. var CLOSING_TIME_BUFFER = 1.5;
  40230. var DETECT_CSS_PROPERTIES = {
  40231. transitionDuration: TRANSITION_DURATION_PROP,
  40232. transitionDelay: TRANSITION_DELAY_PROP,
  40233. transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
  40234. animationDuration: ANIMATION_DURATION_PROP,
  40235. animationDelay: ANIMATION_DELAY_PROP,
  40236. animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
  40237. };
  40238. var DETECT_STAGGER_CSS_PROPERTIES = {
  40239. transitionDuration: TRANSITION_DURATION_PROP,
  40240. transitionDelay: TRANSITION_DELAY_PROP,
  40241. animationDuration: ANIMATION_DURATION_PROP,
  40242. animationDelay: ANIMATION_DELAY_PROP
  40243. };
  40244. function getCssKeyframeDurationStyle(duration) {
  40245. return [ANIMATION_DURATION_PROP, duration + 's'];
  40246. }
  40247. function getCssDelayStyle(delay, isKeyframeAnimation) {
  40248. var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
  40249. return [prop, delay + 's'];
  40250. }
  40251. function computeCssStyles($window, element, properties) {
  40252. var styles = Object.create(null);
  40253. var detectedStyles = $window.getComputedStyle(element) || {};
  40254. forEach(properties, function(formalStyleName, actualStyleName) {
  40255. var val = detectedStyles[formalStyleName];
  40256. if (val) {
  40257. var c = val.charAt(0);
  40258. // only numerical-based values have a negative sign or digit as the first value
  40259. if (c === '-' || c === '+' || c >= 0) {
  40260. val = parseMaxTime(val);
  40261. }
  40262. // by setting this to null in the event that the delay is not set or is set directly as 0
  40263. // then we can still allow for negative values to be used later on and not mistake this
  40264. // value for being greater than any other negative value.
  40265. if (val === 0) {
  40266. val = null;
  40267. }
  40268. styles[actualStyleName] = val;
  40269. }
  40270. });
  40271. return styles;
  40272. }
  40273. function parseMaxTime(str) {
  40274. var maxValue = 0;
  40275. var values = str.split(/\s*,\s*/);
  40276. forEach(values, function(value) {
  40277. // it's always safe to consider only second values and omit `ms` values since
  40278. // getComputedStyle will always handle the conversion for us
  40279. if (value.charAt(value.length - 1) == 's') {
  40280. value = value.substring(0, value.length - 1);
  40281. }
  40282. value = parseFloat(value) || 0;
  40283. maxValue = maxValue ? Math.max(value, maxValue) : value;
  40284. });
  40285. return maxValue;
  40286. }
  40287. function truthyTimingValue(val) {
  40288. return val === 0 || val != null;
  40289. }
  40290. function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
  40291. var style = TRANSITION_PROP;
  40292. var value = duration + 's';
  40293. if (applyOnlyDuration) {
  40294. style += DURATION_KEY;
  40295. } else {
  40296. value += ' linear all';
  40297. }
  40298. return [style, value];
  40299. }
  40300. function createLocalCacheLookup() {
  40301. var cache = Object.create(null);
  40302. return {
  40303. flush: function() {
  40304. cache = Object.create(null);
  40305. },
  40306. count: function(key) {
  40307. var entry = cache[key];
  40308. return entry ? entry.total : 0;
  40309. },
  40310. get: function(key) {
  40311. var entry = cache[key];
  40312. return entry && entry.value;
  40313. },
  40314. put: function(key, value) {
  40315. if (!cache[key]) {
  40316. cache[key] = { total: 1, value: value };
  40317. } else {
  40318. cache[key].total++;
  40319. }
  40320. }
  40321. };
  40322. }
  40323. // we do not reassign an already present style value since
  40324. // if we detect the style property value again we may be
  40325. // detecting styles that were added via the `from` styles.
  40326. // We make use of `isDefined` here since an empty string
  40327. // or null value (which is what getPropertyValue will return
  40328. // for a non-existing style) will still be marked as a valid
  40329. // value for the style (a falsy value implies that the style
  40330. // is to be removed at the end of the animation). If we had a simple
  40331. // "OR" statement then it would not be enough to catch that.
  40332. function registerRestorableStyles(backup, node, properties) {
  40333. forEach(properties, function(prop) {
  40334. backup[prop] = isDefined(backup[prop])
  40335. ? backup[prop]
  40336. : node.style.getPropertyValue(prop);
  40337. });
  40338. }
  40339. var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
  40340. var gcsLookup = createLocalCacheLookup();
  40341. var gcsStaggerLookup = createLocalCacheLookup();
  40342. this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
  40343. '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
  40344. function($window, $$jqLite, $$AnimateRunner, $timeout,
  40345. $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
  40346. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  40347. var parentCounter = 0;
  40348. function gcsHashFn(node, extraClasses) {
  40349. var KEY = "$$ngAnimateParentKey";
  40350. var parentNode = node.parentNode;
  40351. var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
  40352. return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
  40353. }
  40354. function computeCachedCssStyles(node, className, cacheKey, properties) {
  40355. var timings = gcsLookup.get(cacheKey);
  40356. if (!timings) {
  40357. timings = computeCssStyles($window, node, properties);
  40358. if (timings.animationIterationCount === 'infinite') {
  40359. timings.animationIterationCount = 1;
  40360. }
  40361. }
  40362. // we keep putting this in multiple times even though the value and the cacheKey are the same
  40363. // because we're keeping an internal tally of how many duplicate animations are detected.
  40364. gcsLookup.put(cacheKey, timings);
  40365. return timings;
  40366. }
  40367. function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
  40368. var stagger;
  40369. // if we have one or more existing matches of matching elements
  40370. // containing the same parent + CSS styles (which is how cacheKey works)
  40371. // then staggering is possible
  40372. if (gcsLookup.count(cacheKey) > 0) {
  40373. stagger = gcsStaggerLookup.get(cacheKey);
  40374. if (!stagger) {
  40375. var staggerClassName = pendClasses(className, '-stagger');
  40376. $$jqLite.addClass(node, staggerClassName);
  40377. stagger = computeCssStyles($window, node, properties);
  40378. // force the conversion of a null value to zero incase not set
  40379. stagger.animationDuration = Math.max(stagger.animationDuration, 0);
  40380. stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
  40381. $$jqLite.removeClass(node, staggerClassName);
  40382. gcsStaggerLookup.put(cacheKey, stagger);
  40383. }
  40384. }
  40385. return stagger || {};
  40386. }
  40387. var cancelLastRAFRequest;
  40388. var rafWaitQueue = [];
  40389. function waitUntilQuiet(callback) {
  40390. rafWaitQueue.push(callback);
  40391. $$rAFScheduler.waitUntilQuiet(function() {
  40392. gcsLookup.flush();
  40393. gcsStaggerLookup.flush();
  40394. // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
  40395. // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
  40396. var pageWidth = $$forceReflow();
  40397. // we use a for loop to ensure that if the queue is changed
  40398. // during this looping then it will consider new requests
  40399. for (var i = 0; i < rafWaitQueue.length; i++) {
  40400. rafWaitQueue[i](pageWidth);
  40401. }
  40402. rafWaitQueue.length = 0;
  40403. });
  40404. }
  40405. function computeTimings(node, className, cacheKey) {
  40406. var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
  40407. var aD = timings.animationDelay;
  40408. var tD = timings.transitionDelay;
  40409. timings.maxDelay = aD && tD
  40410. ? Math.max(aD, tD)
  40411. : (aD || tD);
  40412. timings.maxDuration = Math.max(
  40413. timings.animationDuration * timings.animationIterationCount,
  40414. timings.transitionDuration);
  40415. return timings;
  40416. }
  40417. return function init(element, initialOptions) {
  40418. // all of the animation functions should create
  40419. // a copy of the options data, however, if a
  40420. // parent service has already created a copy then
  40421. // we should stick to using that
  40422. var options = initialOptions || {};
  40423. if (!options.$$prepared) {
  40424. options = prepareAnimationOptions(copy(options));
  40425. }
  40426. var restoreStyles = {};
  40427. var node = getDomNode(element);
  40428. if (!node
  40429. || !node.parentNode
  40430. || !$$animateQueue.enabled()) {
  40431. return closeAndReturnNoopAnimator();
  40432. }
  40433. var temporaryStyles = [];
  40434. var classes = element.attr('class');
  40435. var styles = packageStyles(options);
  40436. var animationClosed;
  40437. var animationPaused;
  40438. var animationCompleted;
  40439. var runner;
  40440. var runnerHost;
  40441. var maxDelay;
  40442. var maxDelayTime;
  40443. var maxDuration;
  40444. var maxDurationTime;
  40445. var startTime;
  40446. var events = [];
  40447. if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
  40448. return closeAndReturnNoopAnimator();
  40449. }
  40450. var method = options.event && isArray(options.event)
  40451. ? options.event.join(' ')
  40452. : options.event;
  40453. var isStructural = method && options.structural;
  40454. var structuralClassName = '';
  40455. var addRemoveClassName = '';
  40456. if (isStructural) {
  40457. structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
  40458. } else if (method) {
  40459. structuralClassName = method;
  40460. }
  40461. if (options.addClass) {
  40462. addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
  40463. }
  40464. if (options.removeClass) {
  40465. if (addRemoveClassName.length) {
  40466. addRemoveClassName += ' ';
  40467. }
  40468. addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
  40469. }
  40470. // there may be a situation where a structural animation is combined together
  40471. // with CSS classes that need to resolve before the animation is computed.
  40472. // However this means that there is no explicit CSS code to block the animation
  40473. // from happening (by setting 0s none in the class name). If this is the case
  40474. // we need to apply the classes before the first rAF so we know to continue if
  40475. // there actually is a detected transition or keyframe animation
  40476. if (options.applyClassesEarly && addRemoveClassName.length) {
  40477. applyAnimationClasses(element, options);
  40478. }
  40479. var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
  40480. var fullClassName = classes + ' ' + preparationClasses;
  40481. var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
  40482. var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
  40483. var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
  40484. // there is no way we can trigger an animation if no styles and
  40485. // no classes are being applied which would then trigger a transition,
  40486. // unless there a is raw keyframe value that is applied to the element.
  40487. if (!containsKeyframeAnimation
  40488. && !hasToStyles
  40489. && !preparationClasses) {
  40490. return closeAndReturnNoopAnimator();
  40491. }
  40492. var cacheKey, stagger;
  40493. if (options.stagger > 0) {
  40494. var staggerVal = parseFloat(options.stagger);
  40495. stagger = {
  40496. transitionDelay: staggerVal,
  40497. animationDelay: staggerVal,
  40498. transitionDuration: 0,
  40499. animationDuration: 0
  40500. };
  40501. } else {
  40502. cacheKey = gcsHashFn(node, fullClassName);
  40503. stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
  40504. }
  40505. if (!options.$$skipPreparationClasses) {
  40506. $$jqLite.addClass(element, preparationClasses);
  40507. }
  40508. var applyOnlyDuration;
  40509. if (options.transitionStyle) {
  40510. var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
  40511. applyInlineStyle(node, transitionStyle);
  40512. temporaryStyles.push(transitionStyle);
  40513. }
  40514. if (options.duration >= 0) {
  40515. applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
  40516. var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
  40517. // we set the duration so that it will be picked up by getComputedStyle later
  40518. applyInlineStyle(node, durationStyle);
  40519. temporaryStyles.push(durationStyle);
  40520. }
  40521. if (options.keyframeStyle) {
  40522. var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
  40523. applyInlineStyle(node, keyframeStyle);
  40524. temporaryStyles.push(keyframeStyle);
  40525. }
  40526. var itemIndex = stagger
  40527. ? options.staggerIndex >= 0
  40528. ? options.staggerIndex
  40529. : gcsLookup.count(cacheKey)
  40530. : 0;
  40531. var isFirst = itemIndex === 0;
  40532. // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
  40533. // without causing any combination of transitions to kick in. By adding a negative delay value
  40534. // it forces the setup class' transition to end immediately. We later then remove the negative
  40535. // transition delay to allow for the transition to naturally do it's thing. The beauty here is
  40536. // that if there is no transition defined then nothing will happen and this will also allow
  40537. // other transitions to be stacked on top of each other without any chopping them out.
  40538. if (isFirst && !options.skipBlocking) {
  40539. blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
  40540. }
  40541. var timings = computeTimings(node, fullClassName, cacheKey);
  40542. var relativeDelay = timings.maxDelay;
  40543. maxDelay = Math.max(relativeDelay, 0);
  40544. maxDuration = timings.maxDuration;
  40545. var flags = {};
  40546. flags.hasTransitions = timings.transitionDuration > 0;
  40547. flags.hasAnimations = timings.animationDuration > 0;
  40548. flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
  40549. flags.applyTransitionDuration = hasToStyles && (
  40550. (flags.hasTransitions && !flags.hasTransitionAll)
  40551. || (flags.hasAnimations && !flags.hasTransitions));
  40552. flags.applyAnimationDuration = options.duration && flags.hasAnimations;
  40553. flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
  40554. flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
  40555. flags.recalculateTimingStyles = addRemoveClassName.length > 0;
  40556. if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
  40557. maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
  40558. if (flags.applyTransitionDuration) {
  40559. flags.hasTransitions = true;
  40560. timings.transitionDuration = maxDuration;
  40561. applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
  40562. temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
  40563. }
  40564. if (flags.applyAnimationDuration) {
  40565. flags.hasAnimations = true;
  40566. timings.animationDuration = maxDuration;
  40567. temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
  40568. }
  40569. }
  40570. if (maxDuration === 0 && !flags.recalculateTimingStyles) {
  40571. return closeAndReturnNoopAnimator();
  40572. }
  40573. if (options.delay != null) {
  40574. var delayStyle;
  40575. if (typeof options.delay !== "boolean") {
  40576. delayStyle = parseFloat(options.delay);
  40577. // number in options.delay means we have to recalculate the delay for the closing timeout
  40578. maxDelay = Math.max(delayStyle, 0);
  40579. }
  40580. if (flags.applyTransitionDelay) {
  40581. temporaryStyles.push(getCssDelayStyle(delayStyle));
  40582. }
  40583. if (flags.applyAnimationDelay) {
  40584. temporaryStyles.push(getCssDelayStyle(delayStyle, true));
  40585. }
  40586. }
  40587. // we need to recalculate the delay value since we used a pre-emptive negative
  40588. // delay value and the delay value is required for the final event checking. This
  40589. // property will ensure that this will happen after the RAF phase has passed.
  40590. if (options.duration == null && timings.transitionDuration > 0) {
  40591. flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
  40592. }
  40593. maxDelayTime = maxDelay * ONE_SECOND;
  40594. maxDurationTime = maxDuration * ONE_SECOND;
  40595. if (!options.skipBlocking) {
  40596. flags.blockTransition = timings.transitionDuration > 0;
  40597. flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
  40598. stagger.animationDelay > 0 &&
  40599. stagger.animationDuration === 0;
  40600. }
  40601. if (options.from) {
  40602. if (options.cleanupStyles) {
  40603. registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
  40604. }
  40605. applyAnimationFromStyles(element, options);
  40606. }
  40607. if (flags.blockTransition || flags.blockKeyframeAnimation) {
  40608. applyBlocking(maxDuration);
  40609. } else if (!options.skipBlocking) {
  40610. blockTransitions(node, false);
  40611. }
  40612. // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
  40613. return {
  40614. $$willAnimate: true,
  40615. end: endFn,
  40616. start: function() {
  40617. if (animationClosed) return;
  40618. runnerHost = {
  40619. end: endFn,
  40620. cancel: cancelFn,
  40621. resume: null, //this will be set during the start() phase
  40622. pause: null
  40623. };
  40624. runner = new $$AnimateRunner(runnerHost);
  40625. waitUntilQuiet(start);
  40626. // we don't have access to pause/resume the animation
  40627. // since it hasn't run yet. AnimateRunner will therefore
  40628. // set noop functions for resume and pause and they will
  40629. // later be overridden once the animation is triggered
  40630. return runner;
  40631. }
  40632. };
  40633. function endFn() {
  40634. close();
  40635. }
  40636. function cancelFn() {
  40637. close(true);
  40638. }
  40639. function close(rejected) { // jshint ignore:line
  40640. // if the promise has been called already then we shouldn't close
  40641. // the animation again
  40642. if (animationClosed || (animationCompleted && animationPaused)) return;
  40643. animationClosed = true;
  40644. animationPaused = false;
  40645. if (!options.$$skipPreparationClasses) {
  40646. $$jqLite.removeClass(element, preparationClasses);
  40647. }
  40648. $$jqLite.removeClass(element, activeClasses);
  40649. blockKeyframeAnimations(node, false);
  40650. blockTransitions(node, false);
  40651. forEach(temporaryStyles, function(entry) {
  40652. // There is only one way to remove inline style properties entirely from elements.
  40653. // By using `removeProperty` this works, but we need to convert camel-cased CSS
  40654. // styles down to hyphenated values.
  40655. node.style[entry[0]] = '';
  40656. });
  40657. applyAnimationClasses(element, options);
  40658. applyAnimationStyles(element, options);
  40659. if (Object.keys(restoreStyles).length) {
  40660. forEach(restoreStyles, function(value, prop) {
  40661. value ? node.style.setProperty(prop, value)
  40662. : node.style.removeProperty(prop);
  40663. });
  40664. }
  40665. // the reason why we have this option is to allow a synchronous closing callback
  40666. // that is fired as SOON as the animation ends (when the CSS is removed) or if
  40667. // the animation never takes off at all. A good example is a leave animation since
  40668. // the element must be removed just after the animation is over or else the element
  40669. // will appear on screen for one animation frame causing an overbearing flicker.
  40670. if (options.onDone) {
  40671. options.onDone();
  40672. }
  40673. if (events && events.length) {
  40674. // Remove the transitionend / animationend listener(s)
  40675. element.off(events.join(' '), onAnimationProgress);
  40676. }
  40677. //Cancel the fallback closing timeout and remove the timer data
  40678. var animationTimerData = element.data(ANIMATE_TIMER_KEY);
  40679. if (animationTimerData) {
  40680. $timeout.cancel(animationTimerData[0].timer);
  40681. element.removeData(ANIMATE_TIMER_KEY);
  40682. }
  40683. // if the preparation function fails then the promise is not setup
  40684. if (runner) {
  40685. runner.complete(!rejected);
  40686. }
  40687. }
  40688. function applyBlocking(duration) {
  40689. if (flags.blockTransition) {
  40690. blockTransitions(node, duration);
  40691. }
  40692. if (flags.blockKeyframeAnimation) {
  40693. blockKeyframeAnimations(node, !!duration);
  40694. }
  40695. }
  40696. function closeAndReturnNoopAnimator() {
  40697. runner = new $$AnimateRunner({
  40698. end: endFn,
  40699. cancel: cancelFn
  40700. });
  40701. // should flush the cache animation
  40702. waitUntilQuiet(noop);
  40703. close();
  40704. return {
  40705. $$willAnimate: false,
  40706. start: function() {
  40707. return runner;
  40708. },
  40709. end: endFn
  40710. };
  40711. }
  40712. function onAnimationProgress(event) {
  40713. event.stopPropagation();
  40714. var ev = event.originalEvent || event;
  40715. // we now always use `Date.now()` due to the recent changes with
  40716. // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
  40717. var timeStamp = ev.$manualTimeStamp || Date.now();
  40718. /* Firefox (or possibly just Gecko) likes to not round values up
  40719. * when a ms measurement is used for the animation */
  40720. var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
  40721. /* $manualTimeStamp is a mocked timeStamp value which is set
  40722. * within browserTrigger(). This is only here so that tests can
  40723. * mock animations properly. Real events fallback to event.timeStamp,
  40724. * or, if they don't, then a timeStamp is automatically created for them.
  40725. * We're checking to see if the timeStamp surpasses the expected delay,
  40726. * but we're using elapsedTime instead of the timeStamp on the 2nd
  40727. * pre-condition since animationPauseds sometimes close off early */
  40728. if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
  40729. // we set this flag to ensure that if the transition is paused then, when resumed,
  40730. // the animation will automatically close itself since transitions cannot be paused.
  40731. animationCompleted = true;
  40732. close();
  40733. }
  40734. }
  40735. function start() {
  40736. if (animationClosed) return;
  40737. if (!node.parentNode) {
  40738. close();
  40739. return;
  40740. }
  40741. // even though we only pause keyframe animations here the pause flag
  40742. // will still happen when transitions are used. Only the transition will
  40743. // not be paused since that is not possible. If the animation ends when
  40744. // paused then it will not complete until unpaused or cancelled.
  40745. var playPause = function(playAnimation) {
  40746. if (!animationCompleted) {
  40747. animationPaused = !playAnimation;
  40748. if (timings.animationDuration) {
  40749. var value = blockKeyframeAnimations(node, animationPaused);
  40750. animationPaused
  40751. ? temporaryStyles.push(value)
  40752. : removeFromArray(temporaryStyles, value);
  40753. }
  40754. } else if (animationPaused && playAnimation) {
  40755. animationPaused = false;
  40756. close();
  40757. }
  40758. };
  40759. // checking the stagger duration prevents an accidentally cascade of the CSS delay style
  40760. // being inherited from the parent. If the transition duration is zero then we can safely
  40761. // rely that the delay value is an intentional stagger delay style.
  40762. var maxStagger = itemIndex > 0
  40763. && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
  40764. (timings.animationDuration && stagger.animationDuration === 0))
  40765. && Math.max(stagger.animationDelay, stagger.transitionDelay);
  40766. if (maxStagger) {
  40767. $timeout(triggerAnimationStart,
  40768. Math.floor(maxStagger * itemIndex * ONE_SECOND),
  40769. false);
  40770. } else {
  40771. triggerAnimationStart();
  40772. }
  40773. // this will decorate the existing promise runner with pause/resume methods
  40774. runnerHost.resume = function() {
  40775. playPause(true);
  40776. };
  40777. runnerHost.pause = function() {
  40778. playPause(false);
  40779. };
  40780. function triggerAnimationStart() {
  40781. // just incase a stagger animation kicks in when the animation
  40782. // itself was cancelled entirely
  40783. if (animationClosed) return;
  40784. applyBlocking(false);
  40785. forEach(temporaryStyles, function(entry) {
  40786. var key = entry[0];
  40787. var value = entry[1];
  40788. node.style[key] = value;
  40789. });
  40790. applyAnimationClasses(element, options);
  40791. $$jqLite.addClass(element, activeClasses);
  40792. if (flags.recalculateTimingStyles) {
  40793. fullClassName = node.className + ' ' + preparationClasses;
  40794. cacheKey = gcsHashFn(node, fullClassName);
  40795. timings = computeTimings(node, fullClassName, cacheKey);
  40796. relativeDelay = timings.maxDelay;
  40797. maxDelay = Math.max(relativeDelay, 0);
  40798. maxDuration = timings.maxDuration;
  40799. if (maxDuration === 0) {
  40800. close();
  40801. return;
  40802. }
  40803. flags.hasTransitions = timings.transitionDuration > 0;
  40804. flags.hasAnimations = timings.animationDuration > 0;
  40805. }
  40806. if (flags.applyAnimationDelay) {
  40807. relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
  40808. ? parseFloat(options.delay)
  40809. : relativeDelay;
  40810. maxDelay = Math.max(relativeDelay, 0);
  40811. timings.animationDelay = relativeDelay;
  40812. delayStyle = getCssDelayStyle(relativeDelay, true);
  40813. temporaryStyles.push(delayStyle);
  40814. node.style[delayStyle[0]] = delayStyle[1];
  40815. }
  40816. maxDelayTime = maxDelay * ONE_SECOND;
  40817. maxDurationTime = maxDuration * ONE_SECOND;
  40818. if (options.easing) {
  40819. var easeProp, easeVal = options.easing;
  40820. if (flags.hasTransitions) {
  40821. easeProp = TRANSITION_PROP + TIMING_KEY;
  40822. temporaryStyles.push([easeProp, easeVal]);
  40823. node.style[easeProp] = easeVal;
  40824. }
  40825. if (flags.hasAnimations) {
  40826. easeProp = ANIMATION_PROP + TIMING_KEY;
  40827. temporaryStyles.push([easeProp, easeVal]);
  40828. node.style[easeProp] = easeVal;
  40829. }
  40830. }
  40831. if (timings.transitionDuration) {
  40832. events.push(TRANSITIONEND_EVENT);
  40833. }
  40834. if (timings.animationDuration) {
  40835. events.push(ANIMATIONEND_EVENT);
  40836. }
  40837. startTime = Date.now();
  40838. var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
  40839. var endTime = startTime + timerTime;
  40840. var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
  40841. var setupFallbackTimer = true;
  40842. if (animationsData.length) {
  40843. var currentTimerData = animationsData[0];
  40844. setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
  40845. if (setupFallbackTimer) {
  40846. $timeout.cancel(currentTimerData.timer);
  40847. } else {
  40848. animationsData.push(close);
  40849. }
  40850. }
  40851. if (setupFallbackTimer) {
  40852. var timer = $timeout(onAnimationExpired, timerTime, false);
  40853. animationsData[0] = {
  40854. timer: timer,
  40855. expectedEndTime: endTime
  40856. };
  40857. animationsData.push(close);
  40858. element.data(ANIMATE_TIMER_KEY, animationsData);
  40859. }
  40860. if (events.length) {
  40861. element.on(events.join(' '), onAnimationProgress);
  40862. }
  40863. if (options.to) {
  40864. if (options.cleanupStyles) {
  40865. registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
  40866. }
  40867. applyAnimationToStyles(element, options);
  40868. }
  40869. }
  40870. function onAnimationExpired() {
  40871. var animationsData = element.data(ANIMATE_TIMER_KEY);
  40872. // this will be false in the event that the element was
  40873. // removed from the DOM (via a leave animation or something
  40874. // similar)
  40875. if (animationsData) {
  40876. for (var i = 1; i < animationsData.length; i++) {
  40877. animationsData[i]();
  40878. }
  40879. element.removeData(ANIMATE_TIMER_KEY);
  40880. }
  40881. }
  40882. }
  40883. };
  40884. }];
  40885. }];
  40886. var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
  40887. $$animationProvider.drivers.push('$$animateCssDriver');
  40888. var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
  40889. var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
  40890. var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
  40891. var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
  40892. function isDocumentFragment(node) {
  40893. return node.parentNode && node.parentNode.nodeType === 11;
  40894. }
  40895. this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
  40896. function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
  40897. // only browsers that support these properties can render animations
  40898. if (!$sniffer.animations && !$sniffer.transitions) return noop;
  40899. var bodyNode = $document[0].body;
  40900. var rootNode = getDomNode($rootElement);
  40901. var rootBodyElement = jqLite(
  40902. // this is to avoid using something that exists outside of the body
  40903. // we also special case the doc fragment case because our unit test code
  40904. // appends the $rootElement to the body after the app has been bootstrapped
  40905. isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
  40906. );
  40907. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  40908. return function initDriverFn(animationDetails) {
  40909. return animationDetails.from && animationDetails.to
  40910. ? prepareFromToAnchorAnimation(animationDetails.from,
  40911. animationDetails.to,
  40912. animationDetails.classes,
  40913. animationDetails.anchors)
  40914. : prepareRegularAnimation(animationDetails);
  40915. };
  40916. function filterCssClasses(classes) {
  40917. //remove all the `ng-` stuff
  40918. return classes.replace(/\bng-\S+\b/g, '');
  40919. }
  40920. function getUniqueValues(a, b) {
  40921. if (isString(a)) a = a.split(' ');
  40922. if (isString(b)) b = b.split(' ');
  40923. return a.filter(function(val) {
  40924. return b.indexOf(val) === -1;
  40925. }).join(' ');
  40926. }
  40927. function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
  40928. var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
  40929. var startingClasses = filterCssClasses(getClassVal(clone));
  40930. outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  40931. inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  40932. clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
  40933. rootBodyElement.append(clone);
  40934. var animatorIn, animatorOut = prepareOutAnimation();
  40935. // the user may not end up using the `out` animation and
  40936. // only making use of the `in` animation or vice-versa.
  40937. // In either case we should allow this and not assume the
  40938. // animation is over unless both animations are not used.
  40939. if (!animatorOut) {
  40940. animatorIn = prepareInAnimation();
  40941. if (!animatorIn) {
  40942. return end();
  40943. }
  40944. }
  40945. var startingAnimator = animatorOut || animatorIn;
  40946. return {
  40947. start: function() {
  40948. var runner;
  40949. var currentAnimation = startingAnimator.start();
  40950. currentAnimation.done(function() {
  40951. currentAnimation = null;
  40952. if (!animatorIn) {
  40953. animatorIn = prepareInAnimation();
  40954. if (animatorIn) {
  40955. currentAnimation = animatorIn.start();
  40956. currentAnimation.done(function() {
  40957. currentAnimation = null;
  40958. end();
  40959. runner.complete();
  40960. });
  40961. return currentAnimation;
  40962. }
  40963. }
  40964. // in the event that there is no `in` animation
  40965. end();
  40966. runner.complete();
  40967. });
  40968. runner = new $$AnimateRunner({
  40969. end: endFn,
  40970. cancel: endFn
  40971. });
  40972. return runner;
  40973. function endFn() {
  40974. if (currentAnimation) {
  40975. currentAnimation.end();
  40976. }
  40977. }
  40978. }
  40979. };
  40980. function calculateAnchorStyles(anchor) {
  40981. var styles = {};
  40982. var coords = getDomNode(anchor).getBoundingClientRect();
  40983. // we iterate directly since safari messes up and doesn't return
  40984. // all the keys for the coords object when iterated
  40985. forEach(['width','height','top','left'], function(key) {
  40986. var value = coords[key];
  40987. switch (key) {
  40988. case 'top':
  40989. value += bodyNode.scrollTop;
  40990. break;
  40991. case 'left':
  40992. value += bodyNode.scrollLeft;
  40993. break;
  40994. }
  40995. styles[key] = Math.floor(value) + 'px';
  40996. });
  40997. return styles;
  40998. }
  40999. function prepareOutAnimation() {
  41000. var animator = $animateCss(clone, {
  41001. addClass: NG_OUT_ANCHOR_CLASS_NAME,
  41002. delay: true,
  41003. from: calculateAnchorStyles(outAnchor)
  41004. });
  41005. // read the comment within `prepareRegularAnimation` to understand
  41006. // why this check is necessary
  41007. return animator.$$willAnimate ? animator : null;
  41008. }
  41009. function getClassVal(element) {
  41010. return element.attr('class') || '';
  41011. }
  41012. function prepareInAnimation() {
  41013. var endingClasses = filterCssClasses(getClassVal(inAnchor));
  41014. var toAdd = getUniqueValues(endingClasses, startingClasses);
  41015. var toRemove = getUniqueValues(startingClasses, endingClasses);
  41016. var animator = $animateCss(clone, {
  41017. to: calculateAnchorStyles(inAnchor),
  41018. addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
  41019. removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
  41020. delay: true
  41021. });
  41022. // read the comment within `prepareRegularAnimation` to understand
  41023. // why this check is necessary
  41024. return animator.$$willAnimate ? animator : null;
  41025. }
  41026. function end() {
  41027. clone.remove();
  41028. outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  41029. inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  41030. }
  41031. }
  41032. function prepareFromToAnchorAnimation(from, to, classes, anchors) {
  41033. var fromAnimation = prepareRegularAnimation(from, noop);
  41034. var toAnimation = prepareRegularAnimation(to, noop);
  41035. var anchorAnimations = [];
  41036. forEach(anchors, function(anchor) {
  41037. var outElement = anchor['out'];
  41038. var inElement = anchor['in'];
  41039. var animator = prepareAnchoredAnimation(classes, outElement, inElement);
  41040. if (animator) {
  41041. anchorAnimations.push(animator);
  41042. }
  41043. });
  41044. // no point in doing anything when there are no elements to animate
  41045. if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
  41046. return {
  41047. start: function() {
  41048. var animationRunners = [];
  41049. if (fromAnimation) {
  41050. animationRunners.push(fromAnimation.start());
  41051. }
  41052. if (toAnimation) {
  41053. animationRunners.push(toAnimation.start());
  41054. }
  41055. forEach(anchorAnimations, function(animation) {
  41056. animationRunners.push(animation.start());
  41057. });
  41058. var runner = new $$AnimateRunner({
  41059. end: endFn,
  41060. cancel: endFn // CSS-driven animations cannot be cancelled, only ended
  41061. });
  41062. $$AnimateRunner.all(animationRunners, function(status) {
  41063. runner.complete(status);
  41064. });
  41065. return runner;
  41066. function endFn() {
  41067. forEach(animationRunners, function(runner) {
  41068. runner.end();
  41069. });
  41070. }
  41071. }
  41072. };
  41073. }
  41074. function prepareRegularAnimation(animationDetails) {
  41075. var element = animationDetails.element;
  41076. var options = animationDetails.options || {};
  41077. if (animationDetails.structural) {
  41078. options.event = animationDetails.event;
  41079. options.structural = true;
  41080. options.applyClassesEarly = true;
  41081. // we special case the leave animation since we want to ensure that
  41082. // the element is removed as soon as the animation is over. Otherwise
  41083. // a flicker might appear or the element may not be removed at all
  41084. if (animationDetails.event === 'leave') {
  41085. options.onDone = options.domOperation;
  41086. }
  41087. }
  41088. // We assign the preparationClasses as the actual animation event since
  41089. // the internals of $animateCss will just suffix the event token values
  41090. // with `-active` to trigger the animation.
  41091. if (options.preparationClasses) {
  41092. options.event = concatWithSpace(options.event, options.preparationClasses);
  41093. }
  41094. var animator = $animateCss(element, options);
  41095. // the driver lookup code inside of $$animation attempts to spawn a
  41096. // driver one by one until a driver returns a.$$willAnimate animator object.
  41097. // $animateCss will always return an object, however, it will pass in
  41098. // a flag as a hint as to whether an animation was detected or not
  41099. return animator.$$willAnimate ? animator : null;
  41100. }
  41101. }];
  41102. }];
  41103. // TODO(matsko): use caching here to speed things up for detection
  41104. // TODO(matsko): add documentation
  41105. // by the time...
  41106. var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
  41107. this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
  41108. function($injector, $$AnimateRunner, $$jqLite) {
  41109. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41110. // $animateJs(element, 'enter');
  41111. return function(element, event, classes, options) {
  41112. var animationClosed = false;
  41113. // the `classes` argument is optional and if it is not used
  41114. // then the classes will be resolved from the element's className
  41115. // property as well as options.addClass/options.removeClass.
  41116. if (arguments.length === 3 && isObject(classes)) {
  41117. options = classes;
  41118. classes = null;
  41119. }
  41120. options = prepareAnimationOptions(options);
  41121. if (!classes) {
  41122. classes = element.attr('class') || '';
  41123. if (options.addClass) {
  41124. classes += ' ' + options.addClass;
  41125. }
  41126. if (options.removeClass) {
  41127. classes += ' ' + options.removeClass;
  41128. }
  41129. }
  41130. var classesToAdd = options.addClass;
  41131. var classesToRemove = options.removeClass;
  41132. // the lookupAnimations function returns a series of animation objects that are
  41133. // matched up with one or more of the CSS classes. These animation objects are
  41134. // defined via the module.animation factory function. If nothing is detected then
  41135. // we don't return anything which then makes $animation query the next driver.
  41136. var animations = lookupAnimations(classes);
  41137. var before, after;
  41138. if (animations.length) {
  41139. var afterFn, beforeFn;
  41140. if (event == 'leave') {
  41141. beforeFn = 'leave';
  41142. afterFn = 'afterLeave'; // TODO(matsko): get rid of this
  41143. } else {
  41144. beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
  41145. afterFn = event;
  41146. }
  41147. if (event !== 'enter' && event !== 'move') {
  41148. before = packageAnimations(element, event, options, animations, beforeFn);
  41149. }
  41150. after = packageAnimations(element, event, options, animations, afterFn);
  41151. }
  41152. // no matching animations
  41153. if (!before && !after) return;
  41154. function applyOptions() {
  41155. options.domOperation();
  41156. applyAnimationClasses(element, options);
  41157. }
  41158. function close() {
  41159. animationClosed = true;
  41160. applyOptions();
  41161. applyAnimationStyles(element, options);
  41162. }
  41163. var runner;
  41164. return {
  41165. $$willAnimate: true,
  41166. end: function() {
  41167. if (runner) {
  41168. runner.end();
  41169. } else {
  41170. close();
  41171. runner = new $$AnimateRunner();
  41172. runner.complete(true);
  41173. }
  41174. return runner;
  41175. },
  41176. start: function() {
  41177. if (runner) {
  41178. return runner;
  41179. }
  41180. runner = new $$AnimateRunner();
  41181. var closeActiveAnimations;
  41182. var chain = [];
  41183. if (before) {
  41184. chain.push(function(fn) {
  41185. closeActiveAnimations = before(fn);
  41186. });
  41187. }
  41188. if (chain.length) {
  41189. chain.push(function(fn) {
  41190. applyOptions();
  41191. fn(true);
  41192. });
  41193. } else {
  41194. applyOptions();
  41195. }
  41196. if (after) {
  41197. chain.push(function(fn) {
  41198. closeActiveAnimations = after(fn);
  41199. });
  41200. }
  41201. runner.setHost({
  41202. end: function() {
  41203. endAnimations();
  41204. },
  41205. cancel: function() {
  41206. endAnimations(true);
  41207. }
  41208. });
  41209. $$AnimateRunner.chain(chain, onComplete);
  41210. return runner;
  41211. function onComplete(success) {
  41212. close(success);
  41213. runner.complete(success);
  41214. }
  41215. function endAnimations(cancelled) {
  41216. if (!animationClosed) {
  41217. (closeActiveAnimations || noop)(cancelled);
  41218. onComplete(cancelled);
  41219. }
  41220. }
  41221. }
  41222. };
  41223. function executeAnimationFn(fn, element, event, options, onDone) {
  41224. var args;
  41225. switch (event) {
  41226. case 'animate':
  41227. args = [element, options.from, options.to, onDone];
  41228. break;
  41229. case 'setClass':
  41230. args = [element, classesToAdd, classesToRemove, onDone];
  41231. break;
  41232. case 'addClass':
  41233. args = [element, classesToAdd, onDone];
  41234. break;
  41235. case 'removeClass':
  41236. args = [element, classesToRemove, onDone];
  41237. break;
  41238. default:
  41239. args = [element, onDone];
  41240. break;
  41241. }
  41242. args.push(options);
  41243. var value = fn.apply(fn, args);
  41244. if (value) {
  41245. if (isFunction(value.start)) {
  41246. value = value.start();
  41247. }
  41248. if (value instanceof $$AnimateRunner) {
  41249. value.done(onDone);
  41250. } else if (isFunction(value)) {
  41251. // optional onEnd / onCancel callback
  41252. return value;
  41253. }
  41254. }
  41255. return noop;
  41256. }
  41257. function groupEventedAnimations(element, event, options, animations, fnName) {
  41258. var operations = [];
  41259. forEach(animations, function(ani) {
  41260. var animation = ani[fnName];
  41261. if (!animation) return;
  41262. // note that all of these animations will run in parallel
  41263. operations.push(function() {
  41264. var runner;
  41265. var endProgressCb;
  41266. var resolved = false;
  41267. var onAnimationComplete = function(rejected) {
  41268. if (!resolved) {
  41269. resolved = true;
  41270. (endProgressCb || noop)(rejected);
  41271. runner.complete(!rejected);
  41272. }
  41273. };
  41274. runner = new $$AnimateRunner({
  41275. end: function() {
  41276. onAnimationComplete();
  41277. },
  41278. cancel: function() {
  41279. onAnimationComplete(true);
  41280. }
  41281. });
  41282. endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
  41283. var cancelled = result === false;
  41284. onAnimationComplete(cancelled);
  41285. });
  41286. return runner;
  41287. });
  41288. });
  41289. return operations;
  41290. }
  41291. function packageAnimations(element, event, options, animations, fnName) {
  41292. var operations = groupEventedAnimations(element, event, options, animations, fnName);
  41293. if (operations.length === 0) {
  41294. var a,b;
  41295. if (fnName === 'beforeSetClass') {
  41296. a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
  41297. b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
  41298. } else if (fnName === 'setClass') {
  41299. a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
  41300. b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
  41301. }
  41302. if (a) {
  41303. operations = operations.concat(a);
  41304. }
  41305. if (b) {
  41306. operations = operations.concat(b);
  41307. }
  41308. }
  41309. if (operations.length === 0) return;
  41310. // TODO(matsko): add documentation
  41311. return function startAnimation(callback) {
  41312. var runners = [];
  41313. if (operations.length) {
  41314. forEach(operations, function(animateFn) {
  41315. runners.push(animateFn());
  41316. });
  41317. }
  41318. runners.length ? $$AnimateRunner.all(runners, callback) : callback();
  41319. return function endFn(reject) {
  41320. forEach(runners, function(runner) {
  41321. reject ? runner.cancel() : runner.end();
  41322. });
  41323. };
  41324. };
  41325. }
  41326. };
  41327. function lookupAnimations(classes) {
  41328. classes = isArray(classes) ? classes : classes.split(' ');
  41329. var matches = [], flagMap = {};
  41330. for (var i=0; i < classes.length; i++) {
  41331. var klass = classes[i],
  41332. animationFactory = $animateProvider.$$registeredAnimations[klass];
  41333. if (animationFactory && !flagMap[klass]) {
  41334. matches.push($injector.get(animationFactory));
  41335. flagMap[klass] = true;
  41336. }
  41337. }
  41338. return matches;
  41339. }
  41340. }];
  41341. }];
  41342. var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
  41343. $$animationProvider.drivers.push('$$animateJsDriver');
  41344. this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
  41345. return function initDriverFn(animationDetails) {
  41346. if (animationDetails.from && animationDetails.to) {
  41347. var fromAnimation = prepareAnimation(animationDetails.from);
  41348. var toAnimation = prepareAnimation(animationDetails.to);
  41349. if (!fromAnimation && !toAnimation) return;
  41350. return {
  41351. start: function() {
  41352. var animationRunners = [];
  41353. if (fromAnimation) {
  41354. animationRunners.push(fromAnimation.start());
  41355. }
  41356. if (toAnimation) {
  41357. animationRunners.push(toAnimation.start());
  41358. }
  41359. $$AnimateRunner.all(animationRunners, done);
  41360. var runner = new $$AnimateRunner({
  41361. end: endFnFactory(),
  41362. cancel: endFnFactory()
  41363. });
  41364. return runner;
  41365. function endFnFactory() {
  41366. return function() {
  41367. forEach(animationRunners, function(runner) {
  41368. // at this point we cannot cancel animations for groups just yet. 1.5+
  41369. runner.end();
  41370. });
  41371. };
  41372. }
  41373. function done(status) {
  41374. runner.complete(status);
  41375. }
  41376. }
  41377. };
  41378. } else {
  41379. return prepareAnimation(animationDetails);
  41380. }
  41381. };
  41382. function prepareAnimation(animationDetails) {
  41383. // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
  41384. var element = animationDetails.element;
  41385. var event = animationDetails.event;
  41386. var options = animationDetails.options;
  41387. var classes = animationDetails.classes;
  41388. return $$animateJs(element, event, classes, options);
  41389. }
  41390. }];
  41391. }];
  41392. var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
  41393. var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
  41394. var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
  41395. var PRE_DIGEST_STATE = 1;
  41396. var RUNNING_STATE = 2;
  41397. var ONE_SPACE = ' ';
  41398. var rules = this.rules = {
  41399. skip: [],
  41400. cancel: [],
  41401. join: []
  41402. };
  41403. function makeTruthyCssClassMap(classString) {
  41404. if (!classString) {
  41405. return null;
  41406. }
  41407. var keys = classString.split(ONE_SPACE);
  41408. var map = Object.create(null);
  41409. forEach(keys, function(key) {
  41410. map[key] = true;
  41411. });
  41412. return map;
  41413. }
  41414. function hasMatchingClasses(newClassString, currentClassString) {
  41415. if (newClassString && currentClassString) {
  41416. var currentClassMap = makeTruthyCssClassMap(currentClassString);
  41417. return newClassString.split(ONE_SPACE).some(function(className) {
  41418. return currentClassMap[className];
  41419. });
  41420. }
  41421. }
  41422. function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
  41423. return rules[ruleType].some(function(fn) {
  41424. return fn(element, currentAnimation, previousAnimation);
  41425. });
  41426. }
  41427. function hasAnimationClasses(animation, and) {
  41428. var a = (animation.addClass || '').length > 0;
  41429. var b = (animation.removeClass || '').length > 0;
  41430. return and ? a && b : a || b;
  41431. }
  41432. rules.join.push(function(element, newAnimation, currentAnimation) {
  41433. // if the new animation is class-based then we can just tack that on
  41434. return !newAnimation.structural && hasAnimationClasses(newAnimation);
  41435. });
  41436. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41437. // there is no need to animate anything if no classes are being added and
  41438. // there is no structural animation that will be triggered
  41439. return !newAnimation.structural && !hasAnimationClasses(newAnimation);
  41440. });
  41441. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41442. // why should we trigger a new structural animation if the element will
  41443. // be removed from the DOM anyway?
  41444. return currentAnimation.event == 'leave' && newAnimation.structural;
  41445. });
  41446. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41447. // if there is an ongoing current animation then don't even bother running the class-based animation
  41448. return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
  41449. });
  41450. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41451. // there can never be two structural animations running at the same time
  41452. return currentAnimation.structural && newAnimation.structural;
  41453. });
  41454. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41455. // if the previous animation is already running, but the new animation will
  41456. // be triggered, but the new animation is structural
  41457. return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
  41458. });
  41459. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41460. // cancel the animation if classes added / removed in both animation cancel each other out,
  41461. // but only if the current animation isn't structural
  41462. if (currentAnimation.structural) return false;
  41463. var nA = newAnimation.addClass;
  41464. var nR = newAnimation.removeClass;
  41465. var cA = currentAnimation.addClass;
  41466. var cR = currentAnimation.removeClass;
  41467. // early detection to save the global CPU shortage :)
  41468. if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
  41469. return false;
  41470. }
  41471. return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
  41472. });
  41473. this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
  41474. '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
  41475. function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
  41476. $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
  41477. var activeAnimationsLookup = new $$HashMap();
  41478. var disabledElementsLookup = new $$HashMap();
  41479. var animationsEnabled = null;
  41480. function postDigestTaskFactory() {
  41481. var postDigestCalled = false;
  41482. return function(fn) {
  41483. // we only issue a call to postDigest before
  41484. // it has first passed. This prevents any callbacks
  41485. // from not firing once the animation has completed
  41486. // since it will be out of the digest cycle.
  41487. if (postDigestCalled) {
  41488. fn();
  41489. } else {
  41490. $rootScope.$$postDigest(function() {
  41491. postDigestCalled = true;
  41492. fn();
  41493. });
  41494. }
  41495. };
  41496. }
  41497. // Wait until all directive and route-related templates are downloaded and
  41498. // compiled. The $templateRequest.totalPendingRequests variable keeps track of
  41499. // all of the remote templates being currently downloaded. If there are no
  41500. // templates currently downloading then the watcher will still fire anyway.
  41501. var deregisterWatch = $rootScope.$watch(
  41502. function() { return $templateRequest.totalPendingRequests === 0; },
  41503. function(isEmpty) {
  41504. if (!isEmpty) return;
  41505. deregisterWatch();
  41506. // Now that all templates have been downloaded, $animate will wait until
  41507. // the post digest queue is empty before enabling animations. By having two
  41508. // calls to $postDigest calls we can ensure that the flag is enabled at the
  41509. // very end of the post digest queue. Since all of the animations in $animate
  41510. // use $postDigest, it's important that the code below executes at the end.
  41511. // This basically means that the page is fully downloaded and compiled before
  41512. // any animations are triggered.
  41513. $rootScope.$$postDigest(function() {
  41514. $rootScope.$$postDigest(function() {
  41515. // we check for null directly in the event that the application already called
  41516. // .enabled() with whatever arguments that it provided it with
  41517. if (animationsEnabled === null) {
  41518. animationsEnabled = true;
  41519. }
  41520. });
  41521. });
  41522. }
  41523. );
  41524. var callbackRegistry = {};
  41525. // remember that the classNameFilter is set during the provider/config
  41526. // stage therefore we can optimize here and setup a helper function
  41527. var classNameFilter = $animateProvider.classNameFilter();
  41528. var isAnimatableClassName = !classNameFilter
  41529. ? function() { return true; }
  41530. : function(className) {
  41531. return classNameFilter.test(className);
  41532. };
  41533. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41534. function normalizeAnimationDetails(element, animation) {
  41535. return mergeAnimationDetails(element, animation, {});
  41536. }
  41537. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  41538. var contains = Node.prototype.contains || function(arg) {
  41539. // jshint bitwise: false
  41540. return this === arg || !!(this.compareDocumentPosition(arg) & 16);
  41541. // jshint bitwise: true
  41542. };
  41543. function findCallbacks(parent, element, event) {
  41544. var targetNode = getDomNode(element);
  41545. var targetParentNode = getDomNode(parent);
  41546. var matches = [];
  41547. var entries = callbackRegistry[event];
  41548. if (entries) {
  41549. forEach(entries, function(entry) {
  41550. if (contains.call(entry.node, targetNode)) {
  41551. matches.push(entry.callback);
  41552. } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
  41553. matches.push(entry.callback);
  41554. }
  41555. });
  41556. }
  41557. return matches;
  41558. }
  41559. var $animate = {
  41560. on: function(event, container, callback) {
  41561. var node = extractElementNode(container);
  41562. callbackRegistry[event] = callbackRegistry[event] || [];
  41563. callbackRegistry[event].push({
  41564. node: node,
  41565. callback: callback
  41566. });
  41567. // Remove the callback when the element is removed from the DOM
  41568. jqLite(container).on('$destroy', function() {
  41569. $animate.off(event, container, callback);
  41570. });
  41571. },
  41572. off: function(event, container, callback) {
  41573. var entries = callbackRegistry[event];
  41574. if (!entries) return;
  41575. callbackRegistry[event] = arguments.length === 1
  41576. ? null
  41577. : filterFromRegistry(entries, container, callback);
  41578. function filterFromRegistry(list, matchContainer, matchCallback) {
  41579. var containerNode = extractElementNode(matchContainer);
  41580. return list.filter(function(entry) {
  41581. var isMatch = entry.node === containerNode &&
  41582. (!matchCallback || entry.callback === matchCallback);
  41583. return !isMatch;
  41584. });
  41585. }
  41586. },
  41587. pin: function(element, parentElement) {
  41588. assertArg(isElement(element), 'element', 'not an element');
  41589. assertArg(isElement(parentElement), 'parentElement', 'not an element');
  41590. element.data(NG_ANIMATE_PIN_DATA, parentElement);
  41591. },
  41592. push: function(element, event, options, domOperation) {
  41593. options = options || {};
  41594. options.domOperation = domOperation;
  41595. return queueAnimation(element, event, options);
  41596. },
  41597. // this method has four signatures:
  41598. // () - global getter
  41599. // (bool) - global setter
  41600. // (element) - element getter
  41601. // (element, bool) - element setter<F37>
  41602. enabled: function(element, bool) {
  41603. var argCount = arguments.length;
  41604. if (argCount === 0) {
  41605. // () - Global getter
  41606. bool = !!animationsEnabled;
  41607. } else {
  41608. var hasElement = isElement(element);
  41609. if (!hasElement) {
  41610. // (bool) - Global setter
  41611. bool = animationsEnabled = !!element;
  41612. } else {
  41613. var node = getDomNode(element);
  41614. var recordExists = disabledElementsLookup.get(node);
  41615. if (argCount === 1) {
  41616. // (element) - Element getter
  41617. bool = !recordExists;
  41618. } else {
  41619. // (element, bool) - Element setter
  41620. disabledElementsLookup.put(node, !bool);
  41621. }
  41622. }
  41623. }
  41624. return bool;
  41625. }
  41626. };
  41627. return $animate;
  41628. function queueAnimation(element, event, initialOptions) {
  41629. // we always make a copy of the options since
  41630. // there should never be any side effects on
  41631. // the input data when running `$animateCss`.
  41632. var options = copy(initialOptions);
  41633. var node, parent;
  41634. element = stripCommentsFromElement(element);
  41635. if (element) {
  41636. node = getDomNode(element);
  41637. parent = element.parent();
  41638. }
  41639. options = prepareAnimationOptions(options);
  41640. // we create a fake runner with a working promise.
  41641. // These methods will become available after the digest has passed
  41642. var runner = new $$AnimateRunner();
  41643. // this is used to trigger callbacks in postDigest mode
  41644. var runInNextPostDigestOrNow = postDigestTaskFactory();
  41645. if (isArray(options.addClass)) {
  41646. options.addClass = options.addClass.join(' ');
  41647. }
  41648. if (options.addClass && !isString(options.addClass)) {
  41649. options.addClass = null;
  41650. }
  41651. if (isArray(options.removeClass)) {
  41652. options.removeClass = options.removeClass.join(' ');
  41653. }
  41654. if (options.removeClass && !isString(options.removeClass)) {
  41655. options.removeClass = null;
  41656. }
  41657. if (options.from && !isObject(options.from)) {
  41658. options.from = null;
  41659. }
  41660. if (options.to && !isObject(options.to)) {
  41661. options.to = null;
  41662. }
  41663. // there are situations where a directive issues an animation for
  41664. // a jqLite wrapper that contains only comment nodes... If this
  41665. // happens then there is no way we can perform an animation
  41666. if (!node) {
  41667. close();
  41668. return runner;
  41669. }
  41670. var className = [node.className, options.addClass, options.removeClass].join(' ');
  41671. if (!isAnimatableClassName(className)) {
  41672. close();
  41673. return runner;
  41674. }
  41675. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  41676. // this is a hard disable of all animations for the application or on
  41677. // the element itself, therefore there is no need to continue further
  41678. // past this point if not enabled
  41679. // Animations are also disabled if the document is currently hidden (page is not visible
  41680. // to the user), because browsers slow down or do not flush calls to requestAnimationFrame
  41681. var skipAnimations = !animationsEnabled || $document[0].hidden || disabledElementsLookup.get(node);
  41682. var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
  41683. var hasExistingAnimation = !!existingAnimation.state;
  41684. // there is no point in traversing the same collection of parent ancestors if a followup
  41685. // animation will be run on the same element that already did all that checking work
  41686. if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
  41687. skipAnimations = !areAnimationsAllowed(element, parent, event);
  41688. }
  41689. if (skipAnimations) {
  41690. close();
  41691. return runner;
  41692. }
  41693. if (isStructural) {
  41694. closeChildAnimations(element);
  41695. }
  41696. var newAnimation = {
  41697. structural: isStructural,
  41698. element: element,
  41699. event: event,
  41700. addClass: options.addClass,
  41701. removeClass: options.removeClass,
  41702. close: close,
  41703. options: options,
  41704. runner: runner
  41705. };
  41706. if (hasExistingAnimation) {
  41707. var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
  41708. if (skipAnimationFlag) {
  41709. if (existingAnimation.state === RUNNING_STATE) {
  41710. close();
  41711. return runner;
  41712. } else {
  41713. mergeAnimationDetails(element, existingAnimation, newAnimation);
  41714. return existingAnimation.runner;
  41715. }
  41716. }
  41717. var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
  41718. if (cancelAnimationFlag) {
  41719. if (existingAnimation.state === RUNNING_STATE) {
  41720. // this will end the animation right away and it is safe
  41721. // to do so since the animation is already running and the
  41722. // runner callback code will run in async
  41723. existingAnimation.runner.end();
  41724. } else if (existingAnimation.structural) {
  41725. // this means that the animation is queued into a digest, but
  41726. // hasn't started yet. Therefore it is safe to run the close
  41727. // method which will call the runner methods in async.
  41728. existingAnimation.close();
  41729. } else {
  41730. // this will merge the new animation options into existing animation options
  41731. mergeAnimationDetails(element, existingAnimation, newAnimation);
  41732. return existingAnimation.runner;
  41733. }
  41734. } else {
  41735. // a joined animation means that this animation will take over the existing one
  41736. // so an example would involve a leave animation taking over an enter. Then when
  41737. // the postDigest kicks in the enter will be ignored.
  41738. var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
  41739. if (joinAnimationFlag) {
  41740. if (existingAnimation.state === RUNNING_STATE) {
  41741. normalizeAnimationDetails(element, newAnimation);
  41742. } else {
  41743. applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
  41744. event = newAnimation.event = existingAnimation.event;
  41745. options = mergeAnimationDetails(element, existingAnimation, newAnimation);
  41746. //we return the same runner since only the option values of this animation will
  41747. //be fed into the `existingAnimation`.
  41748. return existingAnimation.runner;
  41749. }
  41750. }
  41751. }
  41752. } else {
  41753. // normalization in this case means that it removes redundant CSS classes that
  41754. // already exist (addClass) or do not exist (removeClass) on the element
  41755. normalizeAnimationDetails(element, newAnimation);
  41756. }
  41757. // when the options are merged and cleaned up we may end up not having to do
  41758. // an animation at all, therefore we should check this before issuing a post
  41759. // digest callback. Structural animations will always run no matter what.
  41760. var isValidAnimation = newAnimation.structural;
  41761. if (!isValidAnimation) {
  41762. // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
  41763. isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
  41764. || hasAnimationClasses(newAnimation);
  41765. }
  41766. if (!isValidAnimation) {
  41767. close();
  41768. clearElementAnimationState(element);
  41769. return runner;
  41770. }
  41771. // the counter keeps track of cancelled animations
  41772. var counter = (existingAnimation.counter || 0) + 1;
  41773. newAnimation.counter = counter;
  41774. markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
  41775. $rootScope.$$postDigest(function() {
  41776. var animationDetails = activeAnimationsLookup.get(node);
  41777. var animationCancelled = !animationDetails;
  41778. animationDetails = animationDetails || {};
  41779. // if addClass/removeClass is called before something like enter then the
  41780. // registered parent element may not be present. The code below will ensure
  41781. // that a final value for parent element is obtained
  41782. var parentElement = element.parent() || [];
  41783. // animate/structural/class-based animations all have requirements. Otherwise there
  41784. // is no point in performing an animation. The parent node must also be set.
  41785. var isValidAnimation = parentElement.length > 0
  41786. && (animationDetails.event === 'animate'
  41787. || animationDetails.structural
  41788. || hasAnimationClasses(animationDetails));
  41789. // this means that the previous animation was cancelled
  41790. // even if the follow-up animation is the same event
  41791. if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
  41792. // if another animation did not take over then we need
  41793. // to make sure that the domOperation and options are
  41794. // handled accordingly
  41795. if (animationCancelled) {
  41796. applyAnimationClasses(element, options);
  41797. applyAnimationStyles(element, options);
  41798. }
  41799. // if the event changed from something like enter to leave then we do
  41800. // it, otherwise if it's the same then the end result will be the same too
  41801. if (animationCancelled || (isStructural && animationDetails.event !== event)) {
  41802. options.domOperation();
  41803. runner.end();
  41804. }
  41805. // in the event that the element animation was not cancelled or a follow-up animation
  41806. // isn't allowed to animate from here then we need to clear the state of the element
  41807. // so that any future animations won't read the expired animation data.
  41808. if (!isValidAnimation) {
  41809. clearElementAnimationState(element);
  41810. }
  41811. return;
  41812. }
  41813. // this combined multiple class to addClass / removeClass into a setClass event
  41814. // so long as a structural event did not take over the animation
  41815. event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
  41816. ? 'setClass'
  41817. : animationDetails.event;
  41818. markElementAnimationState(element, RUNNING_STATE);
  41819. var realRunner = $$animation(element, event, animationDetails.options);
  41820. realRunner.done(function(status) {
  41821. close(!status);
  41822. var animationDetails = activeAnimationsLookup.get(node);
  41823. if (animationDetails && animationDetails.counter === counter) {
  41824. clearElementAnimationState(getDomNode(element));
  41825. }
  41826. notifyProgress(runner, event, 'close', {});
  41827. });
  41828. // this will update the runner's flow-control events based on
  41829. // the `realRunner` object.
  41830. runner.setHost(realRunner);
  41831. notifyProgress(runner, event, 'start', {});
  41832. });
  41833. return runner;
  41834. function notifyProgress(runner, event, phase, data) {
  41835. runInNextPostDigestOrNow(function() {
  41836. var callbacks = findCallbacks(parent, element, event);
  41837. if (callbacks.length) {
  41838. // do not optimize this call here to RAF because
  41839. // we don't know how heavy the callback code here will
  41840. // be and if this code is buffered then this can
  41841. // lead to a performance regression.
  41842. $$rAF(function() {
  41843. forEach(callbacks, function(callback) {
  41844. callback(element, phase, data);
  41845. });
  41846. });
  41847. }
  41848. });
  41849. runner.progress(event, phase, data);
  41850. }
  41851. function close(reject) { // jshint ignore:line
  41852. clearGeneratedClasses(element, options);
  41853. applyAnimationClasses(element, options);
  41854. applyAnimationStyles(element, options);
  41855. options.domOperation();
  41856. runner.complete(!reject);
  41857. }
  41858. }
  41859. function closeChildAnimations(element) {
  41860. var node = getDomNode(element);
  41861. var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
  41862. forEach(children, function(child) {
  41863. var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
  41864. var animationDetails = activeAnimationsLookup.get(child);
  41865. if (animationDetails) {
  41866. switch (state) {
  41867. case RUNNING_STATE:
  41868. animationDetails.runner.end();
  41869. /* falls through */
  41870. case PRE_DIGEST_STATE:
  41871. activeAnimationsLookup.remove(child);
  41872. break;
  41873. }
  41874. }
  41875. });
  41876. }
  41877. function clearElementAnimationState(element) {
  41878. var node = getDomNode(element);
  41879. node.removeAttribute(NG_ANIMATE_ATTR_NAME);
  41880. activeAnimationsLookup.remove(node);
  41881. }
  41882. function isMatchingElement(nodeOrElmA, nodeOrElmB) {
  41883. return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
  41884. }
  41885. /**
  41886. * This fn returns false if any of the following is true:
  41887. * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
  41888. * b) a parent element has an ongoing structural animation, and animateChildren is false
  41889. * c) the element is not a child of the body
  41890. * d) the element is not a child of the $rootElement
  41891. */
  41892. function areAnimationsAllowed(element, parentElement, event) {
  41893. var bodyElement = jqLite($document[0].body);
  41894. var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
  41895. var rootElementDetected = isMatchingElement(element, $rootElement);
  41896. var parentAnimationDetected = false;
  41897. var animateChildren;
  41898. var elementDisabled = disabledElementsLookup.get(getDomNode(element));
  41899. var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA);
  41900. if (parentHost) {
  41901. parentElement = parentHost;
  41902. }
  41903. parentElement = getDomNode(parentElement);
  41904. while (parentElement) {
  41905. if (!rootElementDetected) {
  41906. // angular doesn't want to attempt to animate elements outside of the application
  41907. // therefore we need to ensure that the rootElement is an ancestor of the current element
  41908. rootElementDetected = isMatchingElement(parentElement, $rootElement);
  41909. }
  41910. if (parentElement.nodeType !== ELEMENT_NODE) {
  41911. // no point in inspecting the #document element
  41912. break;
  41913. }
  41914. var details = activeAnimationsLookup.get(parentElement) || {};
  41915. // either an enter, leave or move animation will commence
  41916. // therefore we can't allow any animations to take place
  41917. // but if a parent animation is class-based then that's ok
  41918. if (!parentAnimationDetected) {
  41919. var parentElementDisabled = disabledElementsLookup.get(parentElement);
  41920. if (parentElementDisabled === true && elementDisabled !== false) {
  41921. // disable animations if the user hasn't explicitly enabled animations on the
  41922. // current element
  41923. elementDisabled = true;
  41924. // element is disabled via parent element, no need to check anything else
  41925. break;
  41926. } else if (parentElementDisabled === false) {
  41927. elementDisabled = false;
  41928. }
  41929. parentAnimationDetected = details.structural;
  41930. }
  41931. if (isUndefined(animateChildren) || animateChildren === true) {
  41932. var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA);
  41933. if (isDefined(value)) {
  41934. animateChildren = value;
  41935. }
  41936. }
  41937. // there is no need to continue traversing at this point
  41938. if (parentAnimationDetected && animateChildren === false) break;
  41939. if (!bodyElementDetected) {
  41940. // we also need to ensure that the element is or will be a part of the body element
  41941. // otherwise it is pointless to even issue an animation to be rendered
  41942. bodyElementDetected = isMatchingElement(parentElement, bodyElement);
  41943. }
  41944. if (bodyElementDetected && rootElementDetected) {
  41945. // If both body and root have been found, any other checks are pointless,
  41946. // as no animation data should live outside the application
  41947. break;
  41948. }
  41949. if (!rootElementDetected) {
  41950. // If no rootElement is detected, check if the parentElement is pinned to another element
  41951. parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA);
  41952. if (parentHost) {
  41953. // The pin target element becomes the next parent element
  41954. parentElement = getDomNode(parentHost);
  41955. continue;
  41956. }
  41957. }
  41958. parentElement = parentElement.parentNode;
  41959. }
  41960. var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
  41961. return allowAnimation && rootElementDetected && bodyElementDetected;
  41962. }
  41963. function markElementAnimationState(element, state, details) {
  41964. details = details || {};
  41965. details.state = state;
  41966. var node = getDomNode(element);
  41967. node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
  41968. var oldValue = activeAnimationsLookup.get(node);
  41969. var newValue = oldValue
  41970. ? extend(oldValue, details)
  41971. : details;
  41972. activeAnimationsLookup.put(node, newValue);
  41973. }
  41974. }];
  41975. }];
  41976. var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
  41977. var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
  41978. var drivers = this.drivers = [];
  41979. var RUNNER_STORAGE_KEY = '$$animationRunner';
  41980. function setRunner(element, runner) {
  41981. element.data(RUNNER_STORAGE_KEY, runner);
  41982. }
  41983. function removeRunner(element) {
  41984. element.removeData(RUNNER_STORAGE_KEY);
  41985. }
  41986. function getRunner(element) {
  41987. return element.data(RUNNER_STORAGE_KEY);
  41988. }
  41989. this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
  41990. function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
  41991. var animationQueue = [];
  41992. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41993. function sortAnimations(animations) {
  41994. var tree = { children: [] };
  41995. var i, lookup = new $$HashMap();
  41996. // this is done first beforehand so that the hashmap
  41997. // is filled with a list of the elements that will be animated
  41998. for (i = 0; i < animations.length; i++) {
  41999. var animation = animations[i];
  42000. lookup.put(animation.domNode, animations[i] = {
  42001. domNode: animation.domNode,
  42002. fn: animation.fn,
  42003. children: []
  42004. });
  42005. }
  42006. for (i = 0; i < animations.length; i++) {
  42007. processNode(animations[i]);
  42008. }
  42009. return flatten(tree);
  42010. function processNode(entry) {
  42011. if (entry.processed) return entry;
  42012. entry.processed = true;
  42013. var elementNode = entry.domNode;
  42014. var parentNode = elementNode.parentNode;
  42015. lookup.put(elementNode, entry);
  42016. var parentEntry;
  42017. while (parentNode) {
  42018. parentEntry = lookup.get(parentNode);
  42019. if (parentEntry) {
  42020. if (!parentEntry.processed) {
  42021. parentEntry = processNode(parentEntry);
  42022. }
  42023. break;
  42024. }
  42025. parentNode = parentNode.parentNode;
  42026. }
  42027. (parentEntry || tree).children.push(entry);
  42028. return entry;
  42029. }
  42030. function flatten(tree) {
  42031. var result = [];
  42032. var queue = [];
  42033. var i;
  42034. for (i = 0; i < tree.children.length; i++) {
  42035. queue.push(tree.children[i]);
  42036. }
  42037. var remainingLevelEntries = queue.length;
  42038. var nextLevelEntries = 0;
  42039. var row = [];
  42040. for (i = 0; i < queue.length; i++) {
  42041. var entry = queue[i];
  42042. if (remainingLevelEntries <= 0) {
  42043. remainingLevelEntries = nextLevelEntries;
  42044. nextLevelEntries = 0;
  42045. result.push(row);
  42046. row = [];
  42047. }
  42048. row.push(entry.fn);
  42049. entry.children.forEach(function(childEntry) {
  42050. nextLevelEntries++;
  42051. queue.push(childEntry);
  42052. });
  42053. remainingLevelEntries--;
  42054. }
  42055. if (row.length) {
  42056. result.push(row);
  42057. }
  42058. return result;
  42059. }
  42060. }
  42061. // TODO(matsko): document the signature in a better way
  42062. return function(element, event, options) {
  42063. options = prepareAnimationOptions(options);
  42064. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  42065. // there is no animation at the current moment, however
  42066. // these runner methods will get later updated with the
  42067. // methods leading into the driver's end/cancel methods
  42068. // for now they just stop the animation from starting
  42069. var runner = new $$AnimateRunner({
  42070. end: function() { close(); },
  42071. cancel: function() { close(true); }
  42072. });
  42073. if (!drivers.length) {
  42074. close();
  42075. return runner;
  42076. }
  42077. setRunner(element, runner);
  42078. var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
  42079. var tempClasses = options.tempClasses;
  42080. if (tempClasses) {
  42081. classes += ' ' + tempClasses;
  42082. options.tempClasses = null;
  42083. }
  42084. var prepareClassName;
  42085. if (isStructural) {
  42086. prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX;
  42087. $$jqLite.addClass(element, prepareClassName);
  42088. }
  42089. animationQueue.push({
  42090. // this data is used by the postDigest code and passed into
  42091. // the driver step function
  42092. element: element,
  42093. classes: classes,
  42094. event: event,
  42095. structural: isStructural,
  42096. options: options,
  42097. beforeStart: beforeStart,
  42098. close: close
  42099. });
  42100. element.on('$destroy', handleDestroyedElement);
  42101. // we only want there to be one function called within the post digest
  42102. // block. This way we can group animations for all the animations that
  42103. // were apart of the same postDigest flush call.
  42104. if (animationQueue.length > 1) return runner;
  42105. $rootScope.$$postDigest(function() {
  42106. var animations = [];
  42107. forEach(animationQueue, function(entry) {
  42108. // the element was destroyed early on which removed the runner
  42109. // form its storage. This means we can't animate this element
  42110. // at all and it already has been closed due to destruction.
  42111. if (getRunner(entry.element)) {
  42112. animations.push(entry);
  42113. } else {
  42114. entry.close();
  42115. }
  42116. });
  42117. // now any future animations will be in another postDigest
  42118. animationQueue.length = 0;
  42119. var groupedAnimations = groupAnimations(animations);
  42120. var toBeSortedAnimations = [];
  42121. forEach(groupedAnimations, function(animationEntry) {
  42122. toBeSortedAnimations.push({
  42123. domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
  42124. fn: function triggerAnimationStart() {
  42125. // it's important that we apply the `ng-animate` CSS class and the
  42126. // temporary classes before we do any driver invoking since these
  42127. // CSS classes may be required for proper CSS detection.
  42128. animationEntry.beforeStart();
  42129. var startAnimationFn, closeFn = animationEntry.close;
  42130. // in the event that the element was removed before the digest runs or
  42131. // during the RAF sequencing then we should not trigger the animation.
  42132. var targetElement = animationEntry.anchors
  42133. ? (animationEntry.from.element || animationEntry.to.element)
  42134. : animationEntry.element;
  42135. if (getRunner(targetElement)) {
  42136. var operation = invokeFirstDriver(animationEntry);
  42137. if (operation) {
  42138. startAnimationFn = operation.start;
  42139. }
  42140. }
  42141. if (!startAnimationFn) {
  42142. closeFn();
  42143. } else {
  42144. var animationRunner = startAnimationFn();
  42145. animationRunner.done(function(status) {
  42146. closeFn(!status);
  42147. });
  42148. updateAnimationRunners(animationEntry, animationRunner);
  42149. }
  42150. }
  42151. });
  42152. });
  42153. // we need to sort each of the animations in order of parent to child
  42154. // relationships. This ensures that the child classes are applied at the
  42155. // right time.
  42156. $$rAFScheduler(sortAnimations(toBeSortedAnimations));
  42157. });
  42158. return runner;
  42159. // TODO(matsko): change to reference nodes
  42160. function getAnchorNodes(node) {
  42161. var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
  42162. var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
  42163. ? [node]
  42164. : node.querySelectorAll(SELECTOR);
  42165. var anchors = [];
  42166. forEach(items, function(node) {
  42167. var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
  42168. if (attr && attr.length) {
  42169. anchors.push(node);
  42170. }
  42171. });
  42172. return anchors;
  42173. }
  42174. function groupAnimations(animations) {
  42175. var preparedAnimations = [];
  42176. var refLookup = {};
  42177. forEach(animations, function(animation, index) {
  42178. var element = animation.element;
  42179. var node = getDomNode(element);
  42180. var event = animation.event;
  42181. var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
  42182. var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
  42183. if (anchorNodes.length) {
  42184. var direction = enterOrMove ? 'to' : 'from';
  42185. forEach(anchorNodes, function(anchor) {
  42186. var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
  42187. refLookup[key] = refLookup[key] || {};
  42188. refLookup[key][direction] = {
  42189. animationID: index,
  42190. element: jqLite(anchor)
  42191. };
  42192. });
  42193. } else {
  42194. preparedAnimations.push(animation);
  42195. }
  42196. });
  42197. var usedIndicesLookup = {};
  42198. var anchorGroups = {};
  42199. forEach(refLookup, function(operations, key) {
  42200. var from = operations.from;
  42201. var to = operations.to;
  42202. if (!from || !to) {
  42203. // only one of these is set therefore we can't have an
  42204. // anchor animation since all three pieces are required
  42205. var index = from ? from.animationID : to.animationID;
  42206. var indexKey = index.toString();
  42207. if (!usedIndicesLookup[indexKey]) {
  42208. usedIndicesLookup[indexKey] = true;
  42209. preparedAnimations.push(animations[index]);
  42210. }
  42211. return;
  42212. }
  42213. var fromAnimation = animations[from.animationID];
  42214. var toAnimation = animations[to.animationID];
  42215. var lookupKey = from.animationID.toString();
  42216. if (!anchorGroups[lookupKey]) {
  42217. var group = anchorGroups[lookupKey] = {
  42218. structural: true,
  42219. beforeStart: function() {
  42220. fromAnimation.beforeStart();
  42221. toAnimation.beforeStart();
  42222. },
  42223. close: function() {
  42224. fromAnimation.close();
  42225. toAnimation.close();
  42226. },
  42227. classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
  42228. from: fromAnimation,
  42229. to: toAnimation,
  42230. anchors: [] // TODO(matsko): change to reference nodes
  42231. };
  42232. // the anchor animations require that the from and to elements both have at least
  42233. // one shared CSS class which effectively marries the two elements together to use
  42234. // the same animation driver and to properly sequence the anchor animation.
  42235. if (group.classes.length) {
  42236. preparedAnimations.push(group);
  42237. } else {
  42238. preparedAnimations.push(fromAnimation);
  42239. preparedAnimations.push(toAnimation);
  42240. }
  42241. }
  42242. anchorGroups[lookupKey].anchors.push({
  42243. 'out': from.element, 'in': to.element
  42244. });
  42245. });
  42246. return preparedAnimations;
  42247. }
  42248. function cssClassesIntersection(a,b) {
  42249. a = a.split(' ');
  42250. b = b.split(' ');
  42251. var matches = [];
  42252. for (var i = 0; i < a.length; i++) {
  42253. var aa = a[i];
  42254. if (aa.substring(0,3) === 'ng-') continue;
  42255. for (var j = 0; j < b.length; j++) {
  42256. if (aa === b[j]) {
  42257. matches.push(aa);
  42258. break;
  42259. }
  42260. }
  42261. }
  42262. return matches.join(' ');
  42263. }
  42264. function invokeFirstDriver(animationDetails) {
  42265. // we loop in reverse order since the more general drivers (like CSS and JS)
  42266. // may attempt more elements, but custom drivers are more particular
  42267. for (var i = drivers.length - 1; i >= 0; i--) {
  42268. var driverName = drivers[i];
  42269. if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
  42270. var factory = $injector.get(driverName);
  42271. var driver = factory(animationDetails);
  42272. if (driver) {
  42273. return driver;
  42274. }
  42275. }
  42276. }
  42277. function beforeStart() {
  42278. element.addClass(NG_ANIMATE_CLASSNAME);
  42279. if (tempClasses) {
  42280. $$jqLite.addClass(element, tempClasses);
  42281. }
  42282. if (prepareClassName) {
  42283. $$jqLite.removeClass(element, prepareClassName);
  42284. prepareClassName = null;
  42285. }
  42286. }
  42287. function updateAnimationRunners(animation, newRunner) {
  42288. if (animation.from && animation.to) {
  42289. update(animation.from.element);
  42290. update(animation.to.element);
  42291. } else {
  42292. update(animation.element);
  42293. }
  42294. function update(element) {
  42295. getRunner(element).setHost(newRunner);
  42296. }
  42297. }
  42298. function handleDestroyedElement() {
  42299. var runner = getRunner(element);
  42300. if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
  42301. runner.end();
  42302. }
  42303. }
  42304. function close(rejected) { // jshint ignore:line
  42305. element.off('$destroy', handleDestroyedElement);
  42306. removeRunner(element);
  42307. applyAnimationClasses(element, options);
  42308. applyAnimationStyles(element, options);
  42309. options.domOperation();
  42310. if (tempClasses) {
  42311. $$jqLite.removeClass(element, tempClasses);
  42312. }
  42313. element.removeClass(NG_ANIMATE_CLASSNAME);
  42314. runner.complete(!rejected);
  42315. }
  42316. };
  42317. }];
  42318. }];
  42319. /**
  42320. * @ngdoc directive
  42321. * @name ngAnimateSwap
  42322. * @restrict A
  42323. * @scope
  42324. *
  42325. * @description
  42326. *
  42327. * ngAnimateSwap is a animation-oriented directive that allows for the container to
  42328. * be removed and entered in whenever the associated expression changes. A
  42329. * common usecase for this directive is a rotating banner or slider component which
  42330. * contains one image being present at a time. When the active image changes
  42331. * then the old image will perform a `leave` animation and the new element
  42332. * will be inserted via an `enter` animation.
  42333. *
  42334. * @animations
  42335. * | Animation | Occurs |
  42336. * |----------------------------------|--------------------------------------|
  42337. * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
  42338. * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM |
  42339. *
  42340. * @example
  42341. * <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample"
  42342. * deps="angular-animate.js"
  42343. * animations="true" fixBase="true">
  42344. * <file name="index.html">
  42345. * <div class="container" ng-controller="AppCtrl">
  42346. * <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)">
  42347. * {{ number }}
  42348. * </div>
  42349. * </div>
  42350. * </file>
  42351. * <file name="script.js">
  42352. * angular.module('ngAnimateSwapExample', ['ngAnimate'])
  42353. * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
  42354. * $scope.number = 0;
  42355. * $interval(function() {
  42356. * $scope.number++;
  42357. * }, 1000);
  42358. *
  42359. * var colors = ['red','blue','green','yellow','orange'];
  42360. * $scope.colorClass = function(number) {
  42361. * return colors[number % colors.length];
  42362. * };
  42363. * }]);
  42364. * </file>
  42365. * <file name="animations.css">
  42366. * .container {
  42367. * height:250px;
  42368. * width:250px;
  42369. * position:relative;
  42370. * overflow:hidden;
  42371. * border:2px solid black;
  42372. * }
  42373. * .container .cell {
  42374. * font-size:150px;
  42375. * text-align:center;
  42376. * line-height:250px;
  42377. * position:absolute;
  42378. * top:0;
  42379. * left:0;
  42380. * right:0;
  42381. * border-bottom:2px solid black;
  42382. * }
  42383. * .swap-animation.ng-enter, .swap-animation.ng-leave {
  42384. * transition:0.5s linear all;
  42385. * }
  42386. * .swap-animation.ng-enter {
  42387. * top:-250px;
  42388. * }
  42389. * .swap-animation.ng-enter-active {
  42390. * top:0px;
  42391. * }
  42392. * .swap-animation.ng-leave {
  42393. * top:0px;
  42394. * }
  42395. * .swap-animation.ng-leave-active {
  42396. * top:250px;
  42397. * }
  42398. * .red { background:red; }
  42399. * .green { background:green; }
  42400. * .blue { background:blue; }
  42401. * .yellow { background:yellow; }
  42402. * .orange { background:orange; }
  42403. * </file>
  42404. * </example>
  42405. */
  42406. var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
  42407. return {
  42408. restrict: 'A',
  42409. transclude: 'element',
  42410. terminal: true,
  42411. priority: 600, // we use 600 here to ensure that the directive is caught before others
  42412. link: function(scope, $element, attrs, ctrl, $transclude) {
  42413. var previousElement, previousScope;
  42414. scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
  42415. if (previousElement) {
  42416. $animate.leave(previousElement);
  42417. }
  42418. if (previousScope) {
  42419. previousScope.$destroy();
  42420. previousScope = null;
  42421. }
  42422. if (value || value === 0) {
  42423. previousScope = scope.$new();
  42424. $transclude(previousScope, function(element) {
  42425. previousElement = element;
  42426. $animate.enter(element, null, $element);
  42427. });
  42428. }
  42429. });
  42430. }
  42431. };
  42432. }];
  42433. /* global angularAnimateModule: true,
  42434. ngAnimateSwapDirective,
  42435. $$AnimateAsyncRunFactory,
  42436. $$rAFSchedulerFactory,
  42437. $$AnimateChildrenDirective,
  42438. $$AnimateQueueProvider,
  42439. $$AnimationProvider,
  42440. $AnimateCssProvider,
  42441. $$AnimateCssDriverProvider,
  42442. $$AnimateJsProvider,
  42443. $$AnimateJsDriverProvider,
  42444. */
  42445. /**
  42446. * @ngdoc module
  42447. * @name ngAnimate
  42448. * @description
  42449. *
  42450. * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
  42451. * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
  42452. *
  42453. * <div doc-module-components="ngAnimate"></div>
  42454. *
  42455. * # Usage
  42456. * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based
  42457. * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
  42458. * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
  42459. * the HTML element that the animation will be triggered on.
  42460. *
  42461. * ## Directive Support
  42462. * The following directives are "animation aware":
  42463. *
  42464. * | Directive | Supported Animations |
  42465. * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
  42466. * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
  42467. * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
  42468. * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
  42469. * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
  42470. * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
  42471. * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
  42472. * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
  42473. * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
  42474. * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
  42475. * | {@link module:ngMessages#animations ngMessage} | enter and leave |
  42476. *
  42477. * (More information can be found by visiting each the documentation associated with each directive.)
  42478. *
  42479. * ## CSS-based Animations
  42480. *
  42481. * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML
  42482. * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
  42483. *
  42484. * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
  42485. *
  42486. * ```html
  42487. * <div ng-if="bool" class="fade">
  42488. * Fade me in out
  42489. * </div>
  42490. * <button ng-click="bool=true">Fade In!</button>
  42491. * <button ng-click="bool=false">Fade Out!</button>
  42492. * ```
  42493. *
  42494. * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
  42495. *
  42496. * ```css
  42497. * /&#42; The starting CSS styles for the enter animation &#42;/
  42498. * .fade.ng-enter {
  42499. * transition:0.5s linear all;
  42500. * opacity:0;
  42501. * }
  42502. *
  42503. * /&#42; The finishing CSS styles for the enter animation &#42;/
  42504. * .fade.ng-enter.ng-enter-active {
  42505. * opacity:1;
  42506. * }
  42507. * ```
  42508. *
  42509. * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two
  42510. * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition
  42511. * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
  42512. *
  42513. * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:
  42514. *
  42515. * ```css
  42516. * /&#42; now the element will fade out before it is removed from the DOM &#42;/
  42517. * .fade.ng-leave {
  42518. * transition:0.5s linear all;
  42519. * opacity:1;
  42520. * }
  42521. * .fade.ng-leave.ng-leave-active {
  42522. * opacity:0;
  42523. * }
  42524. * ```
  42525. *
  42526. * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
  42527. *
  42528. * ```css
  42529. * /&#42; there is no need to define anything inside of the destination
  42530. * CSS class since the keyframe will take charge of the animation &#42;/
  42531. * .fade.ng-leave {
  42532. * animation: my_fade_animation 0.5s linear;
  42533. * -webkit-animation: my_fade_animation 0.5s linear;
  42534. * }
  42535. *
  42536. * @keyframes my_fade_animation {
  42537. * from { opacity:1; }
  42538. * to { opacity:0; }
  42539. * }
  42540. *
  42541. * @-webkit-keyframes my_fade_animation {
  42542. * from { opacity:1; }
  42543. * to { opacity:0; }
  42544. * }
  42545. * ```
  42546. *
  42547. * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
  42548. *
  42549. * ### CSS Class-based Animations
  42550. *
  42551. * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
  42552. * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
  42553. * and removed.
  42554. *
  42555. * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
  42556. *
  42557. * ```html
  42558. * <div ng-show="bool" class="fade">
  42559. * Show and hide me
  42560. * </div>
  42561. * <button ng-click="bool=true">Toggle</button>
  42562. *
  42563. * <style>
  42564. * .fade.ng-hide {
  42565. * transition:0.5s linear all;
  42566. * opacity:0;
  42567. * }
  42568. * </style>
  42569. * ```
  42570. *
  42571. * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since
  42572. * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
  42573. *
  42574. * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation
  42575. * with CSS styles.
  42576. *
  42577. * ```html
  42578. * <div ng-class="{on:onOff}" class="highlight">
  42579. * Highlight this box
  42580. * </div>
  42581. * <button ng-click="onOff=!onOff">Toggle</button>
  42582. *
  42583. * <style>
  42584. * .highlight {
  42585. * transition:0.5s linear all;
  42586. * }
  42587. * .highlight.on-add {
  42588. * background:white;
  42589. * }
  42590. * .highlight.on {
  42591. * background:yellow;
  42592. * }
  42593. * .highlight.on-remove {
  42594. * background:black;
  42595. * }
  42596. * </style>
  42597. * ```
  42598. *
  42599. * We can also make use of CSS keyframes by placing them within the CSS classes.
  42600. *
  42601. *
  42602. * ### CSS Staggering Animations
  42603. * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
  42604. * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
  42605. * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
  42606. * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
  42607. * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
  42608. *
  42609. * ```css
  42610. * .my-animation.ng-enter {
  42611. * /&#42; standard transition code &#42;/
  42612. * transition: 1s linear all;
  42613. * opacity:0;
  42614. * }
  42615. * .my-animation.ng-enter-stagger {
  42616. * /&#42; this will have a 100ms delay between each successive leave animation &#42;/
  42617. * transition-delay: 0.1s;
  42618. *
  42619. * /&#42; As of 1.4.4, this must always be set: it signals ngAnimate
  42620. * to not accidentally inherit a delay property from another CSS class &#42;/
  42621. * transition-duration: 0s;
  42622. * }
  42623. * .my-animation.ng-enter.ng-enter-active {
  42624. * /&#42; standard transition styles &#42;/
  42625. * opacity:1;
  42626. * }
  42627. * ```
  42628. *
  42629. * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
  42630. * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
  42631. * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
  42632. * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
  42633. *
  42634. * The following code will issue the **ng-leave-stagger** event on the element provided:
  42635. *
  42636. * ```js
  42637. * var kids = parent.children();
  42638. *
  42639. * $animate.leave(kids[0]); //stagger index=0
  42640. * $animate.leave(kids[1]); //stagger index=1
  42641. * $animate.leave(kids[2]); //stagger index=2
  42642. * $animate.leave(kids[3]); //stagger index=3
  42643. * $animate.leave(kids[4]); //stagger index=4
  42644. *
  42645. * window.requestAnimationFrame(function() {
  42646. * //stagger has reset itself
  42647. * $animate.leave(kids[5]); //stagger index=0
  42648. * $animate.leave(kids[6]); //stagger index=1
  42649. *
  42650. * $scope.$digest();
  42651. * });
  42652. * ```
  42653. *
  42654. * Stagger animations are currently only supported within CSS-defined animations.
  42655. *
  42656. * ### The `ng-animate` CSS class
  42657. *
  42658. * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
  42659. * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
  42660. *
  42661. * Therefore, animations can be applied to an element using this temporary class directly via CSS.
  42662. *
  42663. * ```css
  42664. * .zipper.ng-animate {
  42665. * transition:0.5s linear all;
  42666. * }
  42667. * .zipper.ng-enter {
  42668. * opacity:0;
  42669. * }
  42670. * .zipper.ng-enter.ng-enter-active {
  42671. * opacity:1;
  42672. * }
  42673. * .zipper.ng-leave {
  42674. * opacity:1;
  42675. * }
  42676. * .zipper.ng-leave.ng-leave-active {
  42677. * opacity:0;
  42678. * }
  42679. * ```
  42680. *
  42681. * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
  42682. * the CSS class once an animation has completed.)
  42683. *
  42684. *
  42685. * ### The `ng-[event]-prepare` class
  42686. *
  42687. * This is a special class that can be used to prevent unwanted flickering / flash of content before
  42688. * the actual animation starts. The class is added as soon as an animation is initialized, but removed
  42689. * before the actual animation starts (after waiting for a $digest).
  42690. * It is also only added for *structural* animations (`enter`, `move`, and `leave`).
  42691. *
  42692. * In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
  42693. * into elements that have class-based animations such as `ngClass`.
  42694. *
  42695. * ```html
  42696. * <div ng-class="{red: myProp}">
  42697. * <div ng-class="{blue: myProp}">
  42698. * <div class="message" ng-if="myProp"></div>
  42699. * </div>
  42700. * </div>
  42701. * ```
  42702. *
  42703. * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
  42704. * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
  42705. *
  42706. * ```css
  42707. * .message.ng-enter-prepare {
  42708. * opacity: 0;
  42709. * }
  42710. *
  42711. * ```
  42712. *
  42713. * ## JavaScript-based Animations
  42714. *
  42715. * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
  42716. * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the
  42717. * `module.animation()` module function we can register the animation.
  42718. *
  42719. * Let's see an example of a enter/leave animation using `ngRepeat`:
  42720. *
  42721. * ```html
  42722. * <div ng-repeat="item in items" class="slide">
  42723. * {{ item }}
  42724. * </div>
  42725. * ```
  42726. *
  42727. * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:
  42728. *
  42729. * ```js
  42730. * myModule.animation('.slide', [function() {
  42731. * return {
  42732. * // make note that other events (like addClass/removeClass)
  42733. * // have different function input parameters
  42734. * enter: function(element, doneFn) {
  42735. * jQuery(element).fadeIn(1000, doneFn);
  42736. *
  42737. * // remember to call doneFn so that angular
  42738. * // knows that the animation has concluded
  42739. * },
  42740. *
  42741. * move: function(element, doneFn) {
  42742. * jQuery(element).fadeIn(1000, doneFn);
  42743. * },
  42744. *
  42745. * leave: function(element, doneFn) {
  42746. * jQuery(element).fadeOut(1000, doneFn);
  42747. * }
  42748. * }
  42749. * }]);
  42750. * ```
  42751. *
  42752. * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
  42753. * greensock.js and velocity.js.
  42754. *
  42755. * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
  42756. * our animations inside of the same registered animation, however, the function input arguments are a bit different:
  42757. *
  42758. * ```html
  42759. * <div ng-class="color" class="colorful">
  42760. * this box is moody
  42761. * </div>
  42762. * <button ng-click="color='red'">Change to red</button>
  42763. * <button ng-click="color='blue'">Change to blue</button>
  42764. * <button ng-click="color='green'">Change to green</button>
  42765. * ```
  42766. *
  42767. * ```js
  42768. * myModule.animation('.colorful', [function() {
  42769. * return {
  42770. * addClass: function(element, className, doneFn) {
  42771. * // do some cool animation and call the doneFn
  42772. * },
  42773. * removeClass: function(element, className, doneFn) {
  42774. * // do some cool animation and call the doneFn
  42775. * },
  42776. * setClass: function(element, addedClass, removedClass, doneFn) {
  42777. * // do some cool animation and call the doneFn
  42778. * }
  42779. * }
  42780. * }]);
  42781. * ```
  42782. *
  42783. * ## CSS + JS Animations Together
  42784. *
  42785. * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,
  42786. * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking
  42787. * charge of the animation**:
  42788. *
  42789. * ```html
  42790. * <div ng-if="bool" class="slide">
  42791. * Slide in and out
  42792. * </div>
  42793. * ```
  42794. *
  42795. * ```js
  42796. * myModule.animation('.slide', [function() {
  42797. * return {
  42798. * enter: function(element, doneFn) {
  42799. * jQuery(element).slideIn(1000, doneFn);
  42800. * }
  42801. * }
  42802. * }]);
  42803. * ```
  42804. *
  42805. * ```css
  42806. * .slide.ng-enter {
  42807. * transition:0.5s linear all;
  42808. * transform:translateY(-100px);
  42809. * }
  42810. * .slide.ng-enter.ng-enter-active {
  42811. * transform:translateY(0);
  42812. * }
  42813. * ```
  42814. *
  42815. * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the
  42816. * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
  42817. * our own JS-based animation code:
  42818. *
  42819. * ```js
  42820. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  42821. * return {
  42822. * enter: function(element) {
  42823. * // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
  42824. * return $animateCss(element, {
  42825. * event: 'enter',
  42826. * structural: true
  42827. * });
  42828. * }
  42829. * }
  42830. * }]);
  42831. * ```
  42832. *
  42833. * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.
  42834. *
  42835. * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or
  42836. * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that
  42837. * data into `$animateCss` directly:
  42838. *
  42839. * ```js
  42840. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  42841. * return {
  42842. * enter: function(element) {
  42843. * return $animateCss(element, {
  42844. * event: 'enter',
  42845. * structural: true,
  42846. * addClass: 'maroon-setting',
  42847. * from: { height:0 },
  42848. * to: { height: 200 }
  42849. * });
  42850. * }
  42851. * }
  42852. * }]);
  42853. * ```
  42854. *
  42855. * Now we can fill in the rest via our transition CSS code:
  42856. *
  42857. * ```css
  42858. * /&#42; the transition tells ngAnimate to make the animation happen &#42;/
  42859. * .slide.ng-enter { transition:0.5s linear all; }
  42860. *
  42861. * /&#42; this extra CSS class will be absorbed into the transition
  42862. * since the $animateCss code is adding the class &#42;/
  42863. * .maroon-setting { background:red; }
  42864. * ```
  42865. *
  42866. * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.
  42867. *
  42868. * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
  42869. *
  42870. * ## Animation Anchoring (via `ng-animate-ref`)
  42871. *
  42872. * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
  42873. * structural areas of an application (like views) by pairing up elements using an attribute
  42874. * called `ng-animate-ref`.
  42875. *
  42876. * Let's say for example we have two views that are managed by `ng-view` and we want to show
  42877. * that there is a relationship between two components situated in within these views. By using the
  42878. * `ng-animate-ref` attribute we can identify that the two components are paired together and we
  42879. * can then attach an animation, which is triggered when the view changes.
  42880. *
  42881. * Say for example we have the following template code:
  42882. *
  42883. * ```html
  42884. * <!-- index.html -->
  42885. * <div ng-view class="view-animation">
  42886. * </div>
  42887. *
  42888. * <!-- home.html -->
  42889. * <a href="#/banner-page">
  42890. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  42891. * </a>
  42892. *
  42893. * <!-- banner-page.html -->
  42894. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  42895. * ```
  42896. *
  42897. * Now, when the view changes (once the link is clicked), ngAnimate will examine the
  42898. * HTML contents to see if there is a match reference between any components in the view
  42899. * that is leaving and the view that is entering. It will scan both the view which is being
  42900. * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
  42901. * contain a matching ref value.
  42902. *
  42903. * The two images match since they share the same ref value. ngAnimate will now create a
  42904. * transport element (which is a clone of the first image element) and it will then attempt
  42905. * to animate to the position of the second image element in the next view. For the animation to
  42906. * work a special CSS class called `ng-anchor` will be added to the transported element.
  42907. *
  42908. * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
  42909. * ngAnimate will handle the entire transition for us as well as the addition and removal of
  42910. * any changes of CSS classes between the elements:
  42911. *
  42912. * ```css
  42913. * .banner.ng-anchor {
  42914. * /&#42; this animation will last for 1 second since there are
  42915. * two phases to the animation (an `in` and an `out` phase) &#42;/
  42916. * transition:0.5s linear all;
  42917. * }
  42918. * ```
  42919. *
  42920. * We also **must** include animations for the views that are being entered and removed
  42921. * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
  42922. *
  42923. * ```css
  42924. * .view-animation.ng-enter, .view-animation.ng-leave {
  42925. * transition:0.5s linear all;
  42926. * position:fixed;
  42927. * left:0;
  42928. * top:0;
  42929. * width:100%;
  42930. * }
  42931. * .view-animation.ng-enter {
  42932. * transform:translateX(100%);
  42933. * }
  42934. * .view-animation.ng-leave,
  42935. * .view-animation.ng-enter.ng-enter-active {
  42936. * transform:translateX(0%);
  42937. * }
  42938. * .view-animation.ng-leave.ng-leave-active {
  42939. * transform:translateX(-100%);
  42940. * }
  42941. * ```
  42942. *
  42943. * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
  42944. * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
  42945. * from its origin. Once that animation is over then the `in` stage occurs which animates the
  42946. * element to its destination. The reason why there are two animations is to give enough time
  42947. * for the enter animation on the new element to be ready.
  42948. *
  42949. * The example above sets up a transition for both the in and out phases, but we can also target the out or
  42950. * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
  42951. *
  42952. * ```css
  42953. * .banner.ng-anchor-out {
  42954. * transition: 0.5s linear all;
  42955. *
  42956. * /&#42; the scale will be applied during the out animation,
  42957. * but will be animated away when the in animation runs &#42;/
  42958. * transform: scale(1.2);
  42959. * }
  42960. *
  42961. * .banner.ng-anchor-in {
  42962. * transition: 1s linear all;
  42963. * }
  42964. * ```
  42965. *
  42966. *
  42967. *
  42968. *
  42969. * ### Anchoring Demo
  42970. *
  42971. <example module="anchoringExample"
  42972. name="anchoringExample"
  42973. id="anchoringExample"
  42974. deps="angular-animate.js;angular-route.js"
  42975. animations="true">
  42976. <file name="index.html">
  42977. <a href="#/">Home</a>
  42978. <hr />
  42979. <div class="view-container">
  42980. <div ng-view class="view"></div>
  42981. </div>
  42982. </file>
  42983. <file name="script.js">
  42984. angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
  42985. .config(['$routeProvider', function($routeProvider) {
  42986. $routeProvider.when('/', {
  42987. templateUrl: 'home.html',
  42988. controller: 'HomeController as home'
  42989. });
  42990. $routeProvider.when('/profile/:id', {
  42991. templateUrl: 'profile.html',
  42992. controller: 'ProfileController as profile'
  42993. });
  42994. }])
  42995. .run(['$rootScope', function($rootScope) {
  42996. $rootScope.records = [
  42997. { id:1, title: "Miss Beulah Roob" },
  42998. { id:2, title: "Trent Morissette" },
  42999. { id:3, title: "Miss Ava Pouros" },
  43000. { id:4, title: "Rod Pouros" },
  43001. { id:5, title: "Abdul Rice" },
  43002. { id:6, title: "Laurie Rutherford Sr." },
  43003. { id:7, title: "Nakia McLaughlin" },
  43004. { id:8, title: "Jordon Blanda DVM" },
  43005. { id:9, title: "Rhoda Hand" },
  43006. { id:10, title: "Alexandrea Sauer" }
  43007. ];
  43008. }])
  43009. .controller('HomeController', [function() {
  43010. //empty
  43011. }])
  43012. .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
  43013. var index = parseInt($routeParams.id, 10);
  43014. var record = $rootScope.records[index - 1];
  43015. this.title = record.title;
  43016. this.id = record.id;
  43017. }]);
  43018. </file>
  43019. <file name="home.html">
  43020. <h2>Welcome to the home page</h1>
  43021. <p>Please click on an element</p>
  43022. <a class="record"
  43023. ng-href="#/profile/{{ record.id }}"
  43024. ng-animate-ref="{{ record.id }}"
  43025. ng-repeat="record in records">
  43026. {{ record.title }}
  43027. </a>
  43028. </file>
  43029. <file name="profile.html">
  43030. <div class="profile record" ng-animate-ref="{{ profile.id }}">
  43031. {{ profile.title }}
  43032. </div>
  43033. </file>
  43034. <file name="animations.css">
  43035. .record {
  43036. display:block;
  43037. font-size:20px;
  43038. }
  43039. .profile {
  43040. background:black;
  43041. color:white;
  43042. font-size:100px;
  43043. }
  43044. .view-container {
  43045. position:relative;
  43046. }
  43047. .view-container > .view.ng-animate {
  43048. position:absolute;
  43049. top:0;
  43050. left:0;
  43051. width:100%;
  43052. min-height:500px;
  43053. }
  43054. .view.ng-enter, .view.ng-leave,
  43055. .record.ng-anchor {
  43056. transition:0.5s linear all;
  43057. }
  43058. .view.ng-enter {
  43059. transform:translateX(100%);
  43060. }
  43061. .view.ng-enter.ng-enter-active, .view.ng-leave {
  43062. transform:translateX(0%);
  43063. }
  43064. .view.ng-leave.ng-leave-active {
  43065. transform:translateX(-100%);
  43066. }
  43067. .record.ng-anchor-out {
  43068. background:red;
  43069. }
  43070. </file>
  43071. </example>
  43072. *
  43073. * ### How is the element transported?
  43074. *
  43075. * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
  43076. * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
  43077. * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
  43078. * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
  43079. * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
  43080. * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
  43081. * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
  43082. * will become visible since the shim class will be removed.
  43083. *
  43084. * ### How is the morphing handled?
  43085. *
  43086. * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
  43087. * what CSS classes differ between the starting element and the destination element. These different CSS classes
  43088. * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
  43089. * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
  43090. * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
  43091. * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
  43092. * the cloned element is placed inside of root element which is likely close to the body element).
  43093. *
  43094. * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
  43095. *
  43096. *
  43097. * ## Using $animate in your directive code
  43098. *
  43099. * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?
  43100. * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's
  43101. * imagine we have a greeting box that shows and hides itself when the data changes
  43102. *
  43103. * ```html
  43104. * <greeting-box active="onOrOff">Hi there</greeting-box>
  43105. * ```
  43106. *
  43107. * ```js
  43108. * ngModule.directive('greetingBox', ['$animate', function($animate) {
  43109. * return function(scope, element, attrs) {
  43110. * attrs.$observe('active', function(value) {
  43111. * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
  43112. * });
  43113. * });
  43114. * }]);
  43115. * ```
  43116. *
  43117. * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element
  43118. * in our HTML code then we can trigger a CSS or JS animation to happen.
  43119. *
  43120. * ```css
  43121. * /&#42; normally we would create a CSS class to reference on the element &#42;/
  43122. * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
  43123. * ```
  43124. *
  43125. * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
  43126. * possible be sure to visit the {@link ng.$animate $animate service API page}.
  43127. *
  43128. *
  43129. * ## Callbacks and Promises
  43130. *
  43131. * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger
  43132. * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
  43133. * ended by chaining onto the returned promise that animation method returns.
  43134. *
  43135. * ```js
  43136. * // somewhere within the depths of the directive
  43137. * $animate.enter(element, parent).then(function() {
  43138. * //the animation has completed
  43139. * });
  43140. * ```
  43141. *
  43142. * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case
  43143. * anymore.)
  43144. *
  43145. * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
  43146. * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
  43147. * routing controller to hook into that:
  43148. *
  43149. * ```js
  43150. * ngModule.controller('HomePageController', ['$animate', function($animate) {
  43151. * $animate.on('enter', ngViewElement, function(element) {
  43152. * // the animation for this route has completed
  43153. * }]);
  43154. * }])
  43155. * ```
  43156. *
  43157. * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
  43158. */
  43159. /**
  43160. * @ngdoc service
  43161. * @name $animate
  43162. * @kind object
  43163. *
  43164. * @description
  43165. * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
  43166. *
  43167. * Click here {@link ng.$animate to learn more about animations with `$animate`}.
  43168. */
  43169. angular.module('ngAnimate', [])
  43170. .directive('ngAnimateSwap', ngAnimateSwapDirective)
  43171. .directive('ngAnimateChildren', $$AnimateChildrenDirective)
  43172. .factory('$$rAFScheduler', $$rAFSchedulerFactory)
  43173. .provider('$$animateQueue', $$AnimateQueueProvider)
  43174. .provider('$$animation', $$AnimationProvider)
  43175. .provider('$animateCss', $AnimateCssProvider)
  43176. .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
  43177. .provider('$$animateJs', $$AnimateJsProvider)
  43178. .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
  43179. })(window, window.angular);
  43180. /*!
  43181. * ionic.bundle.js is a concatenation of:
  43182. * ionic.js, angular.js, angular-animate.js,
  43183. * angular-sanitize.js, angular-ui-router.js,
  43184. * and ionic-angular.js
  43185. */
  43186. /**
  43187. * @license AngularJS v1.5.3
  43188. * (c) 2010-2016 Google, Inc. http://angularjs.org
  43189. * License: MIT
  43190. */
  43191. (function(window, angular, undefined) {'use strict';
  43192. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  43193. * Any commits to this file should be reviewed with security in mind. *
  43194. * Changes to this file can potentially create security vulnerabilities. *
  43195. * An approval from 2 Core members with history of modifying *
  43196. * this file is required. *
  43197. * *
  43198. * Does the change somehow allow for arbitrary javascript to be executed? *
  43199. * Or allows for someone to change the prototype of built-in objects? *
  43200. * Or gives undesired access to variables likes document or window? *
  43201. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  43202. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  43203. /**
  43204. * @ngdoc module
  43205. * @name ngSanitize
  43206. * @description
  43207. *
  43208. * # ngSanitize
  43209. *
  43210. * The `ngSanitize` module provides functionality to sanitize HTML.
  43211. *
  43212. *
  43213. * <div doc-module-components="ngSanitize"></div>
  43214. *
  43215. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  43216. */
  43217. /**
  43218. * @ngdoc service
  43219. * @name $sanitize
  43220. * @kind function
  43221. *
  43222. * @description
  43223. * Sanitizes an html string by stripping all potentially dangerous tokens.
  43224. *
  43225. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  43226. * then serialized back to properly escaped html string. This means that no unsafe input can make
  43227. * it into the returned string.
  43228. *
  43229. * The whitelist for URL sanitization of attribute values is configured using the functions
  43230. * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
  43231. * `$compileProvider`}.
  43232. *
  43233. * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
  43234. *
  43235. * @param {string} html HTML input.
  43236. * @returns {string} Sanitized HTML.
  43237. *
  43238. * @example
  43239. <example module="sanitizeExample" deps="angular-sanitize.js">
  43240. <file name="index.html">
  43241. <script>
  43242. angular.module('sanitizeExample', ['ngSanitize'])
  43243. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  43244. $scope.snippet =
  43245. '<p style="color:blue">an html\n' +
  43246. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  43247. 'snippet</p>';
  43248. $scope.deliberatelyTrustDangerousSnippet = function() {
  43249. return $sce.trustAsHtml($scope.snippet);
  43250. };
  43251. }]);
  43252. </script>
  43253. <div ng-controller="ExampleController">
  43254. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  43255. <table>
  43256. <tr>
  43257. <td>Directive</td>
  43258. <td>How</td>
  43259. <td>Source</td>
  43260. <td>Rendered</td>
  43261. </tr>
  43262. <tr id="bind-html-with-sanitize">
  43263. <td>ng-bind-html</td>
  43264. <td>Automatically uses $sanitize</td>
  43265. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  43266. <td><div ng-bind-html="snippet"></div></td>
  43267. </tr>
  43268. <tr id="bind-html-with-trust">
  43269. <td>ng-bind-html</td>
  43270. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  43271. <td>
  43272. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  43273. &lt;/div&gt;</pre>
  43274. </td>
  43275. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  43276. </tr>
  43277. <tr id="bind-default">
  43278. <td>ng-bind</td>
  43279. <td>Automatically escapes</td>
  43280. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  43281. <td><div ng-bind="snippet"></div></td>
  43282. </tr>
  43283. </table>
  43284. </div>
  43285. </file>
  43286. <file name="protractor.js" type="protractor">
  43287. it('should sanitize the html snippet by default', function() {
  43288. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  43289. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  43290. });
  43291. it('should inline raw snippet if bound to a trusted value', function() {
  43292. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  43293. toBe("<p style=\"color:blue\">an html\n" +
  43294. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  43295. "snippet</p>");
  43296. });
  43297. it('should escape snippet without any filter', function() {
  43298. expect(element(by.css('#bind-default div')).getInnerHtml()).
  43299. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  43300. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  43301. "snippet&lt;/p&gt;");
  43302. });
  43303. it('should update', function() {
  43304. element(by.model('snippet')).clear();
  43305. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  43306. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  43307. toBe('new <b>text</b>');
  43308. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  43309. 'new <b onclick="alert(1)">text</b>');
  43310. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  43311. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  43312. });
  43313. </file>
  43314. </example>
  43315. */
  43316. /**
  43317. * @ngdoc provider
  43318. * @name $sanitizeProvider
  43319. *
  43320. * @description
  43321. * Creates and configures {@link $sanitize} instance.
  43322. */
  43323. function $SanitizeProvider() {
  43324. var svgEnabled = false;
  43325. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  43326. if (svgEnabled) {
  43327. angular.extend(validElements, svgElements);
  43328. }
  43329. return function(html) {
  43330. var buf = [];
  43331. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  43332. return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
  43333. }));
  43334. return buf.join('');
  43335. };
  43336. }];
  43337. /**
  43338. * @ngdoc method
  43339. * @name $sanitizeProvider#enableSvg
  43340. * @kind function
  43341. *
  43342. * @description
  43343. * Enables a subset of svg to be supported by the sanitizer.
  43344. *
  43345. * <div class="alert alert-warning">
  43346. * <p>By enabling this setting without taking other precautions, you might expose your
  43347. * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
  43348. * outside of the containing element and be rendered over other elements on the page (e.g. a login
  43349. * link). Such behavior can then result in phishing incidents.</p>
  43350. *
  43351. * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
  43352. * tags within the sanitized content:</p>
  43353. *
  43354. * <br>
  43355. *
  43356. * <pre><code>
  43357. * .rootOfTheIncludedContent svg {
  43358. * overflow: hidden !important;
  43359. * }
  43360. * </code></pre>
  43361. * </div>
  43362. *
  43363. * @param {boolean=} regexp New regexp to whitelist urls with.
  43364. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
  43365. * without an argument or self for chaining otherwise.
  43366. */
  43367. this.enableSvg = function(enableSvg) {
  43368. if (angular.isDefined(enableSvg)) {
  43369. svgEnabled = enableSvg;
  43370. return this;
  43371. } else {
  43372. return svgEnabled;
  43373. }
  43374. };
  43375. }
  43376. function sanitizeText(chars) {
  43377. var buf = [];
  43378. var writer = htmlSanitizeWriter(buf, angular.noop);
  43379. writer.chars(chars);
  43380. return buf.join('');
  43381. }
  43382. // Regular Expressions for parsing tags and attributes
  43383. var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  43384. // Match everything outside of normal chars and " (quote character)
  43385. NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
  43386. // Good source of info about elements and attributes
  43387. // http://dev.w3.org/html5/spec/Overview.html#semantics
  43388. // http://simon.html5.org/html-elements
  43389. // Safe Void Elements - HTML5
  43390. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  43391. var voidElements = toMap("area,br,col,hr,img,wbr");
  43392. // Elements that you can, intentionally, leave open (and which close themselves)
  43393. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  43394. var optionalEndTagBlockElements = toMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  43395. optionalEndTagInlineElements = toMap("rp,rt"),
  43396. optionalEndTagElements = angular.extend({},
  43397. optionalEndTagInlineElements,
  43398. optionalEndTagBlockElements);
  43399. // Safe Block Elements - HTML5
  43400. var blockElements = angular.extend({}, optionalEndTagBlockElements, toMap("address,article," +
  43401. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  43402. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul"));
  43403. // Inline Elements - HTML5
  43404. var inlineElements = angular.extend({}, optionalEndTagInlineElements, toMap("a,abbr,acronym,b," +
  43405. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  43406. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  43407. // SVG Elements
  43408. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  43409. // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
  43410. // They can potentially allow for arbitrary javascript to be executed. See #11290
  43411. var svgElements = toMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," +
  43412. "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," +
  43413. "radialGradient,rect,stop,svg,switch,text,title,tspan");
  43414. // Blocked Elements (will be stripped)
  43415. var blockedElements = toMap("script,style");
  43416. var validElements = angular.extend({},
  43417. voidElements,
  43418. blockElements,
  43419. inlineElements,
  43420. optionalEndTagElements);
  43421. //Attributes that have href and hence need to be sanitized
  43422. var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href");
  43423. var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  43424. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  43425. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  43426. 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
  43427. 'valign,value,vspace,width');
  43428. // SVG attributes (without "id" and "name" attributes)
  43429. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  43430. var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  43431. 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
  43432. 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
  43433. 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
  43434. 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
  43435. 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
  43436. 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
  43437. 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
  43438. 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
  43439. 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
  43440. 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
  43441. 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
  43442. 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
  43443. 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
  43444. 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
  43445. var validAttrs = angular.extend({},
  43446. uriAttrs,
  43447. svgAttrs,
  43448. htmlAttrs);
  43449. function toMap(str, lowercaseKeys) {
  43450. var obj = {}, items = str.split(','), i;
  43451. for (i = 0; i < items.length; i++) {
  43452. obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true;
  43453. }
  43454. return obj;
  43455. }
  43456. var inertBodyElement;
  43457. (function(window) {
  43458. var doc;
  43459. if (window.document && window.document.implementation) {
  43460. doc = window.document.implementation.createHTMLDocument("inert");
  43461. } else {
  43462. throw $sanitizeMinErr('noinert', "Can't create an inert html document");
  43463. }
  43464. var docElement = doc.documentElement || doc.getDocumentElement();
  43465. var bodyElements = docElement.getElementsByTagName('body');
  43466. // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
  43467. if (bodyElements.length === 1) {
  43468. inertBodyElement = bodyElements[0];
  43469. } else {
  43470. var html = doc.createElement('html');
  43471. inertBodyElement = doc.createElement('body');
  43472. html.appendChild(inertBodyElement);
  43473. doc.appendChild(html);
  43474. }
  43475. })(window);
  43476. /**
  43477. * @example
  43478. * htmlParser(htmlString, {
  43479. * start: function(tag, attrs) {},
  43480. * end: function(tag) {},
  43481. * chars: function(text) {},
  43482. * comment: function(text) {}
  43483. * });
  43484. *
  43485. * @param {string} html string
  43486. * @param {object} handler
  43487. */
  43488. function htmlParser(html, handler) {
  43489. if (html === null || html === undefined) {
  43490. html = '';
  43491. } else if (typeof html !== 'string') {
  43492. html = '' + html;
  43493. }
  43494. inertBodyElement.innerHTML = html;
  43495. //mXSS protection
  43496. var mXSSAttempts = 5;
  43497. do {
  43498. if (mXSSAttempts === 0) {
  43499. throw $sanitizeMinErr('uinput', "Failed to sanitize html because the input is unstable");
  43500. }
  43501. mXSSAttempts--;
  43502. // strip custom-namespaced attributes on IE<=11
  43503. if (document.documentMode <= 11) {
  43504. stripCustomNsAttrs(inertBodyElement);
  43505. }
  43506. html = inertBodyElement.innerHTML; //trigger mXSS
  43507. inertBodyElement.innerHTML = html;
  43508. } while (html !== inertBodyElement.innerHTML);
  43509. var node = inertBodyElement.firstChild;
  43510. while (node) {
  43511. switch (node.nodeType) {
  43512. case 1: // ELEMENT_NODE
  43513. handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
  43514. break;
  43515. case 3: // TEXT NODE
  43516. handler.chars(node.textContent);
  43517. break;
  43518. }
  43519. var nextNode;
  43520. if (!(nextNode = node.firstChild)) {
  43521. if (node.nodeType == 1) {
  43522. handler.end(node.nodeName.toLowerCase());
  43523. }
  43524. nextNode = node.nextSibling;
  43525. if (!nextNode) {
  43526. while (nextNode == null) {
  43527. node = node.parentNode;
  43528. if (node === inertBodyElement) break;
  43529. nextNode = node.nextSibling;
  43530. if (node.nodeType == 1) {
  43531. handler.end(node.nodeName.toLowerCase());
  43532. }
  43533. }
  43534. }
  43535. }
  43536. node = nextNode;
  43537. }
  43538. while (node = inertBodyElement.firstChild) {
  43539. inertBodyElement.removeChild(node);
  43540. }
  43541. }
  43542. function attrToMap(attrs) {
  43543. var map = {};
  43544. for (var i = 0, ii = attrs.length; i < ii; i++) {
  43545. var attr = attrs[i];
  43546. map[attr.name] = attr.value;
  43547. }
  43548. return map;
  43549. }
  43550. /**
  43551. * Escapes all potentially dangerous characters, so that the
  43552. * resulting string can be safely inserted into attribute or
  43553. * element text.
  43554. * @param value
  43555. * @returns {string} escaped text
  43556. */
  43557. function encodeEntities(value) {
  43558. return value.
  43559. replace(/&/g, '&amp;').
  43560. replace(SURROGATE_PAIR_REGEXP, function(value) {
  43561. var hi = value.charCodeAt(0);
  43562. var low = value.charCodeAt(1);
  43563. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  43564. }).
  43565. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  43566. return '&#' + value.charCodeAt(0) + ';';
  43567. }).
  43568. replace(/</g, '&lt;').
  43569. replace(/>/g, '&gt;');
  43570. }
  43571. /**
  43572. * create an HTML/XML writer which writes to buffer
  43573. * @param {Array} buf use buf.join('') to get out sanitized html string
  43574. * @returns {object} in the form of {
  43575. * start: function(tag, attrs) {},
  43576. * end: function(tag) {},
  43577. * chars: function(text) {},
  43578. * comment: function(text) {}
  43579. * }
  43580. */
  43581. function htmlSanitizeWriter(buf, uriValidator) {
  43582. var ignoreCurrentElement = false;
  43583. var out = angular.bind(buf, buf.push);
  43584. return {
  43585. start: function(tag, attrs) {
  43586. tag = angular.lowercase(tag);
  43587. if (!ignoreCurrentElement && blockedElements[tag]) {
  43588. ignoreCurrentElement = tag;
  43589. }
  43590. if (!ignoreCurrentElement && validElements[tag] === true) {
  43591. out('<');
  43592. out(tag);
  43593. angular.forEach(attrs, function(value, key) {
  43594. var lkey=angular.lowercase(key);
  43595. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  43596. if (validAttrs[lkey] === true &&
  43597. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  43598. out(' ');
  43599. out(key);
  43600. out('="');
  43601. out(encodeEntities(value));
  43602. out('"');
  43603. }
  43604. });
  43605. out('>');
  43606. }
  43607. },
  43608. end: function(tag) {
  43609. tag = angular.lowercase(tag);
  43610. if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
  43611. out('</');
  43612. out(tag);
  43613. out('>');
  43614. }
  43615. if (tag == ignoreCurrentElement) {
  43616. ignoreCurrentElement = false;
  43617. }
  43618. },
  43619. chars: function(chars) {
  43620. if (!ignoreCurrentElement) {
  43621. out(encodeEntities(chars));
  43622. }
  43623. }
  43624. };
  43625. }
  43626. /**
  43627. * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
  43628. * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
  43629. * to allow any of these custom attributes. This method strips them all.
  43630. *
  43631. * @param node Root element to process
  43632. */
  43633. function stripCustomNsAttrs(node) {
  43634. if (node.nodeType === Node.ELEMENT_NODE) {
  43635. var attrs = node.attributes;
  43636. for (var i = 0, l = attrs.length; i < l; i++) {
  43637. var attrNode = attrs[i];
  43638. var attrName = attrNode.name.toLowerCase();
  43639. if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) {
  43640. node.removeAttributeNode(attrNode);
  43641. i--;
  43642. l--;
  43643. }
  43644. }
  43645. }
  43646. var nextNode = node.firstChild;
  43647. if (nextNode) {
  43648. stripCustomNsAttrs(nextNode);
  43649. }
  43650. nextNode = node.nextSibling;
  43651. if (nextNode) {
  43652. stripCustomNsAttrs(nextNode);
  43653. }
  43654. }
  43655. // define ngSanitize module and register $sanitize service
  43656. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  43657. /* global sanitizeText: false */
  43658. /**
  43659. * @ngdoc filter
  43660. * @name linky
  43661. * @kind function
  43662. *
  43663. * @description
  43664. * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
  43665. * plain email address links.
  43666. *
  43667. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  43668. *
  43669. * @param {string} text Input text.
  43670. * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
  43671. * @param {object|function(url)} [attributes] Add custom attributes to the link element.
  43672. *
  43673. * Can be one of:
  43674. *
  43675. * - `object`: A map of attributes
  43676. * - `function`: Takes the url as a parameter and returns a map of attributes
  43677. *
  43678. * If the map of attributes contains a value for `target`, it overrides the value of
  43679. * the target parameter.
  43680. *
  43681. *
  43682. * @returns {string} Html-linkified and {@link $sanitize sanitized} text.
  43683. *
  43684. * @usage
  43685. <span ng-bind-html="linky_expression | linky"></span>
  43686. *
  43687. * @example
  43688. <example module="linkyExample" deps="angular-sanitize.js">
  43689. <file name="index.html">
  43690. <div ng-controller="ExampleController">
  43691. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  43692. <table>
  43693. <tr>
  43694. <th>Filter</th>
  43695. <th>Source</th>
  43696. <th>Rendered</th>
  43697. </tr>
  43698. <tr id="linky-filter">
  43699. <td>linky filter</td>
  43700. <td>
  43701. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  43702. </td>
  43703. <td>
  43704. <div ng-bind-html="snippet | linky"></div>
  43705. </td>
  43706. </tr>
  43707. <tr id="linky-target">
  43708. <td>linky target</td>
  43709. <td>
  43710. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  43711. </td>
  43712. <td>
  43713. <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
  43714. </td>
  43715. </tr>
  43716. <tr id="linky-custom-attributes">
  43717. <td>linky custom attributes</td>
  43718. <td>
  43719. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre>
  43720. </td>
  43721. <td>
  43722. <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
  43723. </td>
  43724. </tr>
  43725. <tr id="escaped-html">
  43726. <td>no filter</td>
  43727. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  43728. <td><div ng-bind="snippet"></div></td>
  43729. </tr>
  43730. </table>
  43731. </file>
  43732. <file name="script.js">
  43733. angular.module('linkyExample', ['ngSanitize'])
  43734. .controller('ExampleController', ['$scope', function($scope) {
  43735. $scope.snippet =
  43736. 'Pretty text with some links:\n'+
  43737. 'http://angularjs.org/,\n'+
  43738. 'mailto:us@somewhere.org,\n'+
  43739. 'another@somewhere.org,\n'+
  43740. 'and one more: ftp://127.0.0.1/.';
  43741. $scope.snippetWithSingleURL = 'http://angularjs.org/';
  43742. }]);
  43743. </file>
  43744. <file name="protractor.js" type="protractor">
  43745. it('should linkify the snippet with urls', function() {
  43746. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  43747. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  43748. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  43749. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  43750. });
  43751. it('should not linkify snippet without the linky filter', function() {
  43752. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  43753. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  43754. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  43755. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  43756. });
  43757. it('should update', function() {
  43758. element(by.model('snippet')).clear();
  43759. element(by.model('snippet')).sendKeys('new http://link.');
  43760. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  43761. toBe('new http://link.');
  43762. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  43763. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  43764. .toBe('new http://link.');
  43765. });
  43766. it('should work with the target property', function() {
  43767. expect(element(by.id('linky-target')).
  43768. element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
  43769. toBe('http://angularjs.org/');
  43770. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  43771. });
  43772. it('should optionally add custom attributes', function() {
  43773. expect(element(by.id('linky-custom-attributes')).
  43774. element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
  43775. toBe('http://angularjs.org/');
  43776. expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
  43777. });
  43778. </file>
  43779. </example>
  43780. */
  43781. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  43782. var LINKY_URL_REGEXP =
  43783. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
  43784. MAILTO_REGEXP = /^mailto:/i;
  43785. var linkyMinErr = angular.$$minErr('linky');
  43786. var isString = angular.isString;
  43787. return function(text, target, attributes) {
  43788. if (text == null || text === '') return text;
  43789. if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
  43790. var match;
  43791. var raw = text;
  43792. var html = [];
  43793. var url;
  43794. var i;
  43795. while ((match = raw.match(LINKY_URL_REGEXP))) {
  43796. // We can not end in these as they are sometimes found at the end of the sentence
  43797. url = match[0];
  43798. // if we did not match ftp/http/www/mailto then assume mailto
  43799. if (!match[2] && !match[4]) {
  43800. url = (match[3] ? 'http://' : 'mailto:') + url;
  43801. }
  43802. i = match.index;
  43803. addText(raw.substr(0, i));
  43804. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  43805. raw = raw.substring(i + match[0].length);
  43806. }
  43807. addText(raw);
  43808. return $sanitize(html.join(''));
  43809. function addText(text) {
  43810. if (!text) {
  43811. return;
  43812. }
  43813. html.push(sanitizeText(text));
  43814. }
  43815. function addLink(url, text) {
  43816. var key;
  43817. html.push('<a ');
  43818. if (angular.isFunction(attributes)) {
  43819. attributes = attributes(url);
  43820. }
  43821. if (angular.isObject(attributes)) {
  43822. for (key in attributes) {
  43823. html.push(key + '="' + attributes[key] + '" ');
  43824. }
  43825. } else {
  43826. attributes = {};
  43827. }
  43828. if (angular.isDefined(target) && !('target' in attributes)) {
  43829. html.push('target="',
  43830. target,
  43831. '" ');
  43832. }
  43833. html.push('href="',
  43834. url.replace(/"/g, '&quot;'),
  43835. '">');
  43836. addText(text);
  43837. html.push('</a>');
  43838. }
  43839. };
  43840. }]);
  43841. })(window, window.angular);
  43842. /*!
  43843. * ionic.bundle.js is a concatenation of:
  43844. * ionic.js, angular.js, angular-animate.js,
  43845. * angular-sanitize.js, angular-ui-router.js,
  43846. * and ionic-angular.js
  43847. */
  43848. /**
  43849. * State-based routing for AngularJS
  43850. * @version v0.2.13
  43851. * @link http://angular-ui.github.com/
  43852. * @license MIT License, http://www.opensource.org/licenses/MIT
  43853. */
  43854. /* commonjs package manager support (eg componentjs) */
  43855. if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
  43856. module.exports = 'ui.router';
  43857. }
  43858. (function (window, angular, undefined) {
  43859. /*jshint globalstrict:true*/
  43860. /*global angular:false*/
  43861. 'use strict';
  43862. var isDefined = angular.isDefined,
  43863. isFunction = angular.isFunction,
  43864. isString = angular.isString,
  43865. isObject = angular.isObject,
  43866. isArray = angular.isArray,
  43867. forEach = angular.forEach,
  43868. extend = angular.extend,
  43869. copy = angular.copy;
  43870. function inherit(parent, extra) {
  43871. return extend(new (extend(function() {}, { prototype: parent }))(), extra);
  43872. }
  43873. function merge(dst) {
  43874. forEach(arguments, function(obj) {
  43875. if (obj !== dst) {
  43876. forEach(obj, function(value, key) {
  43877. if (!dst.hasOwnProperty(key)) dst[key] = value;
  43878. });
  43879. }
  43880. });
  43881. return dst;
  43882. }
  43883. /**
  43884. * Finds the common ancestor path between two states.
  43885. *
  43886. * @param {Object} first The first state.
  43887. * @param {Object} second The second state.
  43888. * @return {Array} Returns an array of state names in descending order, not including the root.
  43889. */
  43890. function ancestors(first, second) {
  43891. var path = [];
  43892. for (var n in first.path) {
  43893. if (first.path[n] !== second.path[n]) break;
  43894. path.push(first.path[n]);
  43895. }
  43896. return path;
  43897. }
  43898. /**
  43899. * IE8-safe wrapper for `Object.keys()`.
  43900. *
  43901. * @param {Object} object A JavaScript object.
  43902. * @return {Array} Returns the keys of the object as an array.
  43903. */
  43904. function objectKeys(object) {
  43905. if (Object.keys) {
  43906. return Object.keys(object);
  43907. }
  43908. var result = [];
  43909. angular.forEach(object, function(val, key) {
  43910. result.push(key);
  43911. });
  43912. return result;
  43913. }
  43914. /**
  43915. * IE8-safe wrapper for `Array.prototype.indexOf()`.
  43916. *
  43917. * @param {Array} array A JavaScript array.
  43918. * @param {*} value A value to search the array for.
  43919. * @return {Number} Returns the array index value of `value`, or `-1` if not present.
  43920. */
  43921. function indexOf(array, value) {
  43922. if (Array.prototype.indexOf) {
  43923. return array.indexOf(value, Number(arguments[2]) || 0);
  43924. }
  43925. var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  43926. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  43927. if (from < 0) from += len;
  43928. for (; from < len; from++) {
  43929. if (from in array && array[from] === value) return from;
  43930. }
  43931. return -1;
  43932. }
  43933. /**
  43934. * Merges a set of parameters with all parameters inherited between the common parents of the
  43935. * current state and a given destination state.
  43936. *
  43937. * @param {Object} currentParams The value of the current state parameters ($stateParams).
  43938. * @param {Object} newParams The set of parameters which will be composited with inherited params.
  43939. * @param {Object} $current Internal definition of object representing the current state.
  43940. * @param {Object} $to Internal definition of object representing state to transition to.
  43941. */
  43942. function inheritParams(currentParams, newParams, $current, $to) {
  43943. var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
  43944. for (var i in parents) {
  43945. if (!parents[i].params) continue;
  43946. parentParams = objectKeys(parents[i].params);
  43947. if (!parentParams.length) continue;
  43948. for (var j in parentParams) {
  43949. if (indexOf(inheritList, parentParams[j]) >= 0) continue;
  43950. inheritList.push(parentParams[j]);
  43951. inherited[parentParams[j]] = currentParams[parentParams[j]];
  43952. }
  43953. }
  43954. return extend({}, inherited, newParams);
  43955. }
  43956. /**
  43957. * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
  43958. *
  43959. * @param {Object} a The first object.
  43960. * @param {Object} b The second object.
  43961. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
  43962. * it defaults to the list of keys in `a`.
  43963. * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
  43964. */
  43965. function equalForKeys(a, b, keys) {
  43966. if (!keys) {
  43967. keys = [];
  43968. for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  43969. }
  43970. for (var i=0; i<keys.length; i++) {
  43971. var k = keys[i];
  43972. if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  43973. }
  43974. return true;
  43975. }
  43976. /**
  43977. * Returns the subset of an object, based on a list of keys.
  43978. *
  43979. * @param {Array} keys
  43980. * @param {Object} values
  43981. * @return {Boolean} Returns a subset of `values`.
  43982. */
  43983. function filterByKeys(keys, values) {
  43984. var filtered = {};
  43985. forEach(keys, function (name) {
  43986. filtered[name] = values[name];
  43987. });
  43988. return filtered;
  43989. }
  43990. // like _.indexBy
  43991. // when you know that your index values will be unique, or you want last-one-in to win
  43992. function indexBy(array, propName) {
  43993. var result = {};
  43994. forEach(array, function(item) {
  43995. result[item[propName]] = item;
  43996. });
  43997. return result;
  43998. }
  43999. // extracted from underscore.js
  44000. // Return a copy of the object only containing the whitelisted properties.
  44001. function pick(obj) {
  44002. var copy = {};
  44003. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  44004. forEach(keys, function(key) {
  44005. if (key in obj) copy[key] = obj[key];
  44006. });
  44007. return copy;
  44008. }
  44009. // extracted from underscore.js
  44010. // Return a copy of the object omitting the blacklisted properties.
  44011. function omit(obj) {
  44012. var copy = {};
  44013. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  44014. for (var key in obj) {
  44015. if (indexOf(keys, key) == -1) copy[key] = obj[key];
  44016. }
  44017. return copy;
  44018. }
  44019. function pluck(collection, key) {
  44020. var result = isArray(collection) ? [] : {};
  44021. forEach(collection, function(val, i) {
  44022. result[i] = isFunction(key) ? key(val) : val[key];
  44023. });
  44024. return result;
  44025. }
  44026. function filter(collection, callback) {
  44027. var array = isArray(collection);
  44028. var result = array ? [] : {};
  44029. forEach(collection, function(val, i) {
  44030. if (callback(val, i)) {
  44031. result[array ? result.length : i] = val;
  44032. }
  44033. });
  44034. return result;
  44035. }
  44036. function map(collection, callback) {
  44037. var result = isArray(collection) ? [] : {};
  44038. forEach(collection, function(val, i) {
  44039. result[i] = callback(val, i);
  44040. });
  44041. return result;
  44042. }
  44043. /**
  44044. * @ngdoc overview
  44045. * @name ui.router.util
  44046. *
  44047. * @description
  44048. * # ui.router.util sub-module
  44049. *
  44050. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  44051. * in your angular app (use {@link ui.router} module instead).
  44052. *
  44053. */
  44054. angular.module('ui.router.util', ['ng']);
  44055. /**
  44056. * @ngdoc overview
  44057. * @name ui.router.router
  44058. *
  44059. * @requires ui.router.util
  44060. *
  44061. * @description
  44062. * # ui.router.router sub-module
  44063. *
  44064. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  44065. * in your angular app (use {@link ui.router} module instead).
  44066. */
  44067. angular.module('ui.router.router', ['ui.router.util']);
  44068. /**
  44069. * @ngdoc overview
  44070. * @name ui.router.state
  44071. *
  44072. * @requires ui.router.router
  44073. * @requires ui.router.util
  44074. *
  44075. * @description
  44076. * # ui.router.state sub-module
  44077. *
  44078. * This module is a dependency of the main ui.router module. Do not include this module as a dependency
  44079. * in your angular app (use {@link ui.router} module instead).
  44080. *
  44081. */
  44082. angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
  44083. /**
  44084. * @ngdoc overview
  44085. * @name ui.router
  44086. *
  44087. * @requires ui.router.state
  44088. *
  44089. * @description
  44090. * # ui.router
  44091. *
  44092. * ## The main module for ui.router
  44093. * There are several sub-modules included with the ui.router module, however only this module is needed
  44094. * as a dependency within your angular app. The other modules are for organization purposes.
  44095. *
  44096. * The modules are:
  44097. * * ui.router - the main "umbrella" module
  44098. * * ui.router.router -
  44099. *
  44100. * *You'll need to include **only** this module as the dependency within your angular app.*
  44101. *
  44102. * <pre>
  44103. * <!doctype html>
  44104. * <html ng-app="myApp">
  44105. * <head>
  44106. * <script src="js/angular.js"></script>
  44107. * <!-- Include the ui-router script -->
  44108. * <script src="js/angular-ui-router.min.js"></script>
  44109. * <script>
  44110. * // ...and add 'ui.router' as a dependency
  44111. * var myApp = angular.module('myApp', ['ui.router']);
  44112. * </script>
  44113. * </head>
  44114. * <body>
  44115. * </body>
  44116. * </html>
  44117. * </pre>
  44118. */
  44119. angular.module('ui.router', ['ui.router.state']);
  44120. angular.module('ui.router.compat', ['ui.router']);
  44121. /**
  44122. * @ngdoc object
  44123. * @name ui.router.util.$resolve
  44124. *
  44125. * @requires $q
  44126. * @requires $injector
  44127. *
  44128. * @description
  44129. * Manages resolution of (acyclic) graphs of promises.
  44130. */
  44131. $Resolve.$inject = ['$q', '$injector'];
  44132. function $Resolve( $q, $injector) {
  44133. var VISIT_IN_PROGRESS = 1,
  44134. VISIT_DONE = 2,
  44135. NOTHING = {},
  44136. NO_DEPENDENCIES = [],
  44137. NO_LOCALS = NOTHING,
  44138. NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
  44139. /**
  44140. * @ngdoc function
  44141. * @name ui.router.util.$resolve#study
  44142. * @methodOf ui.router.util.$resolve
  44143. *
  44144. * @description
  44145. * Studies a set of invocables that are likely to be used multiple times.
  44146. * <pre>
  44147. * $resolve.study(invocables)(locals, parent, self)
  44148. * </pre>
  44149. * is equivalent to
  44150. * <pre>
  44151. * $resolve.resolve(invocables, locals, parent, self)
  44152. * </pre>
  44153. * but the former is more efficient (in fact `resolve` just calls `study`
  44154. * internally).
  44155. *
  44156. * @param {object} invocables Invocable objects
  44157. * @return {function} a function to pass in locals, parent and self
  44158. */
  44159. this.study = function (invocables) {
  44160. if (!isObject(invocables)) throw new Error("'invocables' must be an object");
  44161. var invocableKeys = objectKeys(invocables || {});
  44162. // Perform a topological sort of invocables to build an ordered plan
  44163. var plan = [], cycle = [], visited = {};
  44164. function visit(value, key) {
  44165. if (visited[key] === VISIT_DONE) return;
  44166. cycle.push(key);
  44167. if (visited[key] === VISIT_IN_PROGRESS) {
  44168. cycle.splice(0, indexOf(cycle, key));
  44169. throw new Error("Cyclic dependency: " + cycle.join(" -> "));
  44170. }
  44171. visited[key] = VISIT_IN_PROGRESS;
  44172. if (isString(value)) {
  44173. plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
  44174. } else {
  44175. var params = $injector.annotate(value);
  44176. forEach(params, function (param) {
  44177. if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
  44178. });
  44179. plan.push(key, value, params);
  44180. }
  44181. cycle.pop();
  44182. visited[key] = VISIT_DONE;
  44183. }
  44184. forEach(invocables, visit);
  44185. invocables = cycle = visited = null; // plan is all that's required
  44186. function isResolve(value) {
  44187. return isObject(value) && value.then && value.$$promises;
  44188. }
  44189. return function (locals, parent, self) {
  44190. if (isResolve(locals) && self === undefined) {
  44191. self = parent; parent = locals; locals = null;
  44192. }
  44193. if (!locals) locals = NO_LOCALS;
  44194. else if (!isObject(locals)) {
  44195. throw new Error("'locals' must be an object");
  44196. }
  44197. if (!parent) parent = NO_PARENT;
  44198. else if (!isResolve(parent)) {
  44199. throw new Error("'parent' must be a promise returned by $resolve.resolve()");
  44200. }
  44201. // To complete the overall resolution, we have to wait for the parent
  44202. // promise and for the promise for each invokable in our plan.
  44203. var resolution = $q.defer(),
  44204. result = resolution.promise,
  44205. promises = result.$$promises = {},
  44206. values = extend({}, locals),
  44207. wait = 1 + plan.length/3,
  44208. merged = false;
  44209. function done() {
  44210. // Merge parent values we haven't got yet and publish our own $$values
  44211. if (!--wait) {
  44212. if (!merged) merge(values, parent.$$values);
  44213. result.$$values = values;
  44214. result.$$promises = result.$$promises || true; // keep for isResolve()
  44215. delete result.$$inheritedValues;
  44216. resolution.resolve(values);
  44217. }
  44218. }
  44219. function fail(reason) {
  44220. result.$$failure = reason;
  44221. resolution.reject(reason);
  44222. }
  44223. // Short-circuit if parent has already failed
  44224. if (isDefined(parent.$$failure)) {
  44225. fail(parent.$$failure);
  44226. return result;
  44227. }
  44228. if (parent.$$inheritedValues) {
  44229. merge(values, omit(parent.$$inheritedValues, invocableKeys));
  44230. }
  44231. // Merge parent values if the parent has already resolved, or merge
  44232. // parent promises and wait if the parent resolve is still in progress.
  44233. extend(promises, parent.$$promises);
  44234. if (parent.$$values) {
  44235. merged = merge(values, omit(parent.$$values, invocableKeys));
  44236. result.$$inheritedValues = omit(parent.$$values, invocableKeys);
  44237. done();
  44238. } else {
  44239. if (parent.$$inheritedValues) {
  44240. result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
  44241. }
  44242. parent.then(done, fail);
  44243. }
  44244. // Process each invocable in the plan, but ignore any where a local of the same name exists.
  44245. for (var i=0, ii=plan.length; i<ii; i+=3) {
  44246. if (locals.hasOwnProperty(plan[i])) done();
  44247. else invoke(plan[i], plan[i+1], plan[i+2]);
  44248. }
  44249. function invoke(key, invocable, params) {
  44250. // Create a deferred for this invocation. Failures will propagate to the resolution as well.
  44251. var invocation = $q.defer(), waitParams = 0;
  44252. function onfailure(reason) {
  44253. invocation.reject(reason);
  44254. fail(reason);
  44255. }
  44256. // Wait for any parameter that we have a promise for (either from parent or from this
  44257. // resolve; in that case study() will have made sure it's ordered before us in the plan).
  44258. forEach(params, function (dep) {
  44259. if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
  44260. waitParams++;
  44261. promises[dep].then(function (result) {
  44262. values[dep] = result;
  44263. if (!(--waitParams)) proceed();
  44264. }, onfailure);
  44265. }
  44266. });
  44267. if (!waitParams) proceed();
  44268. function proceed() {
  44269. if (isDefined(result.$$failure)) return;
  44270. try {
  44271. invocation.resolve($injector.invoke(invocable, self, values));
  44272. invocation.promise.then(function (result) {
  44273. values[key] = result;
  44274. done();
  44275. }, onfailure);
  44276. } catch (e) {
  44277. onfailure(e);
  44278. }
  44279. }
  44280. // Publish promise synchronously; invocations further down in the plan may depend on it.
  44281. promises[key] = invocation.promise;
  44282. }
  44283. return result;
  44284. };
  44285. };
  44286. /**
  44287. * @ngdoc function
  44288. * @name ui.router.util.$resolve#resolve
  44289. * @methodOf ui.router.util.$resolve
  44290. *
  44291. * @description
  44292. * Resolves a set of invocables. An invocable is a function to be invoked via
  44293. * `$injector.invoke()`, and can have an arbitrary number of dependencies.
  44294. * An invocable can either return a value directly,
  44295. * or a `$q` promise. If a promise is returned it will be resolved and the
  44296. * resulting value will be used instead. Dependencies of invocables are resolved
  44297. * (in this order of precedence)
  44298. *
  44299. * - from the specified `locals`
  44300. * - from another invocable that is part of this `$resolve` call
  44301. * - from an invocable that is inherited from a `parent` call to `$resolve`
  44302. * (or recursively
  44303. * - from any ancestor `$resolve` of that parent).
  44304. *
  44305. * The return value of `$resolve` is a promise for an object that contains
  44306. * (in this order of precedence)
  44307. *
  44308. * - any `locals` (if specified)
  44309. * - the resolved return values of all injectables
  44310. * - any values inherited from a `parent` call to `$resolve` (if specified)
  44311. *
  44312. * The promise will resolve after the `parent` promise (if any) and all promises
  44313. * returned by injectables have been resolved. If any invocable
  44314. * (or `$injector.invoke`) throws an exception, or if a promise returned by an
  44315. * invocable is rejected, the `$resolve` promise is immediately rejected with the
  44316. * same error. A rejection of a `parent` promise (if specified) will likewise be
  44317. * propagated immediately. Once the `$resolve` promise has been rejected, no
  44318. * further invocables will be called.
  44319. *
  44320. * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
  44321. * to throw an error. As a special case, an injectable can depend on a parameter
  44322. * with the same name as the injectable, which will be fulfilled from the `parent`
  44323. * injectable of the same name. This allows inherited values to be decorated.
  44324. * Note that in this case any other injectable in the same `$resolve` with the same
  44325. * dependency would see the decorated value, not the inherited value.
  44326. *
  44327. * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
  44328. * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
  44329. * exception.
  44330. *
  44331. * Invocables are invoked eagerly as soon as all dependencies are available.
  44332. * This is true even for dependencies inherited from a `parent` call to `$resolve`.
  44333. *
  44334. * As a special case, an invocable can be a string, in which case it is taken to
  44335. * be a service name to be passed to `$injector.get()`. This is supported primarily
  44336. * for backwards-compatibility with the `resolve` property of `$routeProvider`
  44337. * routes.
  44338. *
  44339. * @param {object} invocables functions to invoke or
  44340. * `$injector` services to fetch.
  44341. * @param {object} locals values to make available to the injectables
  44342. * @param {object} parent a promise returned by another call to `$resolve`.
  44343. * @param {object} self the `this` for the invoked methods
  44344. * @return {object} Promise for an object that contains the resolved return value
  44345. * of all invocables, as well as any inherited and local values.
  44346. */
  44347. this.resolve = function (invocables, locals, parent, self) {
  44348. return this.study(invocables)(locals, parent, self);
  44349. };
  44350. }
  44351. angular.module('ui.router.util').service('$resolve', $Resolve);
  44352. /**
  44353. * @ngdoc object
  44354. * @name ui.router.util.$templateFactory
  44355. *
  44356. * @requires $http
  44357. * @requires $templateCache
  44358. * @requires $injector
  44359. *
  44360. * @description
  44361. * Service. Manages loading of templates.
  44362. */
  44363. $TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
  44364. function $TemplateFactory( $http, $templateCache, $injector) {
  44365. /**
  44366. * @ngdoc function
  44367. * @name ui.router.util.$templateFactory#fromConfig
  44368. * @methodOf ui.router.util.$templateFactory
  44369. *
  44370. * @description
  44371. * Creates a template from a configuration object.
  44372. *
  44373. * @param {object} config Configuration object for which to load a template.
  44374. * The following properties are search in the specified order, and the first one
  44375. * that is defined is used to create the template:
  44376. *
  44377. * @param {string|object} config.template html string template or function to
  44378. * load via {@link ui.router.util.$templateFactory#fromString fromString}.
  44379. * @param {string|object} config.templateUrl url to load or a function returning
  44380. * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
  44381. * @param {Function} config.templateProvider function to invoke via
  44382. * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
  44383. * @param {object} params Parameters to pass to the template function.
  44384. * @param {object} locals Locals to pass to `invoke` if the template is loaded
  44385. * via a `templateProvider`. Defaults to `{ params: params }`.
  44386. *
  44387. * @return {string|object} The template html as a string, or a promise for
  44388. * that string,or `null` if no template is configured.
  44389. */
  44390. this.fromConfig = function (config, params, locals) {
  44391. return (
  44392. isDefined(config.template) ? this.fromString(config.template, params) :
  44393. isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
  44394. isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
  44395. null
  44396. );
  44397. };
  44398. /**
  44399. * @ngdoc function
  44400. * @name ui.router.util.$templateFactory#fromString
  44401. * @methodOf ui.router.util.$templateFactory
  44402. *
  44403. * @description
  44404. * Creates a template from a string or a function returning a string.
  44405. *
  44406. * @param {string|object} template html template as a string or function that
  44407. * returns an html template as a string.
  44408. * @param {object} params Parameters to pass to the template function.
  44409. *
  44410. * @return {string|object} The template html as a string, or a promise for that
  44411. * string.
  44412. */
  44413. this.fromString = function (template, params) {
  44414. return isFunction(template) ? template(params) : template;
  44415. };
  44416. /**
  44417. * @ngdoc function
  44418. * @name ui.router.util.$templateFactory#fromUrl
  44419. * @methodOf ui.router.util.$templateFactory
  44420. *
  44421. * @description
  44422. * Loads a template from the a URL via `$http` and `$templateCache`.
  44423. *
  44424. * @param {string|Function} url url of the template to load, or a function
  44425. * that returns a url.
  44426. * @param {Object} params Parameters to pass to the url function.
  44427. * @return {string|Promise.<string>} The template html as a string, or a promise
  44428. * for that string.
  44429. */
  44430. this.fromUrl = function (url, params) {
  44431. if (isFunction(url)) url = url(params);
  44432. if (url == null) return null;
  44433. else return $http
  44434. .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
  44435. .then(function(response) { return response.data; });
  44436. };
  44437. /**
  44438. * @ngdoc function
  44439. * @name ui.router.util.$templateFactory#fromProvider
  44440. * @methodOf ui.router.util.$templateFactory
  44441. *
  44442. * @description
  44443. * Creates a template by invoking an injectable provider function.
  44444. *
  44445. * @param {Function} provider Function to invoke via `$injector.invoke`
  44446. * @param {Object} params Parameters for the template.
  44447. * @param {Object} locals Locals to pass to `invoke`. Defaults to
  44448. * `{ params: params }`.
  44449. * @return {string|Promise.<string>} The template html as a string, or a promise
  44450. * for that string.
  44451. */
  44452. this.fromProvider = function (provider, params, locals) {
  44453. return $injector.invoke(provider, null, locals || { params: params });
  44454. };
  44455. }
  44456. angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
  44457. var $$UMFP; // reference to $UrlMatcherFactoryProvider
  44458. /**
  44459. * @ngdoc object
  44460. * @name ui.router.util.type:UrlMatcher
  44461. *
  44462. * @description
  44463. * Matches URLs against patterns and extracts named parameters from the path or the search
  44464. * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
  44465. * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
  44466. * do not influence whether or not a URL is matched, but their values are passed through into
  44467. * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
  44468. *
  44469. * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
  44470. * syntax, which optionally allows a regular expression for the parameter to be specified:
  44471. *
  44472. * * `':'` name - colon placeholder
  44473. * * `'*'` name - catch-all placeholder
  44474. * * `'{' name '}'` - curly placeholder
  44475. * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
  44476. * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
  44477. *
  44478. * Parameter names may contain only word characters (latin letters, digits, and underscore) and
  44479. * must be unique within the pattern (across both path and search parameters). For colon
  44480. * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
  44481. * number of characters other than '/'. For catch-all placeholders the path parameter matches
  44482. * any number of characters.
  44483. *
  44484. * Examples:
  44485. *
  44486. * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
  44487. * trailing slashes, and patterns have to match the entire path, not just a prefix.
  44488. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
  44489. * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
  44490. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
  44491. * * `'/user/{id:[^/]*}'` - Same as the previous example.
  44492. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
  44493. * parameter consists of 1 to 8 hex digits.
  44494. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
  44495. * path into the parameter 'path'.
  44496. * * `'/files/*path'` - ditto.
  44497. * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
  44498. * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
  44499. *
  44500. * @param {string} pattern The pattern to compile into a matcher.
  44501. * @param {Object} config A configuration object hash:
  44502. * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
  44503. * an existing UrlMatcher
  44504. *
  44505. * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
  44506. * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.
  44507. *
  44508. * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
  44509. * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
  44510. * non-null) will start with this prefix.
  44511. *
  44512. * @property {string} source The pattern that was passed into the constructor
  44513. *
  44514. * @property {string} sourcePath The path portion of the source property
  44515. *
  44516. * @property {string} sourceSearch The search portion of the source property
  44517. *
  44518. * @property {string} regex The constructed regex that will be used to match against the url when
  44519. * it is time to determine which url will match.
  44520. *
  44521. * @returns {Object} New `UrlMatcher` object
  44522. */
  44523. function UrlMatcher(pattern, config, parentMatcher) {
  44524. config = extend({ params: {} }, isObject(config) ? config : {});
  44525. // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
  44526. // '*' name
  44527. // ':' name
  44528. // '{' name '}'
  44529. // '{' name ':' regexp '}'
  44530. // The regular expression is somewhat complicated due to the need to allow curly braces
  44531. // inside the regular expression. The placeholder regexp breaks down as follows:
  44532. // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
  44533. // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
  44534. // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
  44535. // [^{}\\]+ - anything other than curly braces or backslash
  44536. // \\. - a backslash escape
  44537. // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
  44538. var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  44539. searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  44540. compiled = '^', last = 0, m,
  44541. segments = this.segments = [],
  44542. parentParams = parentMatcher ? parentMatcher.params : {},
  44543. params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
  44544. paramNames = [];
  44545. function addParameter(id, type, config, location) {
  44546. paramNames.push(id);
  44547. if (parentParams[id]) return parentParams[id];
  44548. if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
  44549. if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
  44550. params[id] = new $$UMFP.Param(id, type, config, location);
  44551. return params[id];
  44552. }
  44553. function quoteRegExp(string, pattern, squash) {
  44554. var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
  44555. if (!pattern) return result;
  44556. switch(squash) {
  44557. case false: surroundPattern = ['(', ')']; break;
  44558. case true: surroundPattern = ['?(', ')?']; break;
  44559. default: surroundPattern = ['(' + squash + "|", ')?']; break;
  44560. }
  44561. return result + surroundPattern[0] + pattern + surroundPattern[1];
  44562. }
  44563. this.source = pattern;
  44564. // Split into static segments separated by path parameter placeholders.
  44565. // The number of segments is always 1 more than the number of parameters.
  44566. function matchDetails(m, isSearch) {
  44567. var id, regexp, segment, type, cfg, arrayMode;
  44568. id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
  44569. cfg = config.params[id];
  44570. segment = pattern.substring(last, m.index);
  44571. regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
  44572. type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp) });
  44573. return {
  44574. id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
  44575. };
  44576. }
  44577. var p, param, segment;
  44578. while ((m = placeholder.exec(pattern))) {
  44579. p = matchDetails(m, false);
  44580. if (p.segment.indexOf('?') >= 0) break; // we're into the search part
  44581. param = addParameter(p.id, p.type, p.cfg, "path");
  44582. compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);
  44583. segments.push(p.segment);
  44584. last = placeholder.lastIndex;
  44585. }
  44586. segment = pattern.substring(last);
  44587. // Find any search parameter names and remove them from the last segment
  44588. var i = segment.indexOf('?');
  44589. if (i >= 0) {
  44590. var search = this.sourceSearch = segment.substring(i);
  44591. segment = segment.substring(0, i);
  44592. this.sourcePath = pattern.substring(0, last + i);
  44593. if (search.length > 0) {
  44594. last = 0;
  44595. while ((m = searchPlaceholder.exec(search))) {
  44596. p = matchDetails(m, true);
  44597. param = addParameter(p.id, p.type, p.cfg, "search");
  44598. last = placeholder.lastIndex;
  44599. // check if ?&
  44600. }
  44601. }
  44602. } else {
  44603. this.sourcePath = pattern;
  44604. this.sourceSearch = '';
  44605. }
  44606. compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
  44607. segments.push(segment);
  44608. this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
  44609. this.prefix = segments[0];
  44610. this.$$paramNames = paramNames;
  44611. }
  44612. /**
  44613. * @ngdoc function
  44614. * @name ui.router.util.type:UrlMatcher#concat
  44615. * @methodOf ui.router.util.type:UrlMatcher
  44616. *
  44617. * @description
  44618. * Returns a new matcher for a pattern constructed by appending the path part and adding the
  44619. * search parameters of the specified pattern to this pattern. The current pattern is not
  44620. * modified. This can be understood as creating a pattern for URLs that are relative to (or
  44621. * suffixes of) the current pattern.
  44622. *
  44623. * @example
  44624. * The following two matchers are equivalent:
  44625. * <pre>
  44626. * new UrlMatcher('/user/{id}?q').concat('/details?date');
  44627. * new UrlMatcher('/user/{id}/details?q&date');
  44628. * </pre>
  44629. *
  44630. * @param {string} pattern The pattern to append.
  44631. * @param {Object} config An object hash of the configuration for the matcher.
  44632. * @returns {UrlMatcher} A matcher for the concatenated pattern.
  44633. */
  44634. UrlMatcher.prototype.concat = function (pattern, config) {
  44635. // Because order of search parameters is irrelevant, we can add our own search
  44636. // parameters to the end of the new pattern. Parse the new pattern by itself
  44637. // and then join the bits together, but it's much easier to do this on a string level.
  44638. var defaultConfig = {
  44639. caseInsensitive: $$UMFP.caseInsensitive(),
  44640. strict: $$UMFP.strictMode(),
  44641. squash: $$UMFP.defaultSquashPolicy()
  44642. };
  44643. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
  44644. };
  44645. UrlMatcher.prototype.toString = function () {
  44646. return this.source;
  44647. };
  44648. /**
  44649. * @ngdoc function
  44650. * @name ui.router.util.type:UrlMatcher#exec
  44651. * @methodOf ui.router.util.type:UrlMatcher
  44652. *
  44653. * @description
  44654. * Tests the specified path against this matcher, and returns an object containing the captured
  44655. * parameter values, or null if the path does not match. The returned object contains the values
  44656. * of any search parameters that are mentioned in the pattern, but their value may be null if
  44657. * they are not present in `searchParams`. This means that search parameters are always treated
  44658. * as optional.
  44659. *
  44660. * @example
  44661. * <pre>
  44662. * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
  44663. * x: '1', q: 'hello'
  44664. * });
  44665. * // returns { id: 'bob', q: 'hello', r: null }
  44666. * </pre>
  44667. *
  44668. * @param {string} path The URL path to match, e.g. `$location.path()`.
  44669. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
  44670. * @returns {Object} The captured parameter values.
  44671. */
  44672. UrlMatcher.prototype.exec = function (path, searchParams) {
  44673. var m = this.regexp.exec(path);
  44674. if (!m) return null;
  44675. searchParams = searchParams || {};
  44676. var paramNames = this.parameters(), nTotal = paramNames.length,
  44677. nPath = this.segments.length - 1,
  44678. values = {}, i, j, cfg, paramName;
  44679. if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
  44680. function decodePathArray(string) {
  44681. function reverseString(str) { return str.split("").reverse().join(""); }
  44682. function unquoteDashes(str) { return str.replace(/\\-/, "-"); }
  44683. var split = reverseString(string).split(/-(?!\\)/);
  44684. var allReversed = map(split, reverseString);
  44685. return map(allReversed, unquoteDashes).reverse();
  44686. }
  44687. for (i = 0; i < nPath; i++) {
  44688. paramName = paramNames[i];
  44689. var param = this.params[paramName];
  44690. var paramVal = m[i+1];
  44691. // if the param value matches a pre-replace pair, replace the value before decoding.
  44692. for (j = 0; j < param.replace; j++) {
  44693. if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
  44694. }
  44695. if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
  44696. values[paramName] = param.value(paramVal);
  44697. }
  44698. for (/**/; i < nTotal; i++) {
  44699. paramName = paramNames[i];
  44700. values[paramName] = this.params[paramName].value(searchParams[paramName]);
  44701. }
  44702. return values;
  44703. };
  44704. /**
  44705. * @ngdoc function
  44706. * @name ui.router.util.type:UrlMatcher#parameters
  44707. * @methodOf ui.router.util.type:UrlMatcher
  44708. *
  44709. * @description
  44710. * Returns the names of all path and search parameters of this pattern in an unspecified order.
  44711. *
  44712. * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
  44713. * pattern has no parameters, an empty array is returned.
  44714. */
  44715. UrlMatcher.prototype.parameters = function (param) {
  44716. if (!isDefined(param)) return this.$$paramNames;
  44717. return this.params[param] || null;
  44718. };
  44719. /**
  44720. * @ngdoc function
  44721. * @name ui.router.util.type:UrlMatcher#validate
  44722. * @methodOf ui.router.util.type:UrlMatcher
  44723. *
  44724. * @description
  44725. * Checks an object hash of parameters to validate their correctness according to the parameter
  44726. * types of this `UrlMatcher`.
  44727. *
  44728. * @param {Object} params The object hash of parameters to validate.
  44729. * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
  44730. */
  44731. UrlMatcher.prototype.validates = function (params) {
  44732. return this.params.$$validates(params);
  44733. };
  44734. /**
  44735. * @ngdoc function
  44736. * @name ui.router.util.type:UrlMatcher#format
  44737. * @methodOf ui.router.util.type:UrlMatcher
  44738. *
  44739. * @description
  44740. * Creates a URL that matches this pattern by substituting the specified values
  44741. * for the path and search parameters. Null values for path parameters are
  44742. * treated as empty strings.
  44743. *
  44744. * @example
  44745. * <pre>
  44746. * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
  44747. * // returns '/user/bob?q=yes'
  44748. * </pre>
  44749. *
  44750. * @param {Object} values the values to substitute for the parameters in this pattern.
  44751. * @returns {string} the formatted URL (path and optionally search part).
  44752. */
  44753. UrlMatcher.prototype.format = function (values) {
  44754. values = values || {};
  44755. var segments = this.segments, params = this.parameters(), paramset = this.params;
  44756. if (!this.validates(values)) return null;
  44757. var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
  44758. function encodeDashes(str) { // Replace dashes with encoded "\-"
  44759. return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
  44760. }
  44761. for (i = 0; i < nTotal; i++) {
  44762. var isPathParam = i < nPath;
  44763. var name = params[i], param = paramset[name], value = param.value(values[name]);
  44764. var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
  44765. var squash = isDefaultValue ? param.squash : false;
  44766. var encoded = param.type.encode(value);
  44767. if (isPathParam) {
  44768. var nextSegment = segments[i + 1];
  44769. if (squash === false) {
  44770. if (encoded != null) {
  44771. if (isArray(encoded)) {
  44772. result += map(encoded, encodeDashes).join("-");
  44773. } else {
  44774. result += encodeURIComponent(encoded);
  44775. }
  44776. }
  44777. result += nextSegment;
  44778. } else if (squash === true) {
  44779. var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
  44780. result += nextSegment.match(capture)[1];
  44781. } else if (isString(squash)) {
  44782. result += squash + nextSegment;
  44783. }
  44784. } else {
  44785. if (encoded == null || (isDefaultValue && squash !== false)) continue;
  44786. if (!isArray(encoded)) encoded = [ encoded ];
  44787. encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
  44788. result += (search ? '&' : '?') + (name + '=' + encoded);
  44789. search = true;
  44790. }
  44791. }
  44792. return result;
  44793. };
  44794. /**
  44795. * @ngdoc object
  44796. * @name ui.router.util.type:Type
  44797. *
  44798. * @description
  44799. * Implements an interface to define custom parameter types that can be decoded from and encoded to
  44800. * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
  44801. * objects when matching or formatting URLs, or comparing or validating parameter values.
  44802. *
  44803. * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
  44804. * information on registering custom types.
  44805. *
  44806. * @param {Object} config A configuration object which contains the custom type definition. The object's
  44807. * properties will override the default methods and/or pattern in `Type`'s public interface.
  44808. * @example
  44809. * <pre>
  44810. * {
  44811. * decode: function(val) { return parseInt(val, 10); },
  44812. * encode: function(val) { return val && val.toString(); },
  44813. * equals: function(a, b) { return this.is(a) && a === b; },
  44814. * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
  44815. * pattern: /\d+/
  44816. * }
  44817. * </pre>
  44818. *
  44819. * @property {RegExp} pattern The regular expression pattern used to match values of this type when
  44820. * coming from a substring of a URL.
  44821. *
  44822. * @returns {Object} Returns a new `Type` object.
  44823. */
  44824. function Type(config) {
  44825. extend(this, config);
  44826. }
  44827. /**
  44828. * @ngdoc function
  44829. * @name ui.router.util.type:Type#is
  44830. * @methodOf ui.router.util.type:Type
  44831. *
  44832. * @description
  44833. * Detects whether a value is of a particular type. Accepts a native (decoded) value
  44834. * and determines whether it matches the current `Type` object.
  44835. *
  44836. * @param {*} val The value to check.
  44837. * @param {string} key Optional. If the type check is happening in the context of a specific
  44838. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
  44839. * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
  44840. * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
  44841. */
  44842. Type.prototype.is = function(val, key) {
  44843. return true;
  44844. };
  44845. /**
  44846. * @ngdoc function
  44847. * @name ui.router.util.type:Type#encode
  44848. * @methodOf ui.router.util.type:Type
  44849. *
  44850. * @description
  44851. * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
  44852. * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
  44853. * only needs to be a representation of `val` that has been coerced to a string.
  44854. *
  44855. * @param {*} val The value to encode.
  44856. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  44857. * meta-programming of `Type` objects.
  44858. * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
  44859. */
  44860. Type.prototype.encode = function(val, key) {
  44861. return val;
  44862. };
  44863. /**
  44864. * @ngdoc function
  44865. * @name ui.router.util.type:Type#decode
  44866. * @methodOf ui.router.util.type:Type
  44867. *
  44868. * @description
  44869. * Converts a parameter value (from URL string or transition param) to a custom/native value.
  44870. *
  44871. * @param {string} val The URL parameter value to decode.
  44872. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  44873. * meta-programming of `Type` objects.
  44874. * @returns {*} Returns a custom representation of the URL parameter value.
  44875. */
  44876. Type.prototype.decode = function(val, key) {
  44877. return val;
  44878. };
  44879. /**
  44880. * @ngdoc function
  44881. * @name ui.router.util.type:Type#equals
  44882. * @methodOf ui.router.util.type:Type
  44883. *
  44884. * @description
  44885. * Determines whether two decoded values are equivalent.
  44886. *
  44887. * @param {*} a A value to compare against.
  44888. * @param {*} b A value to compare against.
  44889. * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
  44890. */
  44891. Type.prototype.equals = function(a, b) {
  44892. return a == b;
  44893. };
  44894. Type.prototype.$subPattern = function() {
  44895. var sub = this.pattern.toString();
  44896. return sub.substr(1, sub.length - 2);
  44897. };
  44898. Type.prototype.pattern = /.*/;
  44899. Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
  44900. /*
  44901. * Wraps an existing custom Type as an array of Type, depending on 'mode'.
  44902. * e.g.:
  44903. * - urlmatcher pattern "/path?{queryParam[]:int}"
  44904. * - url: "/path?queryParam=1&queryParam=2
  44905. * - $stateParams.queryParam will be [1, 2]
  44906. * if `mode` is "auto", then
  44907. * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
  44908. * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
  44909. */
  44910. Type.prototype.$asArray = function(mode, isSearch) {
  44911. if (!mode) return this;
  44912. if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
  44913. return new ArrayType(this, mode);
  44914. function ArrayType(type, mode) {
  44915. function bindTo(type, callbackName) {
  44916. return function() {
  44917. return type[callbackName].apply(type, arguments);
  44918. };
  44919. }
  44920. // Wrap non-array value as array
  44921. function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
  44922. // Unwrap array value for "auto" mode. Return undefined for empty array.
  44923. function arrayUnwrap(val) {
  44924. switch(val.length) {
  44925. case 0: return undefined;
  44926. case 1: return mode === "auto" ? val[0] : val;
  44927. default: return val;
  44928. }
  44929. }
  44930. function falsey(val) { return !val; }
  44931. // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
  44932. function arrayHandler(callback, allTruthyMode) {
  44933. return function handleArray(val) {
  44934. val = arrayWrap(val);
  44935. var result = map(val, callback);
  44936. if (allTruthyMode === true)
  44937. return filter(result, falsey).length === 0;
  44938. return arrayUnwrap(result);
  44939. };
  44940. }
  44941. // Wraps type (.equals) functions to operate on each value of an array
  44942. function arrayEqualsHandler(callback) {
  44943. return function handleArray(val1, val2) {
  44944. var left = arrayWrap(val1), right = arrayWrap(val2);
  44945. if (left.length !== right.length) return false;
  44946. for (var i = 0; i < left.length; i++) {
  44947. if (!callback(left[i], right[i])) return false;
  44948. }
  44949. return true;
  44950. };
  44951. }
  44952. this.encode = arrayHandler(bindTo(type, 'encode'));
  44953. this.decode = arrayHandler(bindTo(type, 'decode'));
  44954. this.is = arrayHandler(bindTo(type, 'is'), true);
  44955. this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
  44956. this.pattern = type.pattern;
  44957. this.$arrayMode = mode;
  44958. }
  44959. };
  44960. /**
  44961. * @ngdoc object
  44962. * @name ui.router.util.$urlMatcherFactory
  44963. *
  44964. * @description
  44965. * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
  44966. * is also available to providers under the name `$urlMatcherFactoryProvider`.
  44967. */
  44968. function $UrlMatcherFactory() {
  44969. $$UMFP = this;
  44970. var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
  44971. function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
  44972. function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
  44973. // TODO: in 1.0, make string .is() return false if value is undefined by default.
  44974. // function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); }
  44975. function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }
  44976. var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
  44977. string: {
  44978. encode: valToString,
  44979. decode: valFromString,
  44980. is: regexpMatches,
  44981. pattern: /[^/]*/
  44982. },
  44983. int: {
  44984. encode: valToString,
  44985. decode: function(val) { return parseInt(val, 10); },
  44986. is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
  44987. pattern: /\d+/
  44988. },
  44989. bool: {
  44990. encode: function(val) { return val ? 1 : 0; },
  44991. decode: function(val) { return parseInt(val, 10) !== 0; },
  44992. is: function(val) { return val === true || val === false; },
  44993. pattern: /0|1/
  44994. },
  44995. date: {
  44996. encode: function (val) {
  44997. if (!this.is(val))
  44998. return undefined;
  44999. return [ val.getFullYear(),
  45000. ('0' + (val.getMonth() + 1)).slice(-2),
  45001. ('0' + val.getDate()).slice(-2)
  45002. ].join("-");
  45003. },
  45004. decode: function (val) {
  45005. if (this.is(val)) return val;
  45006. var match = this.capture.exec(val);
  45007. return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
  45008. },
  45009. is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
  45010. equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
  45011. pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
  45012. capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
  45013. },
  45014. json: {
  45015. encode: angular.toJson,
  45016. decode: angular.fromJson,
  45017. is: angular.isObject,
  45018. equals: angular.equals,
  45019. pattern: /[^/]*/
  45020. },
  45021. any: { // does not encode/decode
  45022. encode: angular.identity,
  45023. decode: angular.identity,
  45024. is: angular.identity,
  45025. equals: angular.equals,
  45026. pattern: /.*/
  45027. }
  45028. };
  45029. function getDefaultConfig() {
  45030. return {
  45031. strict: isStrictMode,
  45032. caseInsensitive: isCaseInsensitive
  45033. };
  45034. }
  45035. function isInjectable(value) {
  45036. return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
  45037. }
  45038. /**
  45039. * [Internal] Get the default value of a parameter, which may be an injectable function.
  45040. */
  45041. $UrlMatcherFactory.$$getDefaultValue = function(config) {
  45042. if (!isInjectable(config.value)) return config.value;
  45043. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  45044. return injector.invoke(config.value);
  45045. };
  45046. /**
  45047. * @ngdoc function
  45048. * @name ui.router.util.$urlMatcherFactory#caseInsensitive
  45049. * @methodOf ui.router.util.$urlMatcherFactory
  45050. *
  45051. * @description
  45052. * Defines whether URL matching should be case sensitive (the default behavior), or not.
  45053. *
  45054. * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
  45055. * @returns {boolean} the current value of caseInsensitive
  45056. */
  45057. this.caseInsensitive = function(value) {
  45058. if (isDefined(value))
  45059. isCaseInsensitive = value;
  45060. return isCaseInsensitive;
  45061. };
  45062. /**
  45063. * @ngdoc function
  45064. * @name ui.router.util.$urlMatcherFactory#strictMode
  45065. * @methodOf ui.router.util.$urlMatcherFactory
  45066. *
  45067. * @description
  45068. * Defines whether URLs should match trailing slashes, or not (the default behavior).
  45069. *
  45070. * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
  45071. * @returns {boolean} the current value of strictMode
  45072. */
  45073. this.strictMode = function(value) {
  45074. if (isDefined(value))
  45075. isStrictMode = value;
  45076. return isStrictMode;
  45077. };
  45078. /**
  45079. * @ngdoc function
  45080. * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
  45081. * @methodOf ui.router.util.$urlMatcherFactory
  45082. *
  45083. * @description
  45084. * Sets the default behavior when generating or matching URLs with default parameter values.
  45085. *
  45086. * @param {string} value A string that defines the default parameter URL squashing behavior.
  45087. * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
  45088. * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
  45089. * parameter is surrounded by slashes, squash (remove) one slash from the URL
  45090. * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
  45091. * the parameter value from the URL and replace it with this string.
  45092. */
  45093. this.defaultSquashPolicy = function(value) {
  45094. if (!isDefined(value)) return defaultSquashPolicy;
  45095. if (value !== true && value !== false && !isString(value))
  45096. throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
  45097. defaultSquashPolicy = value;
  45098. return value;
  45099. };
  45100. /**
  45101. * @ngdoc function
  45102. * @name ui.router.util.$urlMatcherFactory#compile
  45103. * @methodOf ui.router.util.$urlMatcherFactory
  45104. *
  45105. * @description
  45106. * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
  45107. *
  45108. * @param {string} pattern The URL pattern.
  45109. * @param {Object} config The config object hash.
  45110. * @returns {UrlMatcher} The UrlMatcher.
  45111. */
  45112. this.compile = function (pattern, config) {
  45113. return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
  45114. };
  45115. /**
  45116. * @ngdoc function
  45117. * @name ui.router.util.$urlMatcherFactory#isMatcher
  45118. * @methodOf ui.router.util.$urlMatcherFactory
  45119. *
  45120. * @description
  45121. * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
  45122. *
  45123. * @param {Object} object The object to perform the type check against.
  45124. * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
  45125. * implementing all the same methods.
  45126. */
  45127. this.isMatcher = function (o) {
  45128. if (!isObject(o)) return false;
  45129. var result = true;
  45130. forEach(UrlMatcher.prototype, function(val, name) {
  45131. if (isFunction(val)) {
  45132. result = result && (isDefined(o[name]) && isFunction(o[name]));
  45133. }
  45134. });
  45135. return result;
  45136. };
  45137. /**
  45138. * @ngdoc function
  45139. * @name ui.router.util.$urlMatcherFactory#type
  45140. * @methodOf ui.router.util.$urlMatcherFactory
  45141. *
  45142. * @description
  45143. * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
  45144. * generate URLs with typed parameters.
  45145. *
  45146. * @param {string} name The type name.
  45147. * @param {Object|Function} definition The type definition. See
  45148. * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  45149. * @param {Object|Function} definitionFn (optional) A function that is injected before the app
  45150. * runtime starts. The result of this function is merged into the existing `definition`.
  45151. * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  45152. *
  45153. * @returns {Object} Returns `$urlMatcherFactoryProvider`.
  45154. *
  45155. * @example
  45156. * This is a simple example of a custom type that encodes and decodes items from an
  45157. * array, using the array index as the URL-encoded value:
  45158. *
  45159. * <pre>
  45160. * var list = ['John', 'Paul', 'George', 'Ringo'];
  45161. *
  45162. * $urlMatcherFactoryProvider.type('listItem', {
  45163. * encode: function(item) {
  45164. * // Represent the list item in the URL using its corresponding index
  45165. * return list.indexOf(item);
  45166. * },
  45167. * decode: function(item) {
  45168. * // Look up the list item by index
  45169. * return list[parseInt(item, 10)];
  45170. * },
  45171. * is: function(item) {
  45172. * // Ensure the item is valid by checking to see that it appears
  45173. * // in the list
  45174. * return list.indexOf(item) > -1;
  45175. * }
  45176. * });
  45177. *
  45178. * $stateProvider.state('list', {
  45179. * url: "/list/{item:listItem}",
  45180. * controller: function($scope, $stateParams) {
  45181. * console.log($stateParams.item);
  45182. * }
  45183. * });
  45184. *
  45185. * // ...
  45186. *
  45187. * // Changes URL to '/list/3', logs "Ringo" to the console
  45188. * $state.go('list', { item: "Ringo" });
  45189. * </pre>
  45190. *
  45191. * This is a more complex example of a type that relies on dependency injection to
  45192. * interact with services, and uses the parameter name from the URL to infer how to
  45193. * handle encoding and decoding parameter values:
  45194. *
  45195. * <pre>
  45196. * // Defines a custom type that gets a value from a service,
  45197. * // where each service gets different types of values from
  45198. * // a backend API:
  45199. * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
  45200. *
  45201. * // Matches up services to URL parameter names
  45202. * var services = {
  45203. * user: Users,
  45204. * post: Posts
  45205. * };
  45206. *
  45207. * return {
  45208. * encode: function(object) {
  45209. * // Represent the object in the URL using its unique ID
  45210. * return object.id;
  45211. * },
  45212. * decode: function(value, key) {
  45213. * // Look up the object by ID, using the parameter
  45214. * // name (key) to call the correct service
  45215. * return services[key].findById(value);
  45216. * },
  45217. * is: function(object, key) {
  45218. * // Check that object is a valid dbObject
  45219. * return angular.isObject(object) && object.id && services[key];
  45220. * }
  45221. * equals: function(a, b) {
  45222. * // Check the equality of decoded objects by comparing
  45223. * // their unique IDs
  45224. * return a.id === b.id;
  45225. * }
  45226. * };
  45227. * });
  45228. *
  45229. * // In a config() block, you can then attach URLs with
  45230. * // type-annotated parameters:
  45231. * $stateProvider.state('users', {
  45232. * url: "/users",
  45233. * // ...
  45234. * }).state('users.item', {
  45235. * url: "/{user:dbObject}",
  45236. * controller: function($scope, $stateParams) {
  45237. * // $stateParams.user will now be an object returned from
  45238. * // the Users service
  45239. * },
  45240. * // ...
  45241. * });
  45242. * </pre>
  45243. */
  45244. this.type = function (name, definition, definitionFn) {
  45245. if (!isDefined(definition)) return $types[name];
  45246. if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
  45247. $types[name] = new Type(extend({ name: name }, definition));
  45248. if (definitionFn) {
  45249. typeQueue.push({ name: name, def: definitionFn });
  45250. if (!enqueue) flushTypeQueue();
  45251. }
  45252. return this;
  45253. };
  45254. // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
  45255. function flushTypeQueue() {
  45256. while(typeQueue.length) {
  45257. var type = typeQueue.shift();
  45258. if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
  45259. angular.extend($types[type.name], injector.invoke(type.def));
  45260. }
  45261. }
  45262. // Register default types. Store them in the prototype of $types.
  45263. forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
  45264. $types = inherit($types, {});
  45265. /* No need to document $get, since it returns this */
  45266. this.$get = ['$injector', function ($injector) {
  45267. injector = $injector;
  45268. enqueue = false;
  45269. flushTypeQueue();
  45270. forEach(defaultTypes, function(type, name) {
  45271. if (!$types[name]) $types[name] = new Type(type);
  45272. });
  45273. return this;
  45274. }];
  45275. this.Param = function Param(id, type, config, location) {
  45276. var self = this;
  45277. config = unwrapShorthand(config);
  45278. type = getType(config, type, location);
  45279. var arrayMode = getArrayMode();
  45280. type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
  45281. if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
  45282. config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
  45283. var isOptional = config.value !== undefined;
  45284. var squash = getSquashPolicy(config, isOptional);
  45285. var replace = getReplace(config, arrayMode, isOptional, squash);
  45286. function unwrapShorthand(config) {
  45287. var keys = isObject(config) ? objectKeys(config) : [];
  45288. var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
  45289. indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
  45290. if (isShorthand) config = { value: config };
  45291. config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
  45292. return config;
  45293. }
  45294. function getType(config, urlType, location) {
  45295. if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
  45296. if (urlType) return urlType;
  45297. if (!config.type) return (location === "config" ? $types.any : $types.string);
  45298. return config.type instanceof Type ? config.type : new Type(config.type);
  45299. }
  45300. // array config: param name (param[]) overrides default settings. explicit config overrides param name.
  45301. function getArrayMode() {
  45302. var arrayDefaults = { array: (location === "search" ? "auto" : false) };
  45303. var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
  45304. return extend(arrayDefaults, arrayParamNomenclature, config).array;
  45305. }
  45306. /**
  45307. * returns false, true, or the squash value to indicate the "default parameter url squash policy".
  45308. */
  45309. function getSquashPolicy(config, isOptional) {
  45310. var squash = config.squash;
  45311. if (!isOptional || squash === false) return false;
  45312. if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
  45313. if (squash === true || isString(squash)) return squash;
  45314. throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
  45315. }
  45316. function getReplace(config, arrayMode, isOptional, squash) {
  45317. var replace, configuredKeys, defaultPolicy = [
  45318. { from: "", to: (isOptional || arrayMode ? undefined : "") },
  45319. { from: null, to: (isOptional || arrayMode ? undefined : "") }
  45320. ];
  45321. replace = isArray(config.replace) ? config.replace : [];
  45322. if (isString(squash))
  45323. replace.push({ from: squash, to: undefined });
  45324. configuredKeys = map(replace, function(item) { return item.from; } );
  45325. return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
  45326. }
  45327. /**
  45328. * [Internal] Get the default value of a parameter, which may be an injectable function.
  45329. */
  45330. function $$getDefaultValue() {
  45331. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  45332. return injector.invoke(config.$$fn);
  45333. }
  45334. /**
  45335. * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
  45336. * default value, which may be the result of an injectable function.
  45337. */
  45338. function $value(value) {
  45339. function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
  45340. function $replace(value) {
  45341. var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
  45342. return replacement.length ? replacement[0] : value;
  45343. }
  45344. value = $replace(value);
  45345. return isDefined(value) ? self.type.decode(value) : $$getDefaultValue();
  45346. }
  45347. function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
  45348. extend(this, {
  45349. id: id,
  45350. type: type,
  45351. location: location,
  45352. array: arrayMode,
  45353. squash: squash,
  45354. replace: replace,
  45355. isOptional: isOptional,
  45356. value: $value,
  45357. dynamic: undefined,
  45358. config: config,
  45359. toString: toString
  45360. });
  45361. };
  45362. function ParamSet(params) {
  45363. extend(this, params || {});
  45364. }
  45365. ParamSet.prototype = {
  45366. $$new: function() {
  45367. return inherit(this, extend(new ParamSet(), { $$parent: this}));
  45368. },
  45369. $$keys: function () {
  45370. var keys = [], chain = [], parent = this,
  45371. ignore = objectKeys(ParamSet.prototype);
  45372. while (parent) { chain.push(parent); parent = parent.$$parent; }
  45373. chain.reverse();
  45374. forEach(chain, function(paramset) {
  45375. forEach(objectKeys(paramset), function(key) {
  45376. if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
  45377. });
  45378. });
  45379. return keys;
  45380. },
  45381. $$values: function(paramValues) {
  45382. var values = {}, self = this;
  45383. forEach(self.$$keys(), function(key) {
  45384. values[key] = self[key].value(paramValues && paramValues[key]);
  45385. });
  45386. return values;
  45387. },
  45388. $$equals: function(paramValues1, paramValues2) {
  45389. var equal = true, self = this;
  45390. forEach(self.$$keys(), function(key) {
  45391. var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
  45392. if (!self[key].type.equals(left, right)) equal = false;
  45393. });
  45394. return equal;
  45395. },
  45396. $$validates: function $$validate(paramValues) {
  45397. var result = true, isOptional, val, param, self = this;
  45398. forEach(this.$$keys(), function(key) {
  45399. param = self[key];
  45400. val = paramValues[key];
  45401. isOptional = !val && param.isOptional;
  45402. result = result && (isOptional || !!param.type.is(val));
  45403. });
  45404. return result;
  45405. },
  45406. $$parent: undefined
  45407. };
  45408. this.ParamSet = ParamSet;
  45409. }
  45410. // Register as a provider so it's available to other providers
  45411. angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
  45412. angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
  45413. /**
  45414. * @ngdoc object
  45415. * @name ui.router.router.$urlRouterProvider
  45416. *
  45417. * @requires ui.router.util.$urlMatcherFactoryProvider
  45418. * @requires $locationProvider
  45419. *
  45420. * @description
  45421. * `$urlRouterProvider` has the responsibility of watching `$location`.
  45422. * When `$location` changes it runs through a list of rules one by one until a
  45423. * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
  45424. * a url in a state configuration. All urls are compiled into a UrlMatcher object.
  45425. *
  45426. * There are several methods on `$urlRouterProvider` that make it useful to use directly
  45427. * in your module config.
  45428. */
  45429. $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
  45430. function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
  45431. var rules = [], otherwise = null, interceptDeferred = false, listener;
  45432. // Returns a string that is a prefix of all strings matching the RegExp
  45433. function regExpPrefix(re) {
  45434. var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
  45435. return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  45436. }
  45437. // Interpolates matched values into a String.replace()-style pattern
  45438. function interpolate(pattern, match) {
  45439. return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
  45440. return match[what === '$' ? 0 : Number(what)];
  45441. });
  45442. }
  45443. /**
  45444. * @ngdoc function
  45445. * @name ui.router.router.$urlRouterProvider#rule
  45446. * @methodOf ui.router.router.$urlRouterProvider
  45447. *
  45448. * @description
  45449. * Defines rules that are used by `$urlRouterProvider` to find matches for
  45450. * specific URLs.
  45451. *
  45452. * @example
  45453. * <pre>
  45454. * var app = angular.module('app', ['ui.router.router']);
  45455. *
  45456. * app.config(function ($urlRouterProvider) {
  45457. * // Here's an example of how you might allow case insensitive urls
  45458. * $urlRouterProvider.rule(function ($injector, $location) {
  45459. * var path = $location.path(),
  45460. * normalized = path.toLowerCase();
  45461. *
  45462. * if (path !== normalized) {
  45463. * return normalized;
  45464. * }
  45465. * });
  45466. * });
  45467. * </pre>
  45468. *
  45469. * @param {object} rule Handler function that takes `$injector` and `$location`
  45470. * services as arguments. You can use them to return a valid path as a string.
  45471. *
  45472. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  45473. */
  45474. this.rule = function (rule) {
  45475. if (!isFunction(rule)) throw new Error("'rule' must be a function");
  45476. rules.push(rule);
  45477. return this;
  45478. };
  45479. /**
  45480. * @ngdoc object
  45481. * @name ui.router.router.$urlRouterProvider#otherwise
  45482. * @methodOf ui.router.router.$urlRouterProvider
  45483. *
  45484. * @description
  45485. * Defines a path that is used when an invalid route is requested.
  45486. *
  45487. * @example
  45488. * <pre>
  45489. * var app = angular.module('app', ['ui.router.router']);
  45490. *
  45491. * app.config(function ($urlRouterProvider) {
  45492. * // if the path doesn't match any of the urls you configured
  45493. * // otherwise will take care of routing the user to the
  45494. * // specified url
  45495. * $urlRouterProvider.otherwise('/index');
  45496. *
  45497. * // Example of using function rule as param
  45498. * $urlRouterProvider.otherwise(function ($injector, $location) {
  45499. * return '/a/valid/url';
  45500. * });
  45501. * });
  45502. * </pre>
  45503. *
  45504. * @param {string|object} rule The url path you want to redirect to or a function
  45505. * rule that returns the url path. The function version is passed two params:
  45506. * `$injector` and `$location` services, and must return a url string.
  45507. *
  45508. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  45509. */
  45510. this.otherwise = function (rule) {
  45511. if (isString(rule)) {
  45512. var redirect = rule;
  45513. rule = function () { return redirect; };
  45514. }
  45515. else if (!isFunction(rule)) throw new Error("'rule' must be a function");
  45516. otherwise = rule;
  45517. return this;
  45518. };
  45519. function handleIfMatch($injector, handler, match) {
  45520. if (!match) return false;
  45521. var result = $injector.invoke(handler, handler, { $match: match });
  45522. return isDefined(result) ? result : true;
  45523. }
  45524. /**
  45525. * @ngdoc function
  45526. * @name ui.router.router.$urlRouterProvider#when
  45527. * @methodOf ui.router.router.$urlRouterProvider
  45528. *
  45529. * @description
  45530. * Registers a handler for a given url matching. if handle is a string, it is
  45531. * treated as a redirect, and is interpolated according to the syntax of match
  45532. * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
  45533. *
  45534. * If the handler is a function, it is injectable. It gets invoked if `$location`
  45535. * matches. You have the option of inject the match object as `$match`.
  45536. *
  45537. * The handler can return
  45538. *
  45539. * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
  45540. * will continue trying to find another one that matches.
  45541. * - **string** which is treated as a redirect and passed to `$location.url()`
  45542. * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
  45543. *
  45544. * @example
  45545. * <pre>
  45546. * var app = angular.module('app', ['ui.router.router']);
  45547. *
  45548. * app.config(function ($urlRouterProvider) {
  45549. * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
  45550. * if ($state.$current.navigable !== state ||
  45551. * !equalForKeys($match, $stateParams) {
  45552. * $state.transitionTo(state, $match, false);
  45553. * }
  45554. * });
  45555. * });
  45556. * </pre>
  45557. *
  45558. * @param {string|object} what The incoming path that you want to redirect.
  45559. * @param {string|object} handler The path you want to redirect your user to.
  45560. */
  45561. this.when = function (what, handler) {
  45562. var redirect, handlerIsString = isString(handler);
  45563. if (isString(what)) what = $urlMatcherFactory.compile(what);
  45564. if (!handlerIsString && !isFunction(handler) && !isArray(handler))
  45565. throw new Error("invalid 'handler' in when()");
  45566. var strategies = {
  45567. matcher: function (what, handler) {
  45568. if (handlerIsString) {
  45569. redirect = $urlMatcherFactory.compile(handler);
  45570. handler = ['$match', function ($match) { return redirect.format($match); }];
  45571. }
  45572. return extend(function ($injector, $location) {
  45573. return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
  45574. }, {
  45575. prefix: isString(what.prefix) ? what.prefix : ''
  45576. });
  45577. },
  45578. regex: function (what, handler) {
  45579. if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
  45580. if (handlerIsString) {
  45581. redirect = handler;
  45582. handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
  45583. }
  45584. return extend(function ($injector, $location) {
  45585. return handleIfMatch($injector, handler, what.exec($location.path()));
  45586. }, {
  45587. prefix: regExpPrefix(what)
  45588. });
  45589. }
  45590. };
  45591. var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
  45592. for (var n in check) {
  45593. if (check[n]) return this.rule(strategies[n](what, handler));
  45594. }
  45595. throw new Error("invalid 'what' in when()");
  45596. };
  45597. /**
  45598. * @ngdoc function
  45599. * @name ui.router.router.$urlRouterProvider#deferIntercept
  45600. * @methodOf ui.router.router.$urlRouterProvider
  45601. *
  45602. * @description
  45603. * Disables (or enables) deferring location change interception.
  45604. *
  45605. * If you wish to customize the behavior of syncing the URL (for example, if you wish to
  45606. * defer a transition but maintain the current URL), call this method at configuration time.
  45607. * Then, at run time, call `$urlRouter.listen()` after you have configured your own
  45608. * `$locationChangeSuccess` event handler.
  45609. *
  45610. * @example
  45611. * <pre>
  45612. * var app = angular.module('app', ['ui.router.router']);
  45613. *
  45614. * app.config(function ($urlRouterProvider) {
  45615. *
  45616. * // Prevent $urlRouter from automatically intercepting URL changes;
  45617. * // this allows you to configure custom behavior in between
  45618. * // location changes and route synchronization:
  45619. * $urlRouterProvider.deferIntercept();
  45620. *
  45621. * }).run(function ($rootScope, $urlRouter, UserService) {
  45622. *
  45623. * $rootScope.$on('$locationChangeSuccess', function(e) {
  45624. * // UserService is an example service for managing user state
  45625. * if (UserService.isLoggedIn()) return;
  45626. *
  45627. * // Prevent $urlRouter's default handler from firing
  45628. * e.preventDefault();
  45629. *
  45630. * UserService.handleLogin().then(function() {
  45631. * // Once the user has logged in, sync the current URL
  45632. * // to the router:
  45633. * $urlRouter.sync();
  45634. * });
  45635. * });
  45636. *
  45637. * // Configures $urlRouter's listener *after* your custom listener
  45638. * $urlRouter.listen();
  45639. * });
  45640. * </pre>
  45641. *
  45642. * @param {boolean} defer Indicates whether to defer location change interception. Passing
  45643. no parameter is equivalent to `true`.
  45644. */
  45645. this.deferIntercept = function (defer) {
  45646. if (defer === undefined) defer = true;
  45647. interceptDeferred = defer;
  45648. };
  45649. /**
  45650. * @ngdoc object
  45651. * @name ui.router.router.$urlRouter
  45652. *
  45653. * @requires $location
  45654. * @requires $rootScope
  45655. * @requires $injector
  45656. * @requires $browser
  45657. *
  45658. * @description
  45659. *
  45660. */
  45661. this.$get = $get;
  45662. $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
  45663. function $get( $location, $rootScope, $injector, $browser) {
  45664. var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
  45665. function appendBasePath(url, isHtml5, absolute) {
  45666. if (baseHref === '/') return url;
  45667. if (isHtml5) return baseHref.slice(0, -1) + url;
  45668. if (absolute) return baseHref.slice(1) + url;
  45669. return url;
  45670. }
  45671. // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
  45672. function update(evt) {
  45673. if (evt && evt.defaultPrevented) return;
  45674. var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
  45675. lastPushedUrl = undefined;
  45676. if (ignoreUpdate) return true;
  45677. function check(rule) {
  45678. var handled = rule($injector, $location);
  45679. if (!handled) return false;
  45680. if (isString(handled)) $location.replace().url(handled);
  45681. return true;
  45682. }
  45683. var n = rules.length, i;
  45684. for (i = 0; i < n; i++) {
  45685. if (check(rules[i])) return;
  45686. }
  45687. // always check otherwise last to allow dynamic updates to the set of rules
  45688. if (otherwise) check(otherwise);
  45689. }
  45690. function listen() {
  45691. listener = listener || $rootScope.$on('$locationChangeSuccess', update);
  45692. return listener;
  45693. }
  45694. if (!interceptDeferred) listen();
  45695. return {
  45696. /**
  45697. * @ngdoc function
  45698. * @name ui.router.router.$urlRouter#sync
  45699. * @methodOf ui.router.router.$urlRouter
  45700. *
  45701. * @description
  45702. * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
  45703. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
  45704. * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
  45705. * with the transition by calling `$urlRouter.sync()`.
  45706. *
  45707. * @example
  45708. * <pre>
  45709. * angular.module('app', ['ui.router'])
  45710. * .run(function($rootScope, $urlRouter) {
  45711. * $rootScope.$on('$locationChangeSuccess', function(evt) {
  45712. * // Halt state change from even starting
  45713. * evt.preventDefault();
  45714. * // Perform custom logic
  45715. * var meetsRequirement = ...
  45716. * // Continue with the update and state transition if logic allows
  45717. * if (meetsRequirement) $urlRouter.sync();
  45718. * });
  45719. * });
  45720. * </pre>
  45721. */
  45722. sync: function() {
  45723. update();
  45724. },
  45725. listen: function() {
  45726. return listen();
  45727. },
  45728. update: function(read) {
  45729. if (read) {
  45730. location = $location.url();
  45731. return;
  45732. }
  45733. if ($location.url() === location) return;
  45734. $location.url(location);
  45735. $location.replace();
  45736. },
  45737. push: function(urlMatcher, params, options) {
  45738. $location.url(urlMatcher.format(params || {}));
  45739. lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
  45740. if (options && options.replace) $location.replace();
  45741. },
  45742. /**
  45743. * @ngdoc function
  45744. * @name ui.router.router.$urlRouter#href
  45745. * @methodOf ui.router.router.$urlRouter
  45746. *
  45747. * @description
  45748. * A URL generation method that returns the compiled URL for a given
  45749. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
  45750. *
  45751. * @example
  45752. * <pre>
  45753. * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
  45754. * person: "bob"
  45755. * });
  45756. * // $bob == "/about/bob";
  45757. * </pre>
  45758. *
  45759. * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
  45760. * @param {object=} params An object of parameter values to fill the matcher's required parameters.
  45761. * @param {object=} options Options object. The options are:
  45762. *
  45763. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  45764. *
  45765. * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
  45766. */
  45767. href: function(urlMatcher, params, options) {
  45768. if (!urlMatcher.validates(params)) return null;
  45769. var isHtml5 = $locationProvider.html5Mode();
  45770. if (angular.isObject(isHtml5)) {
  45771. isHtml5 = isHtml5.enabled;
  45772. }
  45773. var url = urlMatcher.format(params);
  45774. options = options || {};
  45775. if (!isHtml5 && url !== null) {
  45776. url = "#" + $locationProvider.hashPrefix() + url;
  45777. }
  45778. url = appendBasePath(url, isHtml5, options.absolute);
  45779. if (!options.absolute || !url) {
  45780. return url;
  45781. }
  45782. var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
  45783. port = (port === 80 || port === 443 ? '' : ':' + port);
  45784. return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
  45785. }
  45786. };
  45787. }
  45788. }
  45789. angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
  45790. /**
  45791. * @ngdoc object
  45792. * @name ui.router.state.$stateProvider
  45793. *
  45794. * @requires ui.router.router.$urlRouterProvider
  45795. * @requires ui.router.util.$urlMatcherFactoryProvider
  45796. *
  45797. * @description
  45798. * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
  45799. * on state.
  45800. *
  45801. * A state corresponds to a "place" in the application in terms of the overall UI and
  45802. * navigation. A state describes (via the controller / template / view properties) what
  45803. * the UI looks like and does at that place.
  45804. *
  45805. * States often have things in common, and the primary way of factoring out these
  45806. * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
  45807. * nested states.
  45808. *
  45809. * The `$stateProvider` provides interfaces to declare these states for your app.
  45810. */
  45811. $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
  45812. function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
  45813. var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
  45814. // Builds state properties from definition passed to registerState()
  45815. var stateBuilder = {
  45816. // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
  45817. // state.children = [];
  45818. // if (parent) parent.children.push(state);
  45819. parent: function(state) {
  45820. if (isDefined(state.parent) && state.parent) return findState(state.parent);
  45821. // regex matches any valid composite state name
  45822. // would match "contact.list" but not "contacts"
  45823. var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
  45824. return compositeName ? findState(compositeName[1]) : root;
  45825. },
  45826. // inherit 'data' from parent and override by own values (if any)
  45827. data: function(state) {
  45828. if (state.parent && state.parent.data) {
  45829. state.data = state.self.data = extend({}, state.parent.data, state.data);
  45830. }
  45831. return state.data;
  45832. },
  45833. // Build a URLMatcher if necessary, either via a relative or absolute URL
  45834. url: function(state) {
  45835. var url = state.url, config = { params: state.params || {} };
  45836. if (isString(url)) {
  45837. if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
  45838. return (state.parent.navigable || root).url.concat(url, config);
  45839. }
  45840. if (!url || $urlMatcherFactory.isMatcher(url)) return url;
  45841. throw new Error("Invalid url '" + url + "' in state '" + state + "'");
  45842. },
  45843. // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
  45844. navigable: function(state) {
  45845. return state.url ? state : (state.parent ? state.parent.navigable : null);
  45846. },
  45847. // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
  45848. ownParams: function(state) {
  45849. var params = state.url && state.url.params || new $$UMFP.ParamSet();
  45850. forEach(state.params || {}, function(config, id) {
  45851. if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
  45852. });
  45853. return params;
  45854. },
  45855. // Derive parameters for this state and ensure they're a super-set of parent's parameters
  45856. params: function(state) {
  45857. return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
  45858. },
  45859. // If there is no explicit multi-view configuration, make one up so we don't have
  45860. // to handle both cases in the view directive later. Note that having an explicit
  45861. // 'views' property will mean the default unnamed view properties are ignored. This
  45862. // is also a good time to resolve view names to absolute names, so everything is a
  45863. // straight lookup at link time.
  45864. views: function(state) {
  45865. var views = {};
  45866. forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
  45867. if (name.indexOf('@') < 0) name += '@' + state.parent.name;
  45868. views[name] = view;
  45869. });
  45870. return views;
  45871. },
  45872. // Keep a full path from the root down to this state as this is needed for state activation.
  45873. path: function(state) {
  45874. return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
  45875. },
  45876. // Speed up $state.contains() as it's used a lot
  45877. includes: function(state) {
  45878. var includes = state.parent ? extend({}, state.parent.includes) : {};
  45879. includes[state.name] = true;
  45880. return includes;
  45881. },
  45882. $delegates: {}
  45883. };
  45884. function isRelative(stateName) {
  45885. return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
  45886. }
  45887. function findState(stateOrName, base) {
  45888. if (!stateOrName) return undefined;
  45889. var isStr = isString(stateOrName),
  45890. name = isStr ? stateOrName : stateOrName.name,
  45891. path = isRelative(name);
  45892. if (path) {
  45893. if (!base) throw new Error("No reference point given for path '" + name + "'");
  45894. base = findState(base);
  45895. var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
  45896. for (; i < pathLength; i++) {
  45897. if (rel[i] === "" && i === 0) {
  45898. current = base;
  45899. continue;
  45900. }
  45901. if (rel[i] === "^") {
  45902. if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
  45903. current = current.parent;
  45904. continue;
  45905. }
  45906. break;
  45907. }
  45908. rel = rel.slice(i).join(".");
  45909. name = current.name + (current.name && rel ? "." : "") + rel;
  45910. }
  45911. var state = states[name];
  45912. if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
  45913. return state;
  45914. }
  45915. return undefined;
  45916. }
  45917. function queueState(parentName, state) {
  45918. if (!queue[parentName]) {
  45919. queue[parentName] = [];
  45920. }
  45921. queue[parentName].push(state);
  45922. }
  45923. function flushQueuedChildren(parentName) {
  45924. var queued = queue[parentName] || [];
  45925. while(queued.length) {
  45926. registerState(queued.shift());
  45927. }
  45928. }
  45929. function registerState(state) {
  45930. // Wrap a new object around the state so we can store our private details easily.
  45931. state = inherit(state, {
  45932. self: state,
  45933. resolve: state.resolve || {},
  45934. toString: function() { return this.name; }
  45935. });
  45936. var name = state.name;
  45937. if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
  45938. if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
  45939. // Get parent name
  45940. var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
  45941. : (isString(state.parent)) ? state.parent
  45942. : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
  45943. : '';
  45944. // If parent is not registered yet, add state to queue and register later
  45945. if (parentName && !states[parentName]) {
  45946. return queueState(parentName, state.self);
  45947. }
  45948. for (var key in stateBuilder) {
  45949. if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
  45950. }
  45951. states[name] = state;
  45952. // Register the state in the global state list and with $urlRouter if necessary.
  45953. if (!state[abstractKey] && state.url) {
  45954. $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
  45955. if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
  45956. $state.transitionTo(state, $match, { inherit: true, location: false });
  45957. }
  45958. }]);
  45959. }
  45960. // Register any queued children
  45961. flushQueuedChildren(name);
  45962. return state;
  45963. }
  45964. // Checks text to see if it looks like a glob.
  45965. function isGlob (text) {
  45966. return text.indexOf('*') > -1;
  45967. }
  45968. // Returns true if glob matches current $state name.
  45969. function doesStateMatchGlob (glob) {
  45970. var globSegments = glob.split('.'),
  45971. segments = $state.$current.name.split('.');
  45972. //match greedy starts
  45973. if (globSegments[0] === '**') {
  45974. segments = segments.slice(indexOf(segments, globSegments[1]));
  45975. segments.unshift('**');
  45976. }
  45977. //match greedy ends
  45978. if (globSegments[globSegments.length - 1] === '**') {
  45979. segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
  45980. segments.push('**');
  45981. }
  45982. if (globSegments.length != segments.length) {
  45983. return false;
  45984. }
  45985. //match single stars
  45986. for (var i = 0, l = globSegments.length; i < l; i++) {
  45987. if (globSegments[i] === '*') {
  45988. segments[i] = '*';
  45989. }
  45990. }
  45991. return segments.join('') === globSegments.join('');
  45992. }
  45993. // Implicit root state that is always active
  45994. root = registerState({
  45995. name: '',
  45996. url: '^',
  45997. views: null,
  45998. 'abstract': true
  45999. });
  46000. root.navigable = null;
  46001. /**
  46002. * @ngdoc function
  46003. * @name ui.router.state.$stateProvider#decorator
  46004. * @methodOf ui.router.state.$stateProvider
  46005. *
  46006. * @description
  46007. * Allows you to extend (carefully) or override (at your own peril) the
  46008. * `stateBuilder` object used internally by `$stateProvider`. This can be used
  46009. * to add custom functionality to ui-router, for example inferring templateUrl
  46010. * based on the state name.
  46011. *
  46012. * When passing only a name, it returns the current (original or decorated) builder
  46013. * function that matches `name`.
  46014. *
  46015. * The builder functions that can be decorated are listed below. Though not all
  46016. * necessarily have a good use case for decoration, that is up to you to decide.
  46017. *
  46018. * In addition, users can attach custom decorators, which will generate new
  46019. * properties within the state's internal definition. There is currently no clear
  46020. * use-case for this beyond accessing internal states (i.e. $state.$current),
  46021. * however, expect this to become increasingly relevant as we introduce additional
  46022. * meta-programming features.
  46023. *
  46024. * **Warning**: Decorators should not be interdependent because the order of
  46025. * execution of the builder functions in non-deterministic. Builder functions
  46026. * should only be dependent on the state definition object and super function.
  46027. *
  46028. *
  46029. * Existing builder functions and current return values:
  46030. *
  46031. * - **parent** `{object}` - returns the parent state object.
  46032. * - **data** `{object}` - returns state data, including any inherited data that is not
  46033. * overridden by own values (if any).
  46034. * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
  46035. * or `null`.
  46036. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
  46037. * navigable).
  46038. * - **params** `{object}` - returns an array of state params that are ensured to
  46039. * be a super-set of parent's params.
  46040. * - **views** `{object}` - returns a views object where each key is an absolute view
  46041. * name (i.e. "viewName@stateName") and each value is the config object
  46042. * (template, controller) for the view. Even when you don't use the views object
  46043. * explicitly on a state config, one is still created for you internally.
  46044. * So by decorating this builder function you have access to decorating template
  46045. * and controller properties.
  46046. * - **ownParams** `{object}` - returns an array of params that belong to the state,
  46047. * not including any params defined by ancestor states.
  46048. * - **path** `{string}` - returns the full path from the root down to this state.
  46049. * Needed for state activation.
  46050. * - **includes** `{object}` - returns an object that includes every state that
  46051. * would pass a `$state.includes()` test.
  46052. *
  46053. * @example
  46054. * <pre>
  46055. * // Override the internal 'views' builder with a function that takes the state
  46056. * // definition, and a reference to the internal function being overridden:
  46057. * $stateProvider.decorator('views', function (state, parent) {
  46058. * var result = {},
  46059. * views = parent(state);
  46060. *
  46061. * angular.forEach(views, function (config, name) {
  46062. * var autoName = (state.name + '.' + name).replace('.', '/');
  46063. * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
  46064. * result[name] = config;
  46065. * });
  46066. * return result;
  46067. * });
  46068. *
  46069. * $stateProvider.state('home', {
  46070. * views: {
  46071. * 'contact.list': { controller: 'ListController' },
  46072. * 'contact.item': { controller: 'ItemController' }
  46073. * }
  46074. * });
  46075. *
  46076. * // ...
  46077. *
  46078. * $state.go('home');
  46079. * // Auto-populates list and item views with /partials/home/contact/list.html,
  46080. * // and /partials/home/contact/item.html, respectively.
  46081. * </pre>
  46082. *
  46083. * @param {string} name The name of the builder function to decorate.
  46084. * @param {object} func A function that is responsible for decorating the original
  46085. * builder function. The function receives two parameters:
  46086. *
  46087. * - `{object}` - state - The state config object.
  46088. * - `{object}` - super - The original builder function.
  46089. *
  46090. * @return {object} $stateProvider - $stateProvider instance
  46091. */
  46092. this.decorator = decorator;
  46093. function decorator(name, func) {
  46094. /*jshint validthis: true */
  46095. if (isString(name) && !isDefined(func)) {
  46096. return stateBuilder[name];
  46097. }
  46098. if (!isFunction(func) || !isString(name)) {
  46099. return this;
  46100. }
  46101. if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
  46102. stateBuilder.$delegates[name] = stateBuilder[name];
  46103. }
  46104. stateBuilder[name] = func;
  46105. return this;
  46106. }
  46107. /**
  46108. * @ngdoc function
  46109. * @name ui.router.state.$stateProvider#state
  46110. * @methodOf ui.router.state.$stateProvider
  46111. *
  46112. * @description
  46113. * Registers a state configuration under a given state name. The stateConfig object
  46114. * has the following acceptable properties.
  46115. *
  46116. * @param {string} name A unique state name, e.g. "home", "about", "contacts".
  46117. * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
  46118. * @param {object} stateConfig State configuration object.
  46119. * @param {string|function=} stateConfig.template
  46120. * <a id='template'></a>
  46121. * html template as a string or a function that returns
  46122. * an html template as a string which should be used by the uiView directives. This property
  46123. * takes precedence over templateUrl.
  46124. *
  46125. * If `template` is a function, it will be called with the following parameters:
  46126. *
  46127. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  46128. * applying the current state
  46129. *
  46130. * <pre>template:
  46131. * "<h1>inline template definition</h1>" +
  46132. * "<div ui-view></div>"</pre>
  46133. * <pre>template: function(params) {
  46134. * return "<h1>generated template</h1>"; }</pre>
  46135. * </div>
  46136. *
  46137. * @param {string|function=} stateConfig.templateUrl
  46138. * <a id='templateUrl'></a>
  46139. *
  46140. * path or function that returns a path to an html
  46141. * template that should be used by uiView.
  46142. *
  46143. * If `templateUrl` is a function, it will be called with the following parameters:
  46144. *
  46145. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  46146. * applying the current state
  46147. *
  46148. * <pre>templateUrl: "home.html"</pre>
  46149. * <pre>templateUrl: function(params) {
  46150. * return myTemplates[params.pageId]; }</pre>
  46151. *
  46152. * @param {function=} stateConfig.templateProvider
  46153. * <a id='templateProvider'></a>
  46154. * Provider function that returns HTML content string.
  46155. * <pre> templateProvider:
  46156. * function(MyTemplateService, params) {
  46157. * return MyTemplateService.getTemplate(params.pageId);
  46158. * }</pre>
  46159. *
  46160. * @param {string|function=} stateConfig.controller
  46161. * <a id='controller'></a>
  46162. *
  46163. * Controller fn that should be associated with newly
  46164. * related scope or the name of a registered controller if passed as a string.
  46165. * Optionally, the ControllerAs may be declared here.
  46166. * <pre>controller: "MyRegisteredController"</pre>
  46167. * <pre>controller:
  46168. * "MyRegisteredController as fooCtrl"}</pre>
  46169. * <pre>controller: function($scope, MyService) {
  46170. * $scope.data = MyService.getData(); }</pre>
  46171. *
  46172. * @param {function=} stateConfig.controllerProvider
  46173. * <a id='controllerProvider'></a>
  46174. *
  46175. * Injectable provider function that returns the actual controller or string.
  46176. * <pre>controllerProvider:
  46177. * function(MyResolveData) {
  46178. * if (MyResolveData.foo)
  46179. * return "FooCtrl"
  46180. * else if (MyResolveData.bar)
  46181. * return "BarCtrl";
  46182. * else return function($scope) {
  46183. * $scope.baz = "Qux";
  46184. * }
  46185. * }</pre>
  46186. *
  46187. * @param {string=} stateConfig.controllerAs
  46188. * <a id='controllerAs'></a>
  46189. *
  46190. * A controller alias name. If present the controller will be
  46191. * published to scope under the controllerAs name.
  46192. * <pre>controllerAs: "myCtrl"</pre>
  46193. *
  46194. * @param {object=} stateConfig.resolve
  46195. * <a id='resolve'></a>
  46196. *
  46197. * An optional map&lt;string, function&gt; of dependencies which
  46198. * should be injected into the controller. If any of these dependencies are promises,
  46199. * the router will wait for them all to be resolved before the controller is instantiated.
  46200. * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
  46201. * and the values of the resolved promises are injected into any controllers that reference them.
  46202. * If any of the promises are rejected the $stateChangeError event is fired.
  46203. *
  46204. * The map object is:
  46205. *
  46206. * - key - {string}: name of dependency to be injected into controller
  46207. * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
  46208. * it is injected and return value it treated as dependency. If result is a promise, it is
  46209. * resolved before its value is injected into controller.
  46210. *
  46211. * <pre>resolve: {
  46212. * myResolve1:
  46213. * function($http, $stateParams) {
  46214. * return $http.get("/api/foos/"+stateParams.fooID);
  46215. * }
  46216. * }</pre>
  46217. *
  46218. * @param {string=} stateConfig.url
  46219. * <a id='url'></a>
  46220. *
  46221. * A url fragment with optional parameters. When a state is navigated or
  46222. * transitioned to, the `$stateParams` service will be populated with any
  46223. * parameters that were passed.
  46224. *
  46225. * examples:
  46226. * <pre>url: "/home"
  46227. * url: "/users/:userid"
  46228. * url: "/books/{bookid:[a-zA-Z_-]}"
  46229. * url: "/books/{categoryid:int}"
  46230. * url: "/books/{publishername:string}/{categoryid:int}"
  46231. * url: "/messages?before&after"
  46232. * url: "/messages?{before:date}&{after:date}"</pre>
  46233. * url: "/messages/:mailboxid?{before:date}&{after:date}"
  46234. *
  46235. * @param {object=} stateConfig.views
  46236. * <a id='views'></a>
  46237. * an optional map&lt;string, object&gt; which defined multiple views, or targets views
  46238. * manually/explicitly.
  46239. *
  46240. * Examples:
  46241. *
  46242. * Targets three named `ui-view`s in the parent state's template
  46243. * <pre>views: {
  46244. * header: {
  46245. * controller: "headerCtrl",
  46246. * templateUrl: "header.html"
  46247. * }, body: {
  46248. * controller: "bodyCtrl",
  46249. * templateUrl: "body.html"
  46250. * }, footer: {
  46251. * controller: "footCtrl",
  46252. * templateUrl: "footer.html"
  46253. * }
  46254. * }</pre>
  46255. *
  46256. * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
  46257. * <pre>views: {
  46258. * 'header@top': {
  46259. * controller: "msgHeaderCtrl",
  46260. * templateUrl: "msgHeader.html"
  46261. * }, 'body': {
  46262. * controller: "messagesCtrl",
  46263. * templateUrl: "messages.html"
  46264. * }
  46265. * }</pre>
  46266. *
  46267. * @param {boolean=} [stateConfig.abstract=false]
  46268. * <a id='abstract'></a>
  46269. * An abstract state will never be directly activated,
  46270. * but can provide inherited properties to its common children states.
  46271. * <pre>abstract: true</pre>
  46272. *
  46273. * @param {function=} stateConfig.onEnter
  46274. * <a id='onEnter'></a>
  46275. *
  46276. * Callback function for when a state is entered. Good way
  46277. * to trigger an action or dispatch an event, such as opening a dialog.
  46278. * If minifying your scripts, make sure to explictly annotate this function,
  46279. * because it won't be automatically annotated by your build tools.
  46280. *
  46281. * <pre>onEnter: function(MyService, $stateParams) {
  46282. * MyService.foo($stateParams.myParam);
  46283. * }</pre>
  46284. *
  46285. * @param {function=} stateConfig.onExit
  46286. * <a id='onExit'></a>
  46287. *
  46288. * Callback function for when a state is exited. Good way to
  46289. * trigger an action or dispatch an event, such as opening a dialog.
  46290. * If minifying your scripts, make sure to explictly annotate this function,
  46291. * because it won't be automatically annotated by your build tools.
  46292. *
  46293. * <pre>onExit: function(MyService, $stateParams) {
  46294. * MyService.cleanup($stateParams.myParam);
  46295. * }</pre>
  46296. *
  46297. * @param {boolean=} [stateConfig.reloadOnSearch=true]
  46298. * <a id='reloadOnSearch'></a>
  46299. *
  46300. * If `false`, will not retrigger the same state
  46301. * just because a search/query parameter has changed (via $location.search() or $location.hash()).
  46302. * Useful for when you'd like to modify $location.search() without triggering a reload.
  46303. * <pre>reloadOnSearch: false</pre>
  46304. *
  46305. * @param {object=} stateConfig.data
  46306. * <a id='data'></a>
  46307. *
  46308. * Arbitrary data object, useful for custom configuration. The parent state's `data` is
  46309. * prototypally inherited. In other words, adding a data property to a state adds it to
  46310. * the entire subtree via prototypal inheritance.
  46311. *
  46312. * <pre>data: {
  46313. * requiredRole: 'foo'
  46314. * } </pre>
  46315. *
  46316. * @param {object=} stateConfig.params
  46317. * <a id='params'></a>
  46318. *
  46319. * A map which optionally configures parameters declared in the `url`, or
  46320. * defines additional non-url parameters. For each parameter being
  46321. * configured, add a configuration object keyed to the name of the parameter.
  46322. *
  46323. * Each parameter configuration object may contain the following properties:
  46324. *
  46325. * - ** value ** - {object|function=}: specifies the default value for this
  46326. * parameter. This implicitly sets this parameter as optional.
  46327. *
  46328. * When UI-Router routes to a state and no value is
  46329. * specified for this parameter in the URL or transition, the
  46330. * default value will be used instead. If `value` is a function,
  46331. * it will be injected and invoked, and the return value used.
  46332. *
  46333. * *Note*: `undefined` is treated as "no default value" while `null`
  46334. * is treated as "the default value is `null`".
  46335. *
  46336. * *Shorthand*: If you only need to configure the default value of the
  46337. * parameter, you may use a shorthand syntax. In the **`params`**
  46338. * map, instead mapping the param name to a full parameter configuration
  46339. * object, simply set map it to the default parameter value, e.g.:
  46340. *
  46341. * <pre>// define a parameter's default value
  46342. * params: {
  46343. * param1: { value: "defaultValue" }
  46344. * }
  46345. * // shorthand default values
  46346. * params: {
  46347. * param1: "defaultValue",
  46348. * param2: "param2Default"
  46349. * }</pre>
  46350. *
  46351. * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
  46352. * treated as an array of values. If you specified a Type, the value will be
  46353. * treated as an array of the specified Type. Note: query parameter values
  46354. * default to a special `"auto"` mode.
  46355. *
  46356. * For query parameters in `"auto"` mode, if multiple values for a single parameter
  46357. * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
  46358. * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
  46359. * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
  46360. * value (e.g.: `{ foo: '1' }`).
  46361. *
  46362. * <pre>params: {
  46363. * param1: { array: true }
  46364. * }</pre>
  46365. *
  46366. * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
  46367. * the current parameter value is the same as the default value. If `squash` is not set, it uses the
  46368. * configured default squash policy.
  46369. * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
  46370. *
  46371. * There are three squash settings:
  46372. *
  46373. * - false: The parameter's default value is not squashed. It is encoded and included in the URL
  46374. * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
  46375. * by slashes in the state's `url` declaration, then one of those slashes are omitted.
  46376. * This can allow for cleaner looking URLs.
  46377. * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
  46378. *
  46379. * <pre>params: {
  46380. * param1: {
  46381. * value: "defaultId",
  46382. * squash: true
  46383. * } }
  46384. * // squash "defaultValue" to "~"
  46385. * params: {
  46386. * param1: {
  46387. * value: "defaultValue",
  46388. * squash: "~"
  46389. * } }
  46390. * </pre>
  46391. *
  46392. *
  46393. * @example
  46394. * <pre>
  46395. * // Some state name examples
  46396. *
  46397. * // stateName can be a single top-level name (must be unique).
  46398. * $stateProvider.state("home", {});
  46399. *
  46400. * // Or it can be a nested state name. This state is a child of the
  46401. * // above "home" state.
  46402. * $stateProvider.state("home.newest", {});
  46403. *
  46404. * // Nest states as deeply as needed.
  46405. * $stateProvider.state("home.newest.abc.xyz.inception", {});
  46406. *
  46407. * // state() returns $stateProvider, so you can chain state declarations.
  46408. * $stateProvider
  46409. * .state("home", {})
  46410. * .state("about", {})
  46411. * .state("contacts", {});
  46412. * </pre>
  46413. *
  46414. */
  46415. this.state = state;
  46416. function state(name, definition) {
  46417. /*jshint validthis: true */
  46418. if (isObject(name)) definition = name;
  46419. else definition.name = name;
  46420. registerState(definition);
  46421. return this;
  46422. }
  46423. /**
  46424. * @ngdoc object
  46425. * @name ui.router.state.$state
  46426. *
  46427. * @requires $rootScope
  46428. * @requires $q
  46429. * @requires ui.router.state.$view
  46430. * @requires $injector
  46431. * @requires ui.router.util.$resolve
  46432. * @requires ui.router.state.$stateParams
  46433. * @requires ui.router.router.$urlRouter
  46434. *
  46435. * @property {object} params A param object, e.g. {sectionId: section.id)}, that
  46436. * you'd like to test against the current active state.
  46437. * @property {object} current A reference to the state's config object. However
  46438. * you passed it in. Useful for accessing custom data.
  46439. * @property {object} transition Currently pending transition. A promise that'll
  46440. * resolve or reject.
  46441. *
  46442. * @description
  46443. * `$state` service is responsible for representing states as well as transitioning
  46444. * between them. It also provides interfaces to ask for current state or even states
  46445. * you're coming from.
  46446. */
  46447. this.$get = $get;
  46448. $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
  46449. function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
  46450. var TransitionSuperseded = $q.reject(new Error('transition superseded'));
  46451. var TransitionPrevented = $q.reject(new Error('transition prevented'));
  46452. var TransitionAborted = $q.reject(new Error('transition aborted'));
  46453. var TransitionFailed = $q.reject(new Error('transition failed'));
  46454. // Handles the case where a state which is the target of a transition is not found, and the user
  46455. // can optionally retry or defer the transition
  46456. function handleRedirect(redirect, state, params, options) {
  46457. /**
  46458. * @ngdoc event
  46459. * @name ui.router.state.$state#$stateNotFound
  46460. * @eventOf ui.router.state.$state
  46461. * @eventType broadcast on root scope
  46462. * @description
  46463. * Fired when a requested state **cannot be found** using the provided state name during transition.
  46464. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
  46465. * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
  46466. * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
  46467. * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
  46468. *
  46469. * @param {Object} event Event object.
  46470. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
  46471. * @param {State} fromState Current state object.
  46472. * @param {Object} fromParams Current state params.
  46473. *
  46474. * @example
  46475. *
  46476. * <pre>
  46477. * // somewhere, assume lazy.state has not been defined
  46478. * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
  46479. *
  46480. * // somewhere else
  46481. * $scope.$on('$stateNotFound',
  46482. * function(event, unfoundState, fromState, fromParams){
  46483. * console.log(unfoundState.to); // "lazy.state"
  46484. * console.log(unfoundState.toParams); // {a:1, b:2}
  46485. * console.log(unfoundState.options); // {inherit:false} + default options
  46486. * })
  46487. * </pre>
  46488. */
  46489. var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
  46490. if (evt.defaultPrevented) {
  46491. $urlRouter.update();
  46492. return TransitionAborted;
  46493. }
  46494. if (!evt.retry) {
  46495. return null;
  46496. }
  46497. // Allow the handler to return a promise to defer state lookup retry
  46498. if (options.$retry) {
  46499. $urlRouter.update();
  46500. return TransitionFailed;
  46501. }
  46502. var retryTransition = $state.transition = $q.when(evt.retry);
  46503. retryTransition.then(function() {
  46504. if (retryTransition !== $state.transition) return TransitionSuperseded;
  46505. redirect.options.$retry = true;
  46506. return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
  46507. }, function() {
  46508. return TransitionAborted;
  46509. });
  46510. $urlRouter.update();
  46511. return retryTransition;
  46512. }
  46513. root.locals = { resolve: null, globals: { $stateParams: {} } };
  46514. $state = {
  46515. params: {},
  46516. current: root.self,
  46517. $current: root,
  46518. transition: null
  46519. };
  46520. /**
  46521. * @ngdoc function
  46522. * @name ui.router.state.$state#reload
  46523. * @methodOf ui.router.state.$state
  46524. *
  46525. * @description
  46526. * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired,
  46527. * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).
  46528. *
  46529. * @example
  46530. * <pre>
  46531. * var app angular.module('app', ['ui.router']);
  46532. *
  46533. * app.controller('ctrl', function ($scope, $state) {
  46534. * $scope.reload = function(){
  46535. * $state.reload();
  46536. * }
  46537. * });
  46538. * </pre>
  46539. *
  46540. * `reload()` is just an alias for:
  46541. * <pre>
  46542. * $state.transitionTo($state.current, $stateParams, {
  46543. * reload: true, inherit: false, notify: true
  46544. * });
  46545. * </pre>
  46546. *
  46547. * @returns {promise} A promise representing the state of the new transition. See
  46548. * {@link ui.router.state.$state#methods_go $state.go}.
  46549. */
  46550. $state.reload = function reload() {
  46551. return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
  46552. };
  46553. /**
  46554. * @ngdoc function
  46555. * @name ui.router.state.$state#go
  46556. * @methodOf ui.router.state.$state
  46557. *
  46558. * @description
  46559. * Convenience method for transitioning to a new state. `$state.go` calls
  46560. * `$state.transitionTo` internally but automatically sets options to
  46561. * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
  46562. * This allows you to easily use an absolute or relative to path and specify
  46563. * only the parameters you'd like to update (while letting unspecified parameters
  46564. * inherit from the currently active ancestor states).
  46565. *
  46566. * @example
  46567. * <pre>
  46568. * var app = angular.module('app', ['ui.router']);
  46569. *
  46570. * app.controller('ctrl', function ($scope, $state) {
  46571. * $scope.changeState = function () {
  46572. * $state.go('contact.detail');
  46573. * };
  46574. * });
  46575. * </pre>
  46576. * <img src='../ngdoc_assets/StateGoExamples.png'/>
  46577. *
  46578. * @param {string} to Absolute state name or relative state path. Some examples:
  46579. *
  46580. * - `$state.go('contact.detail')` - will go to the `contact.detail` state
  46581. * - `$state.go('^')` - will go to a parent state
  46582. * - `$state.go('^.sibling')` - will go to a sibling state
  46583. * - `$state.go('.child.grandchild')` - will go to grandchild state
  46584. *
  46585. * @param {object=} params A map of the parameters that will be sent to the state,
  46586. * will populate $stateParams. Any parameters that are not specified will be inherited from currently
  46587. * defined parameters. This allows, for example, going to a sibling state that shares parameters
  46588. * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
  46589. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
  46590. * will get you all current parameters, etc.
  46591. * @param {object=} options Options object. The options are:
  46592. *
  46593. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  46594. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  46595. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  46596. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  46597. * defines which state to be relative from.
  46598. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  46599. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  46600. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  46601. * use this when you want to force a reload when *everything* is the same, including search params.
  46602. *
  46603. * @returns {promise} A promise representing the state of the new transition.
  46604. *
  46605. * Possible success values:
  46606. *
  46607. * - $state.current
  46608. *
  46609. * <br/>Possible rejection values:
  46610. *
  46611. * - 'transition superseded' - when a newer transition has been started after this one
  46612. * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
  46613. * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
  46614. * when a `$stateNotFound` `event.retry` promise errors.
  46615. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
  46616. * - *resolve error* - when an error has occurred with a `resolve`
  46617. *
  46618. */
  46619. $state.go = function go(to, params, options) {
  46620. return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
  46621. };
  46622. /**
  46623. * @ngdoc function
  46624. * @name ui.router.state.$state#transitionTo
  46625. * @methodOf ui.router.state.$state
  46626. *
  46627. * @description
  46628. * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
  46629. * uses `transitionTo` internally. `$state.go` is recommended in most situations.
  46630. *
  46631. * @example
  46632. * <pre>
  46633. * var app = angular.module('app', ['ui.router']);
  46634. *
  46635. * app.controller('ctrl', function ($scope, $state) {
  46636. * $scope.changeState = function () {
  46637. * $state.transitionTo('contact.detail');
  46638. * };
  46639. * });
  46640. * </pre>
  46641. *
  46642. * @param {string} to State name.
  46643. * @param {object=} toParams A map of the parameters that will be sent to the state,
  46644. * will populate $stateParams.
  46645. * @param {object=} options Options object. The options are:
  46646. *
  46647. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  46648. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  46649. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
  46650. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
  46651. * defines which state to be relative from.
  46652. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  46653. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  46654. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  46655. * use this when you want to force a reload when *everything* is the same, including search params.
  46656. *
  46657. * @returns {promise} A promise representing the state of the new transition. See
  46658. * {@link ui.router.state.$state#methods_go $state.go}.
  46659. */
  46660. $state.transitionTo = function transitionTo(to, toParams, options) {
  46661. toParams = toParams || {};
  46662. options = extend({
  46663. location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
  46664. }, options || {});
  46665. var from = $state.$current, fromParams = $state.params, fromPath = from.path;
  46666. var evt, toState = findState(to, options.relative);
  46667. if (!isDefined(toState)) {
  46668. var redirect = { to: to, toParams: toParams, options: options };
  46669. var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
  46670. if (redirectResult) {
  46671. return redirectResult;
  46672. }
  46673. // Always retry once if the $stateNotFound was not prevented
  46674. // (handles either redirect changed or state lazy-definition)
  46675. to = redirect.to;
  46676. toParams = redirect.toParams;
  46677. options = redirect.options;
  46678. toState = findState(to, options.relative);
  46679. if (!isDefined(toState)) {
  46680. if (!options.relative) throw new Error("No such state '" + to + "'");
  46681. throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
  46682. }
  46683. }
  46684. if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
  46685. if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
  46686. if (!toState.params.$$validates(toParams)) return TransitionFailed;
  46687. toParams = toState.params.$$values(toParams);
  46688. to = toState;
  46689. var toPath = to.path;
  46690. // Starting from the root of the path, keep all levels that haven't changed
  46691. var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
  46692. if (!options.reload) {
  46693. while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
  46694. locals = toLocals[keep] = state.locals;
  46695. keep++;
  46696. state = toPath[keep];
  46697. }
  46698. }
  46699. // If we're going to the same state and all locals are kept, we've got nothing to do.
  46700. // But clear 'transition', as we still want to cancel any other pending transitions.
  46701. // TODO: We may not want to bump 'transition' if we're called from a location change
  46702. // that we've initiated ourselves, because we might accidentally abort a legitimate
  46703. // transition initiated from code?
  46704. if (shouldTriggerReload(to, from, locals, options)) {
  46705. if (to.self.reloadOnSearch !== false) $urlRouter.update();
  46706. $state.transition = null;
  46707. return $q.when($state.current);
  46708. }
  46709. // Filter parameters before we pass them to event handlers etc.
  46710. toParams = filterByKeys(to.params.$$keys(), toParams || {});
  46711. // Broadcast start event and cancel the transition if requested
  46712. if (options.notify) {
  46713. /**
  46714. * @ngdoc event
  46715. * @name ui.router.state.$state#$stateChangeStart
  46716. * @eventOf ui.router.state.$state
  46717. * @eventType broadcast on root scope
  46718. * @description
  46719. * Fired when the state transition **begins**. You can use `event.preventDefault()`
  46720. * to prevent the transition from happening and then the transition promise will be
  46721. * rejected with a `'transition prevented'` value.
  46722. *
  46723. * @param {Object} event Event object.
  46724. * @param {State} toState The state being transitioned to.
  46725. * @param {Object} toParams The params supplied to the `toState`.
  46726. * @param {State} fromState The current state, pre-transition.
  46727. * @param {Object} fromParams The params supplied to the `fromState`.
  46728. *
  46729. * @example
  46730. *
  46731. * <pre>
  46732. * $rootScope.$on('$stateChangeStart',
  46733. * function(event, toState, toParams, fromState, fromParams){
  46734. * event.preventDefault();
  46735. * // transitionTo() promise will be rejected with
  46736. * // a 'transition prevented' error
  46737. * })
  46738. * </pre>
  46739. */
  46740. if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
  46741. $urlRouter.update();
  46742. return TransitionPrevented;
  46743. }
  46744. }
  46745. // Resolve locals for the remaining states, but don't update any global state just
  46746. // yet -- if anything fails to resolve the current state needs to remain untouched.
  46747. // We also set up an inheritance chain for the locals here. This allows the view directive
  46748. // to quickly look up the correct definition for each view in the current state. Even
  46749. // though we create the locals object itself outside resolveState(), it is initially
  46750. // empty and gets filled asynchronously. We need to keep track of the promise for the
  46751. // (fully resolved) current locals, and pass this down the chain.
  46752. var resolved = $q.when(locals);
  46753. for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
  46754. locals = toLocals[l] = inherit(locals);
  46755. resolved = resolveState(state, toParams, state === to, resolved, locals, options);
  46756. }
  46757. // Once everything is resolved, we are ready to perform the actual transition
  46758. // and return a promise for the new state. We also keep track of what the
  46759. // current promise is, so that we can detect overlapping transitions and
  46760. // keep only the outcome of the last transition.
  46761. var transition = $state.transition = resolved.then(function () {
  46762. var l, entering, exiting;
  46763. if ($state.transition !== transition) return TransitionSuperseded;
  46764. // Exit 'from' states not kept
  46765. for (l = fromPath.length - 1; l >= keep; l--) {
  46766. exiting = fromPath[l];
  46767. if (exiting.self.onExit) {
  46768. $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
  46769. }
  46770. exiting.locals = null;
  46771. }
  46772. // Enter 'to' states not kept
  46773. for (l = keep; l < toPath.length; l++) {
  46774. entering = toPath[l];
  46775. entering.locals = toLocals[l];
  46776. if (entering.self.onEnter) {
  46777. $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
  46778. }
  46779. }
  46780. // Run it again, to catch any transitions in callbacks
  46781. if ($state.transition !== transition) return TransitionSuperseded;
  46782. // Update globals in $state
  46783. $state.$current = to;
  46784. $state.current = to.self;
  46785. $state.params = toParams;
  46786. copy($state.params, $stateParams);
  46787. $state.transition = null;
  46788. if (options.location && to.navigable) {
  46789. $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
  46790. $$avoidResync: true, replace: options.location === 'replace'
  46791. });
  46792. }
  46793. if (options.notify) {
  46794. /**
  46795. * @ngdoc event
  46796. * @name ui.router.state.$state#$stateChangeSuccess
  46797. * @eventOf ui.router.state.$state
  46798. * @eventType broadcast on root scope
  46799. * @description
  46800. * Fired once the state transition is **complete**.
  46801. *
  46802. * @param {Object} event Event object.
  46803. * @param {State} toState The state being transitioned to.
  46804. * @param {Object} toParams The params supplied to the `toState`.
  46805. * @param {State} fromState The current state, pre-transition.
  46806. * @param {Object} fromParams The params supplied to the `fromState`.
  46807. */
  46808. $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
  46809. }
  46810. $urlRouter.update(true);
  46811. return $state.current;
  46812. }, function (error) {
  46813. if ($state.transition !== transition) return TransitionSuperseded;
  46814. $state.transition = null;
  46815. /**
  46816. * @ngdoc event
  46817. * @name ui.router.state.$state#$stateChangeError
  46818. * @eventOf ui.router.state.$state
  46819. * @eventType broadcast on root scope
  46820. * @description
  46821. * Fired when an **error occurs** during transition. It's important to note that if you
  46822. * have any errors in your resolve functions (javascript errors, non-existent services, etc)
  46823. * they will not throw traditionally. You must listen for this $stateChangeError event to
  46824. * catch **ALL** errors.
  46825. *
  46826. * @param {Object} event Event object.
  46827. * @param {State} toState The state being transitioned to.
  46828. * @param {Object} toParams The params supplied to the `toState`.
  46829. * @param {State} fromState The current state, pre-transition.
  46830. * @param {Object} fromParams The params supplied to the `fromState`.
  46831. * @param {Error} error The resolve error object.
  46832. */
  46833. evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
  46834. if (!evt.defaultPrevented) {
  46835. $urlRouter.update();
  46836. }
  46837. return $q.reject(error);
  46838. });
  46839. return transition;
  46840. };
  46841. /**
  46842. * @ngdoc function
  46843. * @name ui.router.state.$state#is
  46844. * @methodOf ui.router.state.$state
  46845. *
  46846. * @description
  46847. * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
  46848. * but only checks for the full state name. If params is supplied then it will be
  46849. * tested for strict equality against the current active params object, so all params
  46850. * must match with none missing and no extras.
  46851. *
  46852. * @example
  46853. * <pre>
  46854. * $state.$current.name = 'contacts.details.item';
  46855. *
  46856. * // absolute name
  46857. * $state.is('contact.details.item'); // returns true
  46858. * $state.is(contactDetailItemStateObject); // returns true
  46859. *
  46860. * // relative name (. and ^), typically from a template
  46861. * // E.g. from the 'contacts.details' template
  46862. * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
  46863. * </pre>
  46864. *
  46865. * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
  46866. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
  46867. * to test against the current active state.
  46868. * @param {object=} options An options object. The options are:
  46869. *
  46870. * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
  46871. * test relative to `options.relative` state (or name).
  46872. *
  46873. * @returns {boolean} Returns true if it is the state.
  46874. */
  46875. $state.is = function is(stateOrName, params, options) {
  46876. options = extend({ relative: $state.$current }, options || {});
  46877. var state = findState(stateOrName, options.relative);
  46878. if (!isDefined(state)) { return undefined; }
  46879. if ($state.$current !== state) { return false; }
  46880. return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
  46881. };
  46882. /**
  46883. * @ngdoc function
  46884. * @name ui.router.state.$state#includes
  46885. * @methodOf ui.router.state.$state
  46886. *
  46887. * @description
  46888. * A method to determine if the current active state is equal to or is the child of the
  46889. * state stateName. If any params are passed then they will be tested for a match as well.
  46890. * Not all the parameters need to be passed, just the ones you'd like to test for equality.
  46891. *
  46892. * @example
  46893. * Partial and relative names
  46894. * <pre>
  46895. * $state.$current.name = 'contacts.details.item';
  46896. *
  46897. * // Using partial names
  46898. * $state.includes("contacts"); // returns true
  46899. * $state.includes("contacts.details"); // returns true
  46900. * $state.includes("contacts.details.item"); // returns true
  46901. * $state.includes("contacts.list"); // returns false
  46902. * $state.includes("about"); // returns false
  46903. *
  46904. * // Using relative names (. and ^), typically from a template
  46905. * // E.g. from the 'contacts.details' template
  46906. * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
  46907. * </pre>
  46908. *
  46909. * Basic globbing patterns
  46910. * <pre>
  46911. * $state.$current.name = 'contacts.details.item.url';
  46912. *
  46913. * $state.includes("*.details.*.*"); // returns true
  46914. * $state.includes("*.details.**"); // returns true
  46915. * $state.includes("**.item.**"); // returns true
  46916. * $state.includes("*.details.item.url"); // returns true
  46917. * $state.includes("*.details.*.url"); // returns true
  46918. * $state.includes("*.details.*"); // returns false
  46919. * $state.includes("item.**"); // returns false
  46920. * </pre>
  46921. *
  46922. * @param {string} stateOrName A partial name, relative name, or glob pattern
  46923. * to be searched for within the current state name.
  46924. * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
  46925. * that you'd like to test against the current active state.
  46926. * @param {object=} options An options object. The options are:
  46927. *
  46928. * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
  46929. * .includes will test relative to `options.relative` state (or name).
  46930. *
  46931. * @returns {boolean} Returns true if it does include the state
  46932. */
  46933. $state.includes = function includes(stateOrName, params, options) {
  46934. options = extend({ relative: $state.$current }, options || {});
  46935. if (isString(stateOrName) && isGlob(stateOrName)) {
  46936. if (!doesStateMatchGlob(stateOrName)) {
  46937. return false;
  46938. }
  46939. stateOrName = $state.$current.name;
  46940. }
  46941. var state = findState(stateOrName, options.relative);
  46942. if (!isDefined(state)) { return undefined; }
  46943. if (!isDefined($state.$current.includes[state.name])) { return false; }
  46944. return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
  46945. };
  46946. /**
  46947. * @ngdoc function
  46948. * @name ui.router.state.$state#href
  46949. * @methodOf ui.router.state.$state
  46950. *
  46951. * @description
  46952. * A url generation method that returns the compiled url for the given state populated with the given params.
  46953. *
  46954. * @example
  46955. * <pre>
  46956. * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
  46957. * </pre>
  46958. *
  46959. * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
  46960. * @param {object=} params An object of parameter values to fill the state's required parameters.
  46961. * @param {object=} options Options object. The options are:
  46962. *
  46963. * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
  46964. * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
  46965. * ancestor with a valid url).
  46966. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  46967. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  46968. * defines which state to be relative from.
  46969. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  46970. *
  46971. * @returns {string} compiled state url
  46972. */
  46973. $state.href = function href(stateOrName, params, options) {
  46974. options = extend({
  46975. lossy: true,
  46976. inherit: true,
  46977. absolute: false,
  46978. relative: $state.$current
  46979. }, options || {});
  46980. var state = findState(stateOrName, options.relative);
  46981. if (!isDefined(state)) return null;
  46982. if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
  46983. var nav = (state && options.lossy) ? state.navigable : state;
  46984. if (!nav || nav.url === undefined || nav.url === null) {
  46985. return null;
  46986. }
  46987. return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), {
  46988. absolute: options.absolute
  46989. });
  46990. };
  46991. /**
  46992. * @ngdoc function
  46993. * @name ui.router.state.$state#get
  46994. * @methodOf ui.router.state.$state
  46995. *
  46996. * @description
  46997. * Returns the state configuration object for any specific state or all states.
  46998. *
  46999. * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
  47000. * the requested state. If not provided, returns an array of ALL state configs.
  47001. * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
  47002. * @returns {Object|Array} State configuration object or array of all objects.
  47003. */
  47004. $state.get = function (stateOrName, context) {
  47005. if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
  47006. var state = findState(stateOrName, context || $state.$current);
  47007. return (state && state.self) ? state.self : null;
  47008. };
  47009. function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
  47010. // Make a restricted $stateParams with only the parameters that apply to this state if
  47011. // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
  47012. // we also need $stateParams to be available for any $injector calls we make during the
  47013. // dependency resolution process.
  47014. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  47015. var locals = { $stateParams: $stateParams };
  47016. // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  47017. // We're also including $stateParams in this; that way the parameters are restricted
  47018. // to the set that should be visible to the state, and are independent of when we update
  47019. // the global $state and $stateParams values.
  47020. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  47021. var promises = [dst.resolve.then(function (globals) {
  47022. dst.globals = globals;
  47023. })];
  47024. if (inherited) promises.push(inherited);
  47025. // Resolve template and dependencies for all views.
  47026. forEach(state.views, function (view, name) {
  47027. var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
  47028. injectables.$template = [ function () {
  47029. return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || '';
  47030. }];
  47031. promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
  47032. // References to the controller (only instantiated at link time)
  47033. if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
  47034. var injectLocals = angular.extend({}, injectables, locals);
  47035. result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
  47036. } else {
  47037. result.$$controller = view.controller;
  47038. }
  47039. // Provide access to the state itself for internal use
  47040. result.$$state = state;
  47041. result.$$controllerAs = view.controllerAs;
  47042. dst[name] = result;
  47043. }));
  47044. });
  47045. // Wait for all the promises and then return the activation object
  47046. return $q.all(promises).then(function (values) {
  47047. return dst;
  47048. });
  47049. }
  47050. return $state;
  47051. }
  47052. function shouldTriggerReload(to, from, locals, options) {
  47053. if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {
  47054. return true;
  47055. }
  47056. }
  47057. }
  47058. angular.module('ui.router.state')
  47059. .value('$stateParams', {})
  47060. .provider('$state', $StateProvider);
  47061. $ViewProvider.$inject = [];
  47062. function $ViewProvider() {
  47063. this.$get = $get;
  47064. /**
  47065. * @ngdoc object
  47066. * @name ui.router.state.$view
  47067. *
  47068. * @requires ui.router.util.$templateFactory
  47069. * @requires $rootScope
  47070. *
  47071. * @description
  47072. *
  47073. */
  47074. $get.$inject = ['$rootScope', '$templateFactory'];
  47075. function $get( $rootScope, $templateFactory) {
  47076. return {
  47077. // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
  47078. /**
  47079. * @ngdoc function
  47080. * @name ui.router.state.$view#load
  47081. * @methodOf ui.router.state.$view
  47082. *
  47083. * @description
  47084. *
  47085. * @param {string} name name
  47086. * @param {object} options option object.
  47087. */
  47088. load: function load(name, options) {
  47089. var result, defaults = {
  47090. template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
  47091. };
  47092. options = extend(defaults, options);
  47093. if (options.view) {
  47094. result = $templateFactory.fromConfig(options.view, options.params, options.locals);
  47095. }
  47096. if (result && options.notify) {
  47097. /**
  47098. * @ngdoc event
  47099. * @name ui.router.state.$state#$viewContentLoading
  47100. * @eventOf ui.router.state.$view
  47101. * @eventType broadcast on root scope
  47102. * @description
  47103. *
  47104. * Fired once the view **begins loading**, *before* the DOM is rendered.
  47105. *
  47106. * @param {Object} event Event object.
  47107. * @param {Object} viewConfig The view config properties (template, controller, etc).
  47108. *
  47109. * @example
  47110. *
  47111. * <pre>
  47112. * $scope.$on('$viewContentLoading',
  47113. * function(event, viewConfig){
  47114. * // Access to all the view config properties.
  47115. * // and one special property 'targetView'
  47116. * // viewConfig.targetView
  47117. * });
  47118. * </pre>
  47119. */
  47120. $rootScope.$broadcast('$viewContentLoading', options);
  47121. }
  47122. return result;
  47123. }
  47124. };
  47125. }
  47126. }
  47127. angular.module('ui.router.state').provider('$view', $ViewProvider);
  47128. /**
  47129. * @ngdoc object
  47130. * @name ui.router.state.$uiViewScrollProvider
  47131. *
  47132. * @description
  47133. * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
  47134. */
  47135. function $ViewScrollProvider() {
  47136. var useAnchorScroll = false;
  47137. /**
  47138. * @ngdoc function
  47139. * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
  47140. * @methodOf ui.router.state.$uiViewScrollProvider
  47141. *
  47142. * @description
  47143. * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
  47144. * scrolling based on the url anchor.
  47145. */
  47146. this.useAnchorScroll = function () {
  47147. useAnchorScroll = true;
  47148. };
  47149. /**
  47150. * @ngdoc object
  47151. * @name ui.router.state.$uiViewScroll
  47152. *
  47153. * @requires $anchorScroll
  47154. * @requires $timeout
  47155. *
  47156. * @description
  47157. * When called with a jqLite element, it scrolls the element into view (after a
  47158. * `$timeout` so the DOM has time to refresh).
  47159. *
  47160. * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
  47161. * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
  47162. */
  47163. this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
  47164. if (useAnchorScroll) {
  47165. return $anchorScroll;
  47166. }
  47167. return function ($element) {
  47168. $timeout(function () {
  47169. $element[0].scrollIntoView();
  47170. }, 0, false);
  47171. };
  47172. }];
  47173. }
  47174. angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
  47175. /**
  47176. * @ngdoc directive
  47177. * @name ui.router.state.directive:ui-view
  47178. *
  47179. * @requires ui.router.state.$state
  47180. * @requires $compile
  47181. * @requires $controller
  47182. * @requires $injector
  47183. * @requires ui.router.state.$uiViewScroll
  47184. * @requires $document
  47185. *
  47186. * @restrict ECA
  47187. *
  47188. * @description
  47189. * The ui-view directive tells $state where to place your templates.
  47190. *
  47191. * @param {string=} name A view name. The name should be unique amongst the other views in the
  47192. * same state. You can have views of the same name that live in different states.
  47193. *
  47194. * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
  47195. * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
  47196. * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
  47197. * scroll ui-view elements into view when they are populated during a state activation.
  47198. *
  47199. * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
  47200. * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
  47201. *
  47202. * @param {string=} onload Expression to evaluate whenever the view updates.
  47203. *
  47204. * @example
  47205. * A view can be unnamed or named.
  47206. * <pre>
  47207. * <!-- Unnamed -->
  47208. * <div ui-view></div>
  47209. *
  47210. * <!-- Named -->
  47211. * <div ui-view="viewName"></div>
  47212. * </pre>
  47213. *
  47214. * You can only have one unnamed view within any template (or root html). If you are only using a
  47215. * single view and it is unnamed then you can populate it like so:
  47216. * <pre>
  47217. * <div ui-view></div>
  47218. * $stateProvider.state("home", {
  47219. * template: "<h1>HELLO!</h1>"
  47220. * })
  47221. * </pre>
  47222. *
  47223. * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
  47224. * config property, by name, in this case an empty name:
  47225. * <pre>
  47226. * $stateProvider.state("home", {
  47227. * views: {
  47228. * "": {
  47229. * template: "<h1>HELLO!</h1>"
  47230. * }
  47231. * }
  47232. * })
  47233. * </pre>
  47234. *
  47235. * But typically you'll only use the views property if you name your view or have more than one view
  47236. * in the same template. There's not really a compelling reason to name a view if its the only one,
  47237. * but you could if you wanted, like so:
  47238. * <pre>
  47239. * <div ui-view="main"></div>
  47240. * </pre>
  47241. * <pre>
  47242. * $stateProvider.state("home", {
  47243. * views: {
  47244. * "main": {
  47245. * template: "<h1>HELLO!</h1>"
  47246. * }
  47247. * }
  47248. * })
  47249. * </pre>
  47250. *
  47251. * Really though, you'll use views to set up multiple views:
  47252. * <pre>
  47253. * <div ui-view></div>
  47254. * <div ui-view="chart"></div>
  47255. * <div ui-view="data"></div>
  47256. * </pre>
  47257. *
  47258. * <pre>
  47259. * $stateProvider.state("home", {
  47260. * views: {
  47261. * "": {
  47262. * template: "<h1>HELLO!</h1>"
  47263. * },
  47264. * "chart": {
  47265. * template: "<chart_thing/>"
  47266. * },
  47267. * "data": {
  47268. * template: "<data_thing/>"
  47269. * }
  47270. * }
  47271. * })
  47272. * </pre>
  47273. *
  47274. * Examples for `autoscroll`:
  47275. *
  47276. * <pre>
  47277. * <!-- If autoscroll present with no expression,
  47278. * then scroll ui-view into view -->
  47279. * <ui-view autoscroll/>
  47280. *
  47281. * <!-- If autoscroll present with valid expression,
  47282. * then scroll ui-view into view if expression evaluates to true -->
  47283. * <ui-view autoscroll='true'/>
  47284. * <ui-view autoscroll='false'/>
  47285. * <ui-view autoscroll='scopeVariable'/>
  47286. * </pre>
  47287. */
  47288. $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
  47289. function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
  47290. function getService() {
  47291. return ($injector.has) ? function(service) {
  47292. return $injector.has(service) ? $injector.get(service) : null;
  47293. } : function(service) {
  47294. try {
  47295. return $injector.get(service);
  47296. } catch (e) {
  47297. return null;
  47298. }
  47299. };
  47300. }
  47301. var service = getService(),
  47302. $animator = service('$animator'),
  47303. $animate = service('$animate');
  47304. // Returns a set of DOM manipulation functions based on which Angular version
  47305. // it should use
  47306. function getRenderer(attrs, scope) {
  47307. var statics = function() {
  47308. return {
  47309. enter: function (element, target, cb) { target.after(element); cb(); },
  47310. leave: function (element, cb) { element.remove(); cb(); }
  47311. };
  47312. };
  47313. if ($animate) {
  47314. return {
  47315. enter: function(element, target, cb) {
  47316. var promise = $animate.enter(element, null, target, cb);
  47317. if (promise && promise.then) promise.then(cb);
  47318. },
  47319. leave: function(element, cb) {
  47320. var promise = $animate.leave(element, cb);
  47321. if (promise && promise.then) promise.then(cb);
  47322. }
  47323. };
  47324. }
  47325. if ($animator) {
  47326. var animate = $animator && $animator(scope, attrs);
  47327. return {
  47328. enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
  47329. leave: function(element, cb) { animate.leave(element); cb(); }
  47330. };
  47331. }
  47332. return statics();
  47333. }
  47334. var directive = {
  47335. restrict: 'ECA',
  47336. terminal: true,
  47337. priority: 400,
  47338. transclude: 'element',
  47339. compile: function (tElement, tAttrs, $transclude) {
  47340. return function (scope, $element, attrs) {
  47341. var previousEl, currentEl, currentScope, latestLocals,
  47342. onloadExp = attrs.onload || '',
  47343. autoScrollExp = attrs.autoscroll,
  47344. renderer = getRenderer(attrs, scope);
  47345. scope.$on('$stateChangeSuccess', function() {
  47346. updateView(false);
  47347. });
  47348. scope.$on('$viewContentLoading', function() {
  47349. updateView(false);
  47350. });
  47351. updateView(true);
  47352. function cleanupLastView() {
  47353. if (previousEl) {
  47354. previousEl.remove();
  47355. previousEl = null;
  47356. }
  47357. if (currentScope) {
  47358. currentScope.$destroy();
  47359. currentScope = null;
  47360. }
  47361. if (currentEl) {
  47362. renderer.leave(currentEl, function() {
  47363. previousEl = null;
  47364. });
  47365. previousEl = currentEl;
  47366. currentEl = null;
  47367. }
  47368. }
  47369. function updateView(firstTime) {
  47370. var newScope,
  47371. name = getUiViewName(scope, attrs, $element, $interpolate),
  47372. previousLocals = name && $state.$current && $state.$current.locals[name];
  47373. if (!firstTime && previousLocals === latestLocals) return; // nothing to do
  47374. newScope = scope.$new();
  47375. latestLocals = $state.$current.locals[name];
  47376. var clone = $transclude(newScope, function(clone) {
  47377. renderer.enter(clone, $element, function onUiViewEnter() {
  47378. if(currentScope) {
  47379. currentScope.$emit('$viewContentAnimationEnded');
  47380. }
  47381. if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
  47382. $uiViewScroll(clone);
  47383. }
  47384. });
  47385. cleanupLastView();
  47386. });
  47387. currentEl = clone;
  47388. currentScope = newScope;
  47389. /**
  47390. * @ngdoc event
  47391. * @name ui.router.state.directive:ui-view#$viewContentLoaded
  47392. * @eventOf ui.router.state.directive:ui-view
  47393. * @eventType emits on ui-view directive scope
  47394. * @description *
  47395. * Fired once the view is **loaded**, *after* the DOM is rendered.
  47396. *
  47397. * @param {Object} event Event object.
  47398. */
  47399. currentScope.$emit('$viewContentLoaded');
  47400. currentScope.$eval(onloadExp);
  47401. }
  47402. };
  47403. }
  47404. };
  47405. return directive;
  47406. }
  47407. $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
  47408. function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
  47409. return {
  47410. restrict: 'ECA',
  47411. priority: -400,
  47412. compile: function (tElement) {
  47413. var initial = tElement.html();
  47414. return function (scope, $element, attrs) {
  47415. var current = $state.$current,
  47416. name = getUiViewName(scope, attrs, $element, $interpolate),
  47417. locals = current && current.locals[name];
  47418. if (! locals) {
  47419. return;
  47420. }
  47421. $element.data('$uiView', { name: name, state: locals.$$state });
  47422. $element.html(locals.$template ? locals.$template : initial);
  47423. var link = $compile($element.contents());
  47424. if (locals.$$controller) {
  47425. locals.$scope = scope;
  47426. var controller = $controller(locals.$$controller, locals);
  47427. if (locals.$$controllerAs) {
  47428. scope[locals.$$controllerAs] = controller;
  47429. }
  47430. $element.data('$ngControllerController', controller);
  47431. $element.children().data('$ngControllerController', controller);
  47432. }
  47433. link(scope);
  47434. };
  47435. }
  47436. };
  47437. }
  47438. /**
  47439. * Shared ui-view code for both directives:
  47440. * Given scope, element, and its attributes, return the view's name
  47441. */
  47442. function getUiViewName(scope, attrs, element, $interpolate) {
  47443. var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
  47444. var inherited = element.inheritedData('$uiView');
  47445. return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
  47446. }
  47447. angular.module('ui.router.state').directive('uiView', $ViewDirective);
  47448. angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
  47449. function parseStateRef(ref, current) {
  47450. var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  47451. if (preparsed) ref = current + '(' + preparsed[1] + ')';
  47452. parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  47453. if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  47454. return { state: parsed[1], paramExpr: parsed[3] || null };
  47455. }
  47456. function stateContext(el) {
  47457. var stateData = el.parent().inheritedData('$uiView');
  47458. if (stateData && stateData.state && stateData.state.name) {
  47459. return stateData.state;
  47460. }
  47461. }
  47462. /**
  47463. * @ngdoc directive
  47464. * @name ui.router.state.directive:ui-sref
  47465. *
  47466. * @requires ui.router.state.$state
  47467. * @requires $timeout
  47468. *
  47469. * @restrict A
  47470. *
  47471. * @description
  47472. * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
  47473. * URL, the directive will automatically generate & update the `href` attribute via
  47474. * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
  47475. * the link will trigger a state transition with optional parameters.
  47476. *
  47477. * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
  47478. * handled natively by the browser.
  47479. *
  47480. * You can also use relative state paths within ui-sref, just like the relative
  47481. * paths passed to `$state.go()`. You just need to be aware that the path is relative
  47482. * to the state that the link lives in, in other words the state that loaded the
  47483. * template containing the link.
  47484. *
  47485. * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
  47486. * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
  47487. * and `reload`.
  47488. *
  47489. * @example
  47490. * Here's an example of how you'd use ui-sref and how it would compile. If you have the
  47491. * following template:
  47492. * <pre>
  47493. * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
  47494. *
  47495. * <ul>
  47496. * <li ng-repeat="contact in contacts">
  47497. * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
  47498. * </li>
  47499. * </ul>
  47500. * </pre>
  47501. *
  47502. * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
  47503. * <pre>
  47504. * <a href="#/home" ui-sref="home">Home</a> | <a href="#/about" ui-sref="about">About</a> | <a href="#/contacts?page=2" ui-sref="{page: 2}">Next page</a>
  47505. *
  47506. * <ul>
  47507. * <li ng-repeat="contact in contacts">
  47508. * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
  47509. * </li>
  47510. * <li ng-repeat="contact in contacts">
  47511. * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
  47512. * </li>
  47513. * <li ng-repeat="contact in contacts">
  47514. * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
  47515. * </li>
  47516. * </ul>
  47517. *
  47518. * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
  47519. * </pre>
  47520. *
  47521. * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
  47522. * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
  47523. */
  47524. $StateRefDirective.$inject = ['$state', '$timeout'];
  47525. function $StateRefDirective($state, $timeout) {
  47526. var allowedOptions = ['location', 'inherit', 'reload'];
  47527. return {
  47528. restrict: 'A',
  47529. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  47530. link: function(scope, element, attrs, uiSrefActive) {
  47531. var ref = parseStateRef(attrs.uiSref, $state.current.name);
  47532. var params = null, url = null, base = stateContext(element) || $state.$current;
  47533. var newHref = null, isAnchor = element.prop("tagName") === "A";
  47534. var isForm = element[0].nodeName === "FORM";
  47535. var attr = isForm ? "action" : "href", nav = true;
  47536. var options = { relative: base, inherit: true };
  47537. var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
  47538. angular.forEach(allowedOptions, function(option) {
  47539. if (option in optionsOverride) {
  47540. options[option] = optionsOverride[option];
  47541. }
  47542. });
  47543. var update = function(newVal) {
  47544. if (newVal) params = angular.copy(newVal);
  47545. if (!nav) return;
  47546. newHref = $state.href(ref.state, params, options);
  47547. var activeDirective = uiSrefActive[1] || uiSrefActive[0];
  47548. if (activeDirective) {
  47549. activeDirective.$$setStateInfo(ref.state, params);
  47550. }
  47551. if (newHref === null) {
  47552. nav = false;
  47553. return false;
  47554. }
  47555. attrs.$set(attr, newHref);
  47556. };
  47557. if (ref.paramExpr) {
  47558. scope.$watch(ref.paramExpr, function(newVal, oldVal) {
  47559. if (newVal !== params) update(newVal);
  47560. }, true);
  47561. params = angular.copy(scope.$eval(ref.paramExpr));
  47562. }
  47563. update();
  47564. if (isForm) return;
  47565. element.bind("click", function(e) {
  47566. var button = e.which || e.button;
  47567. if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
  47568. // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
  47569. var transition = $timeout(function() {
  47570. $state.go(ref.state, params, options);
  47571. });
  47572. e.preventDefault();
  47573. // if the state has no URL, ignore one preventDefault from the <a> directive.
  47574. var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
  47575. e.preventDefault = function() {
  47576. if (ignorePreventDefaultCount-- <= 0)
  47577. $timeout.cancel(transition);
  47578. };
  47579. }
  47580. });
  47581. }
  47582. };
  47583. }
  47584. /**
  47585. * @ngdoc directive
  47586. * @name ui.router.state.directive:ui-sref-active
  47587. *
  47588. * @requires ui.router.state.$state
  47589. * @requires ui.router.state.$stateParams
  47590. * @requires $interpolate
  47591. *
  47592. * @restrict A
  47593. *
  47594. * @description
  47595. * A directive working alongside ui-sref to add classes to an element when the
  47596. * related ui-sref directive's state is active, and removing them when it is inactive.
  47597. * The primary use-case is to simplify the special appearance of navigation menus
  47598. * relying on `ui-sref`, by having the "active" state's menu button appear different,
  47599. * distinguishing it from the inactive menu items.
  47600. *
  47601. * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
  47602. * ui-sref-active found at the same level or above the ui-sref will be used.
  47603. *
  47604. * Will activate when the ui-sref's target state or any child state is active. If you
  47605. * need to activate only when the ui-sref target state is active and *not* any of
  47606. * it's children, then you will use
  47607. * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
  47608. *
  47609. * @example
  47610. * Given the following template:
  47611. * <pre>
  47612. * <ul>
  47613. * <li ui-sref-active="active" class="item">
  47614. * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  47615. * </li>
  47616. * </ul>
  47617. * </pre>
  47618. *
  47619. *
  47620. * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
  47621. * the resulting HTML will appear as (note the 'active' class):
  47622. * <pre>
  47623. * <ul>
  47624. * <li ui-sref-active="active" class="item active">
  47625. * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  47626. * </li>
  47627. * </ul>
  47628. * </pre>
  47629. *
  47630. * The class name is interpolated **once** during the directives link time (any further changes to the
  47631. * interpolated value are ignored).
  47632. *
  47633. * Multiple classes may be specified in a space-separated format:
  47634. * <pre>
  47635. * <ul>
  47636. * <li ui-sref-active='class1 class2 class3'>
  47637. * <a ui-sref="app.user">link</a>
  47638. * </li>
  47639. * </ul>
  47640. * </pre>
  47641. */
  47642. /**
  47643. * @ngdoc directive
  47644. * @name ui.router.state.directive:ui-sref-active-eq
  47645. *
  47646. * @requires ui.router.state.$state
  47647. * @requires ui.router.state.$stateParams
  47648. * @requires $interpolate
  47649. *
  47650. * @restrict A
  47651. *
  47652. * @description
  47653. * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
  47654. * when the exact target state used in the `ui-sref` is active; no child states.
  47655. *
  47656. */
  47657. $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
  47658. function $StateRefActiveDirective($state, $stateParams, $interpolate) {
  47659. return {
  47660. restrict: "A",
  47661. controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
  47662. var state, params, activeClass;
  47663. // There probably isn't much point in $observing this
  47664. // uiSrefActive and uiSrefActiveEq share the same directive object with some
  47665. // slight difference in logic routing
  47666. activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
  47667. // Allow uiSref to communicate with uiSrefActive[Equals]
  47668. this.$$setStateInfo = function (newState, newParams) {
  47669. state = $state.get(newState, stateContext($element));
  47670. params = newParams;
  47671. update();
  47672. };
  47673. $scope.$on('$stateChangeSuccess', update);
  47674. // Update route state
  47675. function update() {
  47676. if (isMatch()) {
  47677. $element.addClass(activeClass);
  47678. } else {
  47679. $element.removeClass(activeClass);
  47680. }
  47681. }
  47682. function isMatch() {
  47683. if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
  47684. return state && $state.is(state.name, params);
  47685. } else {
  47686. return state && $state.includes(state.name, params);
  47687. }
  47688. }
  47689. }]
  47690. };
  47691. }
  47692. angular.module('ui.router.state')
  47693. .directive('uiSref', $StateRefDirective)
  47694. .directive('uiSrefActive', $StateRefActiveDirective)
  47695. .directive('uiSrefActiveEq', $StateRefActiveDirective);
  47696. /**
  47697. * @ngdoc filter
  47698. * @name ui.router.state.filter:isState
  47699. *
  47700. * @requires ui.router.state.$state
  47701. *
  47702. * @description
  47703. * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
  47704. */
  47705. $IsStateFilter.$inject = ['$state'];
  47706. function $IsStateFilter($state) {
  47707. var isFilter = function (state) {
  47708. return $state.is(state);
  47709. };
  47710. isFilter.$stateful = true;
  47711. return isFilter;
  47712. }
  47713. /**
  47714. * @ngdoc filter
  47715. * @name ui.router.state.filter:includedByState
  47716. *
  47717. * @requires ui.router.state.$state
  47718. *
  47719. * @description
  47720. * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
  47721. */
  47722. $IncludedByStateFilter.$inject = ['$state'];
  47723. function $IncludedByStateFilter($state) {
  47724. var includesFilter = function (state) {
  47725. return $state.includes(state);
  47726. };
  47727. includesFilter.$stateful = true;
  47728. return includesFilter;
  47729. }
  47730. angular.module('ui.router.state')
  47731. .filter('isState', $IsStateFilter)
  47732. .filter('includedByState', $IncludedByStateFilter);
  47733. })(window, window.angular);
  47734. /*!
  47735. * ionic.bundle.js is a concatenation of:
  47736. * ionic.js, angular.js, angular-animate.js,
  47737. * angular-sanitize.js, angular-ui-router.js,
  47738. * and ionic-angular.js
  47739. */
  47740. /*!
  47741. * Copyright 2015 Drifty Co.
  47742. * http://drifty.com/
  47743. *
  47744. * Ionic, v1.3.1
  47745. * A powerful HTML5 mobile app framework.
  47746. * http://ionicframework.com/
  47747. *
  47748. * By @maxlynch, @benjsperry, @adamdbradley <3
  47749. *
  47750. * Licensed under the MIT license. Please see LICENSE for more information.
  47751. *
  47752. */
  47753. (function() {
  47754. /* eslint no-unused-vars:0 */
  47755. var IonicModule = angular.module('ionic', ['ngAnimate', 'ngSanitize', 'ui.router', 'ngIOS9UIWebViewPatch']),
  47756. extend = angular.extend,
  47757. forEach = angular.forEach,
  47758. isDefined = angular.isDefined,
  47759. isNumber = angular.isNumber,
  47760. isString = angular.isString,
  47761. jqLite = angular.element,
  47762. noop = angular.noop;
  47763. /**
  47764. * @ngdoc service
  47765. * @name $ionicActionSheet
  47766. * @module ionic
  47767. * @description
  47768. * The Action Sheet is a slide-up pane that lets the user choose from a set of options.
  47769. * Dangerous options are highlighted in red and made obvious.
  47770. *
  47771. * There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even
  47772. * hitting escape on the keyboard for desktop testing.
  47773. *
  47774. * ![Action Sheet](http://ionicframework.com.s3.amazonaws.com/docs/controllers/actionSheet.gif)
  47775. *
  47776. * @usage
  47777. * To trigger an Action Sheet in your code, use the $ionicActionSheet service in your angular controllers:
  47778. *
  47779. * ```js
  47780. * angular.module('mySuperApp', ['ionic'])
  47781. * .controller(function($scope, $ionicActionSheet, $timeout) {
  47782. *
  47783. * // Triggered on a button click, or some other target
  47784. * $scope.show = function() {
  47785. *
  47786. * // Show the action sheet
  47787. * var hideSheet = $ionicActionSheet.show({
  47788. * buttons: [
  47789. * { text: '<b>Share</b> This' },
  47790. * { text: 'Move' }
  47791. * ],
  47792. * destructiveText: 'Delete',
  47793. * titleText: 'Modify your album',
  47794. * cancelText: 'Cancel',
  47795. * cancel: function() {
  47796. // add cancel code..
  47797. },
  47798. * buttonClicked: function(index) {
  47799. * return true;
  47800. * }
  47801. * });
  47802. *
  47803. * // For example's sake, hide the sheet after two seconds
  47804. * $timeout(function() {
  47805. * hideSheet();
  47806. * }, 2000);
  47807. *
  47808. * };
  47809. * });
  47810. * ```
  47811. *
  47812. */
  47813. IonicModule
  47814. .factory('$ionicActionSheet', [
  47815. '$rootScope',
  47816. '$compile',
  47817. '$animate',
  47818. '$timeout',
  47819. '$ionicTemplateLoader',
  47820. '$ionicPlatform',
  47821. '$ionicBody',
  47822. 'IONIC_BACK_PRIORITY',
  47823. function($rootScope, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform, $ionicBody, IONIC_BACK_PRIORITY) {
  47824. return {
  47825. show: actionSheet
  47826. };
  47827. /**
  47828. * @ngdoc method
  47829. * @name $ionicActionSheet#show
  47830. * @description
  47831. * Load and return a new action sheet.
  47832. *
  47833. * A new isolated scope will be created for the
  47834. * action sheet and the new element will be appended into the body.
  47835. *
  47836. * @param {object} options The options for this ActionSheet. Properties:
  47837. *
  47838. * - `[Object]` `buttons` Which buttons to show. Each button is an object with a `text` field.
  47839. * - `{string}` `titleText` The title to show on the action sheet.
  47840. * - `{string=}` `cancelText` the text for a 'cancel' button on the action sheet.
  47841. * - `{string=}` `destructiveText` The text for a 'danger' on the action sheet.
  47842. * - `{function=}` `cancel` Called if the cancel button is pressed, the backdrop is tapped or
  47843. * the hardware back button is pressed.
  47844. * - `{function=}` `buttonClicked` Called when one of the non-destructive buttons is clicked,
  47845. * with the index of the button that was clicked and the button object. Return true to close
  47846. * the action sheet, or false to keep it opened.
  47847. * - `{function=}` `destructiveButtonClicked` Called when the destructive button is clicked.
  47848. * Return true to close the action sheet, or false to keep it opened.
  47849. * - `{boolean=}` `cancelOnStateChange` Whether to cancel the actionSheet when navigating
  47850. * to a new state. Default true.
  47851. * - `{string}` `cssClass` The custom CSS class name.
  47852. *
  47853. * @returns {function} `hideSheet` A function which, when called, hides & cancels the action sheet.
  47854. */
  47855. function actionSheet(opts) {
  47856. var scope = $rootScope.$new(true);
  47857. extend(scope, {
  47858. cancel: noop,
  47859. destructiveButtonClicked: noop,
  47860. buttonClicked: noop,
  47861. $deregisterBackButton: noop,
  47862. buttons: [],
  47863. cancelOnStateChange: true
  47864. }, opts || {});
  47865. function textForIcon(text) {
  47866. if (text && /icon/.test(text)) {
  47867. scope.$actionSheetHasIcon = true;
  47868. }
  47869. }
  47870. for (var x = 0; x < scope.buttons.length; x++) {
  47871. textForIcon(scope.buttons[x].text);
  47872. }
  47873. textForIcon(scope.cancelText);
  47874. textForIcon(scope.destructiveText);
  47875. // Compile the template
  47876. var element = scope.element = $compile('<ion-action-sheet ng-class="cssClass" buttons="buttons"></ion-action-sheet>')(scope);
  47877. // Grab the sheet element for animation
  47878. var sheetEl = jqLite(element[0].querySelector('.action-sheet-wrapper'));
  47879. var stateChangeListenDone = scope.cancelOnStateChange ?
  47880. $rootScope.$on('$stateChangeSuccess', function() { scope.cancel(); }) :
  47881. noop;
  47882. // removes the actionSheet from the screen
  47883. scope.removeSheet = function(done) {
  47884. if (scope.removed) return;
  47885. scope.removed = true;
  47886. sheetEl.removeClass('action-sheet-up');
  47887. $timeout(function() {
  47888. // wait to remove this due to a 300ms delay native
  47889. // click which would trigging whatever was underneath this
  47890. $ionicBody.removeClass('action-sheet-open');
  47891. }, 400);
  47892. scope.$deregisterBackButton();
  47893. stateChangeListenDone();
  47894. $animate.removeClass(element, 'active').then(function() {
  47895. scope.$destroy();
  47896. element.remove();
  47897. // scope.cancel.$scope is defined near the bottom
  47898. scope.cancel.$scope = sheetEl = null;
  47899. (done || noop)(opts.buttons);
  47900. });
  47901. };
  47902. scope.showSheet = function(done) {
  47903. if (scope.removed) return;
  47904. $ionicBody.append(element)
  47905. .addClass('action-sheet-open');
  47906. $animate.addClass(element, 'active').then(function() {
  47907. if (scope.removed) return;
  47908. (done || noop)();
  47909. });
  47910. $timeout(function() {
  47911. if (scope.removed) return;
  47912. sheetEl.addClass('action-sheet-up');
  47913. }, 20, false);
  47914. };
  47915. // registerBackButtonAction returns a callback to deregister the action
  47916. scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
  47917. function() {
  47918. $timeout(scope.cancel);
  47919. },
  47920. IONIC_BACK_PRIORITY.actionSheet
  47921. );
  47922. // called when the user presses the cancel button
  47923. scope.cancel = function() {
  47924. // after the animation is out, call the cancel callback
  47925. scope.removeSheet(opts.cancel);
  47926. };
  47927. scope.buttonClicked = function(index) {
  47928. // Check if the button click event returned true, which means
  47929. // we can close the action sheet
  47930. if (opts.buttonClicked(index, opts.buttons[index]) === true) {
  47931. scope.removeSheet();
  47932. }
  47933. };
  47934. scope.destructiveButtonClicked = function() {
  47935. // Check if the destructive button click event returned true, which means
  47936. // we can close the action sheet
  47937. if (opts.destructiveButtonClicked() === true) {
  47938. scope.removeSheet();
  47939. }
  47940. };
  47941. scope.showSheet();
  47942. // Expose the scope on $ionicActionSheet's return value for the sake
  47943. // of testing it.
  47944. scope.cancel.$scope = scope;
  47945. return scope.cancel;
  47946. }
  47947. }]);
  47948. jqLite.prototype.addClass = function(cssClasses) {
  47949. var x, y, cssClass, el, splitClasses, existingClasses;
  47950. if (cssClasses && cssClasses != 'ng-scope' && cssClasses != 'ng-isolate-scope') {
  47951. for (x = 0; x < this.length; x++) {
  47952. el = this[x];
  47953. if (el.setAttribute) {
  47954. if (cssClasses.indexOf(' ') < 0 && el.classList.add) {
  47955. el.classList.add(cssClasses);
  47956. } else {
  47957. existingClasses = (' ' + (el.getAttribute('class') || '') + ' ')
  47958. .replace(/[\n\t]/g, " ");
  47959. splitClasses = cssClasses.split(' ');
  47960. for (y = 0; y < splitClasses.length; y++) {
  47961. cssClass = splitClasses[y].trim();
  47962. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  47963. existingClasses += cssClass + ' ';
  47964. }
  47965. }
  47966. el.setAttribute('class', existingClasses.trim());
  47967. }
  47968. }
  47969. }
  47970. }
  47971. return this;
  47972. };
  47973. jqLite.prototype.removeClass = function(cssClasses) {
  47974. var x, y, splitClasses, cssClass, el;
  47975. if (cssClasses) {
  47976. for (x = 0; x < this.length; x++) {
  47977. el = this[x];
  47978. if (el.getAttribute) {
  47979. if (cssClasses.indexOf(' ') < 0 && el.classList.remove) {
  47980. el.classList.remove(cssClasses);
  47981. } else {
  47982. splitClasses = cssClasses.split(' ');
  47983. for (y = 0; y < splitClasses.length; y++) {
  47984. cssClass = splitClasses[y];
  47985. el.setAttribute('class', (
  47986. (" " + (el.getAttribute('class') || '') + " ")
  47987. .replace(/[\n\t]/g, " ")
  47988. .replace(" " + cssClass.trim() + " ", " ")).trim()
  47989. );
  47990. }
  47991. }
  47992. }
  47993. }
  47994. }
  47995. return this;
  47996. };
  47997. /**
  47998. * @ngdoc service
  47999. * @name $ionicBackdrop
  48000. * @module ionic
  48001. * @description
  48002. * Shows and hides a backdrop over the UI. Appears behind popups, loading,
  48003. * and other overlays.
  48004. *
  48005. * Often, multiple UI components require a backdrop, but only one backdrop is
  48006. * ever needed in the DOM at a time.
  48007. *
  48008. * Therefore, each component that requires the backdrop to be shown calls
  48009. * `$ionicBackdrop.retain()` when it wants the backdrop, then `$ionicBackdrop.release()`
  48010. * when it is done with the backdrop.
  48011. *
  48012. * For each time `retain` is called, the backdrop will be shown until `release` is called.
  48013. *
  48014. * For example, if `retain` is called three times, the backdrop will be shown until `release`
  48015. * is called three times.
  48016. *
  48017. * **Notes:**
  48018. * - The backdrop service will broadcast 'backdrop.shown' and 'backdrop.hidden' events from the root scope,
  48019. * this is useful for alerting native components not in html.
  48020. *
  48021. * @usage
  48022. *
  48023. * ```js
  48024. * function MyController($scope, $ionicBackdrop, $timeout, $rootScope) {
  48025. * //Show a backdrop for one second
  48026. * $scope.action = function() {
  48027. * $ionicBackdrop.retain();
  48028. * $timeout(function() {
  48029. * $ionicBackdrop.release();
  48030. * }, 1000);
  48031. * };
  48032. *
  48033. * // Execute action on backdrop disappearing
  48034. * $scope.$on('backdrop.hidden', function() {
  48035. * // Execute action
  48036. * });
  48037. *
  48038. * // Execute action on backdrop appearing
  48039. * $scope.$on('backdrop.shown', function() {
  48040. * // Execute action
  48041. * });
  48042. *
  48043. * }
  48044. * ```
  48045. */
  48046. IonicModule
  48047. .factory('$ionicBackdrop', [
  48048. '$document', '$timeout', '$$rAF', '$rootScope',
  48049. function($document, $timeout, $$rAF, $rootScope) {
  48050. var el = jqLite('<div class="backdrop">');
  48051. var backdropHolds = 0;
  48052. $document[0].body.appendChild(el[0]);
  48053. return {
  48054. /**
  48055. * @ngdoc method
  48056. * @name $ionicBackdrop#retain
  48057. * @description Retains the backdrop.
  48058. */
  48059. retain: retain,
  48060. /**
  48061. * @ngdoc method
  48062. * @name $ionicBackdrop#release
  48063. * @description
  48064. * Releases the backdrop.
  48065. */
  48066. release: release,
  48067. getElement: getElement,
  48068. // exposed for testing
  48069. _element: el
  48070. };
  48071. function retain() {
  48072. backdropHolds++;
  48073. if (backdropHolds === 1) {
  48074. el.addClass('visible');
  48075. $rootScope.$broadcast('backdrop.shown');
  48076. $$rAF(function() {
  48077. // If we're still at >0 backdropHolds after async...
  48078. if (backdropHolds >= 1) el.addClass('active');
  48079. });
  48080. }
  48081. }
  48082. function release() {
  48083. if (backdropHolds === 1) {
  48084. el.removeClass('active');
  48085. $rootScope.$broadcast('backdrop.hidden');
  48086. $timeout(function() {
  48087. // If we're still at 0 backdropHolds after async...
  48088. if (backdropHolds === 0) el.removeClass('visible');
  48089. }, 400, false);
  48090. }
  48091. backdropHolds = Math.max(0, backdropHolds - 1);
  48092. }
  48093. function getElement() {
  48094. return el;
  48095. }
  48096. }]);
  48097. /**
  48098. * @private
  48099. */
  48100. IonicModule
  48101. .factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {
  48102. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  48103. return function(scope, attrs, bindDefinition) {
  48104. forEach(bindDefinition || {}, function(definition, scopeName) {
  48105. //Adapted from angular.js $compile
  48106. var match = definition.match(LOCAL_REGEXP) || [],
  48107. attrName = match[3] || scopeName,
  48108. mode = match[1], // @, =, or &
  48109. parentGet,
  48110. unwatch;
  48111. switch (mode) {
  48112. case '@':
  48113. if (!attrs[attrName]) {
  48114. return;
  48115. }
  48116. attrs.$observe(attrName, function(value) {
  48117. scope[scopeName] = value;
  48118. });
  48119. // we trigger an interpolation to ensure
  48120. // the value is there for use immediately
  48121. if (attrs[attrName]) {
  48122. scope[scopeName] = $interpolate(attrs[attrName])(scope);
  48123. }
  48124. break;
  48125. case '=':
  48126. if (!attrs[attrName]) {
  48127. return;
  48128. }
  48129. unwatch = scope.$watch(attrs[attrName], function(value) {
  48130. scope[scopeName] = value;
  48131. });
  48132. //Destroy parent scope watcher when this scope is destroyed
  48133. scope.$on('$destroy', unwatch);
  48134. break;
  48135. case '&':
  48136. /* jshint -W044 */
  48137. if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\(.*?\)'))) {
  48138. throw new Error('& expression binding "' + scopeName + '" looks like it will recursively call "' +
  48139. attrs[attrName] + '" and cause a stack overflow! Please choose a different scopeName.');
  48140. }
  48141. parentGet = $parse(attrs[attrName]);
  48142. scope[scopeName] = function(locals) {
  48143. return parentGet(scope, locals);
  48144. };
  48145. break;
  48146. }
  48147. });
  48148. };
  48149. }]);
  48150. /**
  48151. * @ngdoc service
  48152. * @name $ionicBody
  48153. * @module ionic
  48154. * @description An angular utility service to easily and efficiently
  48155. * add and remove CSS classes from the document's body element.
  48156. */
  48157. IonicModule
  48158. .factory('$ionicBody', ['$document', function($document) {
  48159. return {
  48160. /**
  48161. * @ngdoc method
  48162. * @name $ionicBody#addClass
  48163. * @description Add a class to the document's body element.
  48164. * @param {string} class Each argument will be added to the body element.
  48165. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48166. */
  48167. addClass: function() {
  48168. for (var x = 0; x < arguments.length; x++) {
  48169. $document[0].body.classList.add(arguments[x]);
  48170. }
  48171. return this;
  48172. },
  48173. /**
  48174. * @ngdoc method
  48175. * @name $ionicBody#removeClass
  48176. * @description Remove a class from the document's body element.
  48177. * @param {string} class Each argument will be removed from the body element.
  48178. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48179. */
  48180. removeClass: function() {
  48181. for (var x = 0; x < arguments.length; x++) {
  48182. $document[0].body.classList.remove(arguments[x]);
  48183. }
  48184. return this;
  48185. },
  48186. /**
  48187. * @ngdoc method
  48188. * @name $ionicBody#enableClass
  48189. * @description Similar to the `add` method, except the first parameter accepts a boolean
  48190. * value determining if the class should be added or removed. Rather than writing user code,
  48191. * such as "if true then add the class, else then remove the class", this method can be
  48192. * given a true or false value which reduces redundant code.
  48193. * @param {boolean} shouldEnableClass A true/false value if the class should be added or removed.
  48194. * @param {string} class Each remaining argument would be added or removed depending on
  48195. * the first argument.
  48196. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48197. */
  48198. enableClass: function(shouldEnableClass) {
  48199. var args = Array.prototype.slice.call(arguments).slice(1);
  48200. if (shouldEnableClass) {
  48201. this.addClass.apply(this, args);
  48202. } else {
  48203. this.removeClass.apply(this, args);
  48204. }
  48205. return this;
  48206. },
  48207. /**
  48208. * @ngdoc method
  48209. * @name $ionicBody#append
  48210. * @description Append a child to the document's body.
  48211. * @param {element} element The element to be appended to the body. The passed in element
  48212. * can be either a jqLite element, or a DOM element.
  48213. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48214. */
  48215. append: function(ele) {
  48216. $document[0].body.appendChild(ele.length ? ele[0] : ele);
  48217. return this;
  48218. },
  48219. /**
  48220. * @ngdoc method
  48221. * @name $ionicBody#get
  48222. * @description Get the document's body element.
  48223. * @returns {element} Returns the document's body element.
  48224. */
  48225. get: function() {
  48226. return $document[0].body;
  48227. }
  48228. };
  48229. }]);
  48230. IonicModule
  48231. .factory('$ionicClickBlock', [
  48232. '$document',
  48233. '$ionicBody',
  48234. '$timeout',
  48235. function($document, $ionicBody, $timeout) {
  48236. var CSS_HIDE = 'click-block-hide';
  48237. var cbEle, fallbackTimer, pendingShow;
  48238. function preventClick(ev) {
  48239. ev.preventDefault();
  48240. ev.stopPropagation();
  48241. }
  48242. function addClickBlock() {
  48243. if (pendingShow) {
  48244. if (cbEle) {
  48245. cbEle.classList.remove(CSS_HIDE);
  48246. } else {
  48247. cbEle = $document[0].createElement('div');
  48248. cbEle.className = 'click-block';
  48249. $ionicBody.append(cbEle);
  48250. cbEle.addEventListener('touchstart', preventClick);
  48251. cbEle.addEventListener('mousedown', preventClick);
  48252. }
  48253. pendingShow = false;
  48254. }
  48255. }
  48256. function removeClickBlock() {
  48257. cbEle && cbEle.classList.add(CSS_HIDE);
  48258. }
  48259. return {
  48260. show: function(autoExpire) {
  48261. pendingShow = true;
  48262. $timeout.cancel(fallbackTimer);
  48263. fallbackTimer = $timeout(this.hide, autoExpire || 310, false);
  48264. addClickBlock();
  48265. },
  48266. hide: function() {
  48267. pendingShow = false;
  48268. $timeout.cancel(fallbackTimer);
  48269. removeClickBlock();
  48270. }
  48271. };
  48272. }]);
  48273. /**
  48274. * @ngdoc service
  48275. * @name $ionicGesture
  48276. * @module ionic
  48277. * @description An angular service exposing ionic
  48278. * {@link ionic.utility:ionic.EventController}'s gestures.
  48279. */
  48280. IonicModule
  48281. .factory('$ionicGesture', [function() {
  48282. return {
  48283. /**
  48284. * @ngdoc method
  48285. * @name $ionicGesture#on
  48286. * @description Add an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#onGesture}.
  48287. * @param {string} eventType The gesture event to listen for.
  48288. * @param {function(e)} callback The function to call when the gesture
  48289. * happens.
  48290. * @param {element} $element The angular element to listen for the event on.
  48291. * @param {object} options object.
  48292. * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).
  48293. */
  48294. on: function(eventType, cb, $element, options) {
  48295. return window.ionic.onGesture(eventType, cb, $element[0], options);
  48296. },
  48297. /**
  48298. * @ngdoc method
  48299. * @name $ionicGesture#off
  48300. * @description Remove an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#offGesture}.
  48301. * @param {ionic.Gesture} gesture The gesture that should be removed.
  48302. * @param {string} eventType The gesture event to remove the listener for.
  48303. * @param {function(e)} callback The listener to remove.
  48304. */
  48305. off: function(gesture, eventType, cb) {
  48306. return window.ionic.offGesture(gesture, eventType, cb);
  48307. }
  48308. };
  48309. }]);
  48310. /**
  48311. * @ngdoc service
  48312. * @name $ionicHistory
  48313. * @module ionic
  48314. * @description
  48315. * $ionicHistory keeps track of views as the user navigates through an app. Similar to the way a
  48316. * browser behaves, an Ionic app is able to keep track of the previous view, the current view, and
  48317. * the forward view (if there is one). However, a typical web browser only keeps track of one
  48318. * history stack in a linear fashion.
  48319. *
  48320. * Unlike a traditional browser environment, apps and webapps have parallel independent histories,
  48321. * such as with tabs. Should a user navigate few pages deep on one tab, and then switch to a new
  48322. * tab and back, the back button relates not to the previous tab, but to the previous pages
  48323. * visited within _that_ tab.
  48324. *
  48325. * `$ionicHistory` facilitates this parallel history architecture.
  48326. */
  48327. IonicModule
  48328. .factory('$ionicHistory', [
  48329. '$rootScope',
  48330. '$state',
  48331. '$location',
  48332. '$window',
  48333. '$timeout',
  48334. '$ionicViewSwitcher',
  48335. '$ionicNavViewDelegate',
  48336. function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
  48337. // history actions while navigating views
  48338. var ACTION_INITIAL_VIEW = 'initialView';
  48339. var ACTION_NEW_VIEW = 'newView';
  48340. var ACTION_MOVE_BACK = 'moveBack';
  48341. var ACTION_MOVE_FORWARD = 'moveForward';
  48342. // direction of navigation
  48343. var DIRECTION_BACK = 'back';
  48344. var DIRECTION_FORWARD = 'forward';
  48345. var DIRECTION_ENTER = 'enter';
  48346. var DIRECTION_EXIT = 'exit';
  48347. var DIRECTION_SWAP = 'swap';
  48348. var DIRECTION_NONE = 'none';
  48349. var stateChangeCounter = 0;
  48350. var lastStateId, nextViewOptions, deregisterStateChangeListener, nextViewExpireTimer, forcedNav;
  48351. var viewHistory = {
  48352. histories: { root: { historyId: 'root', parentHistoryId: null, stack: [], cursor: -1 } },
  48353. views: {},
  48354. backView: null,
  48355. forwardView: null,
  48356. currentView: null
  48357. };
  48358. var View = function() {};
  48359. View.prototype.initialize = function(data) {
  48360. if (data) {
  48361. for (var name in data) this[name] = data[name];
  48362. return this;
  48363. }
  48364. return null;
  48365. };
  48366. View.prototype.go = function() {
  48367. if (this.stateName) {
  48368. return $state.go(this.stateName, this.stateParams);
  48369. }
  48370. if (this.url && this.url !== $location.url()) {
  48371. if (viewHistory.backView === this) {
  48372. return $window.history.go(-1);
  48373. } else if (viewHistory.forwardView === this) {
  48374. return $window.history.go(1);
  48375. }
  48376. $location.url(this.url);
  48377. }
  48378. return null;
  48379. };
  48380. View.prototype.destroy = function() {
  48381. if (this.scope) {
  48382. this.scope.$destroy && this.scope.$destroy();
  48383. this.scope = null;
  48384. }
  48385. };
  48386. function getViewById(viewId) {
  48387. return (viewId ? viewHistory.views[ viewId ] : null);
  48388. }
  48389. function getBackView(view) {
  48390. return (view ? getViewById(view.backViewId) : null);
  48391. }
  48392. function getForwardView(view) {
  48393. return (view ? getViewById(view.forwardViewId) : null);
  48394. }
  48395. function getHistoryById(historyId) {
  48396. return (historyId ? viewHistory.histories[ historyId ] : null);
  48397. }
  48398. function getHistory(scope) {
  48399. var histObj = getParentHistoryObj(scope);
  48400. if (!viewHistory.histories[ histObj.historyId ]) {
  48401. // this history object exists in parent scope, but doesn't
  48402. // exist in the history data yet
  48403. viewHistory.histories[ histObj.historyId ] = {
  48404. historyId: histObj.historyId,
  48405. parentHistoryId: getParentHistoryObj(histObj.scope.$parent).historyId,
  48406. stack: [],
  48407. cursor: -1
  48408. };
  48409. }
  48410. return getHistoryById(histObj.historyId);
  48411. }
  48412. function getParentHistoryObj(scope) {
  48413. var parentScope = scope;
  48414. while (parentScope) {
  48415. if (parentScope.hasOwnProperty('$historyId')) {
  48416. // this parent scope has a historyId
  48417. return { historyId: parentScope.$historyId, scope: parentScope };
  48418. }
  48419. // nothing found keep climbing up
  48420. parentScope = parentScope.$parent;
  48421. }
  48422. // no history for the parent, use the root
  48423. return { historyId: 'root', scope: $rootScope };
  48424. }
  48425. function setNavViews(viewId) {
  48426. viewHistory.currentView = getViewById(viewId);
  48427. viewHistory.backView = getBackView(viewHistory.currentView);
  48428. viewHistory.forwardView = getForwardView(viewHistory.currentView);
  48429. }
  48430. function getCurrentStateId() {
  48431. var id;
  48432. if ($state && $state.current && $state.current.name) {
  48433. id = $state.current.name;
  48434. if ($state.params) {
  48435. for (var key in $state.params) {
  48436. if ($state.params.hasOwnProperty(key) && $state.params[key]) {
  48437. id += "_" + key + "=" + $state.params[key];
  48438. }
  48439. }
  48440. }
  48441. return id;
  48442. }
  48443. // if something goes wrong make sure its got a unique stateId
  48444. return ionic.Utils.nextUid();
  48445. }
  48446. function getCurrentStateParams() {
  48447. var rtn;
  48448. if ($state && $state.params) {
  48449. for (var key in $state.params) {
  48450. if ($state.params.hasOwnProperty(key)) {
  48451. rtn = rtn || {};
  48452. rtn[key] = $state.params[key];
  48453. }
  48454. }
  48455. }
  48456. return rtn;
  48457. }
  48458. return {
  48459. register: function(parentScope, viewLocals) {
  48460. var currentStateId = getCurrentStateId(),
  48461. hist = getHistory(parentScope),
  48462. currentView = viewHistory.currentView,
  48463. backView = viewHistory.backView,
  48464. forwardView = viewHistory.forwardView,
  48465. viewId = null,
  48466. action = null,
  48467. direction = DIRECTION_NONE,
  48468. historyId = hist.historyId,
  48469. url = $location.url(),
  48470. tmp, x, ele;
  48471. if (lastStateId !== currentStateId) {
  48472. lastStateId = currentStateId;
  48473. stateChangeCounter++;
  48474. }
  48475. if (forcedNav) {
  48476. // we've previously set exactly what to do
  48477. viewId = forcedNav.viewId;
  48478. action = forcedNav.action;
  48479. direction = forcedNav.direction;
  48480. forcedNav = null;
  48481. } else if (backView && backView.stateId === currentStateId) {
  48482. // they went back one, set the old current view as a forward view
  48483. viewId = backView.viewId;
  48484. historyId = backView.historyId;
  48485. action = ACTION_MOVE_BACK;
  48486. if (backView.historyId === currentView.historyId) {
  48487. // went back in the same history
  48488. direction = DIRECTION_BACK;
  48489. } else if (currentView) {
  48490. direction = DIRECTION_EXIT;
  48491. tmp = getHistoryById(backView.historyId);
  48492. if (tmp && tmp.parentHistoryId === currentView.historyId) {
  48493. direction = DIRECTION_ENTER;
  48494. } else {
  48495. tmp = getHistoryById(currentView.historyId);
  48496. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48497. direction = DIRECTION_SWAP;
  48498. }
  48499. }
  48500. }
  48501. } else if (forwardView && forwardView.stateId === currentStateId) {
  48502. // they went to the forward one, set the forward view to no longer a forward view
  48503. viewId = forwardView.viewId;
  48504. historyId = forwardView.historyId;
  48505. action = ACTION_MOVE_FORWARD;
  48506. if (forwardView.historyId === currentView.historyId) {
  48507. direction = DIRECTION_FORWARD;
  48508. } else if (currentView) {
  48509. direction = DIRECTION_EXIT;
  48510. if (currentView.historyId === hist.parentHistoryId) {
  48511. direction = DIRECTION_ENTER;
  48512. } else {
  48513. tmp = getHistoryById(currentView.historyId);
  48514. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48515. direction = DIRECTION_SWAP;
  48516. }
  48517. }
  48518. }
  48519. tmp = getParentHistoryObj(parentScope);
  48520. if (forwardView.historyId && tmp.scope) {
  48521. // if a history has already been created by the forward view then make sure it stays the same
  48522. tmp.scope.$historyId = forwardView.historyId;
  48523. historyId = forwardView.historyId;
  48524. }
  48525. } else if (currentView && currentView.historyId !== historyId &&
  48526. hist.cursor > -1 && hist.stack.length > 0 && hist.cursor < hist.stack.length &&
  48527. hist.stack[hist.cursor].stateId === currentStateId) {
  48528. // they just changed to a different history and the history already has views in it
  48529. var switchToView = hist.stack[hist.cursor];
  48530. viewId = switchToView.viewId;
  48531. historyId = switchToView.historyId;
  48532. action = ACTION_MOVE_BACK;
  48533. direction = DIRECTION_SWAP;
  48534. tmp = getHistoryById(currentView.historyId);
  48535. if (tmp && tmp.parentHistoryId === historyId) {
  48536. direction = DIRECTION_EXIT;
  48537. } else {
  48538. tmp = getHistoryById(historyId);
  48539. if (tmp && tmp.parentHistoryId === currentView.historyId) {
  48540. direction = DIRECTION_ENTER;
  48541. }
  48542. }
  48543. // if switching to a different history, and the history of the view we're switching
  48544. // to has an existing back view from a different history than itself, then
  48545. // it's back view would be better represented using the current view as its back view
  48546. tmp = getViewById(switchToView.backViewId);
  48547. if (tmp && switchToView.historyId !== tmp.historyId) {
  48548. // the new view is being removed from it's old position in the history and being placed at the top,
  48549. // so we need to update any views that reference it as a backview, otherwise there will be infinitely loops
  48550. var viewIds = Object.keys(viewHistory.views);
  48551. viewIds.forEach(function(viewId) {
  48552. var view = viewHistory.views[viewId];
  48553. if ( view.backViewId === switchToView.viewId ) {
  48554. view.backViewId = null;
  48555. }
  48556. });
  48557. hist.stack[hist.cursor].backViewId = currentView.viewId;
  48558. }
  48559. } else {
  48560. // create an element from the viewLocals template
  48561. ele = $ionicViewSwitcher.createViewEle(viewLocals);
  48562. if (this.isAbstractEle(ele, viewLocals)) {
  48563. return {
  48564. action: 'abstractView',
  48565. direction: DIRECTION_NONE,
  48566. ele: ele
  48567. };
  48568. }
  48569. // set a new unique viewId
  48570. viewId = ionic.Utils.nextUid();
  48571. if (currentView) {
  48572. // set the forward view if there is a current view (ie: if its not the first view)
  48573. currentView.forwardViewId = viewId;
  48574. action = ACTION_NEW_VIEW;
  48575. // check if there is a new forward view within the same history
  48576. if (forwardView && currentView.stateId !== forwardView.stateId &&
  48577. currentView.historyId === forwardView.historyId) {
  48578. // they navigated to a new view but the stack already has a forward view
  48579. // since its a new view remove any forwards that existed
  48580. tmp = getHistoryById(forwardView.historyId);
  48581. if (tmp) {
  48582. // the forward has a history
  48583. for (x = tmp.stack.length - 1; x >= forwardView.index; x--) {
  48584. // starting from the end destroy all forwards in this history from this point
  48585. var stackItem = tmp.stack[x];
  48586. stackItem && stackItem.destroy && stackItem.destroy();
  48587. tmp.stack.splice(x);
  48588. }
  48589. historyId = forwardView.historyId;
  48590. }
  48591. }
  48592. // its only moving forward if its in the same history
  48593. if (hist.historyId === currentView.historyId) {
  48594. direction = DIRECTION_FORWARD;
  48595. } else if (currentView.historyId !== hist.historyId) {
  48596. // DB: this is a new view in a different tab
  48597. direction = DIRECTION_ENTER;
  48598. tmp = getHistoryById(currentView.historyId);
  48599. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48600. direction = DIRECTION_SWAP;
  48601. } else {
  48602. tmp = getHistoryById(tmp.parentHistoryId);
  48603. if (tmp && tmp.historyId === hist.historyId) {
  48604. direction = DIRECTION_EXIT;
  48605. }
  48606. }
  48607. }
  48608. } else {
  48609. // there's no current view, so this must be the initial view
  48610. action = ACTION_INITIAL_VIEW;
  48611. }
  48612. if (stateChangeCounter < 2) {
  48613. // views that were spun up on the first load should not animate
  48614. direction = DIRECTION_NONE;
  48615. }
  48616. // add the new view
  48617. viewHistory.views[viewId] = this.createView({
  48618. viewId: viewId,
  48619. index: hist.stack.length,
  48620. historyId: hist.historyId,
  48621. backViewId: (currentView && currentView.viewId ? currentView.viewId : null),
  48622. forwardViewId: null,
  48623. stateId: currentStateId,
  48624. stateName: this.currentStateName(),
  48625. stateParams: getCurrentStateParams(),
  48626. url: url,
  48627. canSwipeBack: canSwipeBack(ele, viewLocals)
  48628. });
  48629. // add the new view to this history's stack
  48630. hist.stack.push(viewHistory.views[viewId]);
  48631. }
  48632. deregisterStateChangeListener && deregisterStateChangeListener();
  48633. $timeout.cancel(nextViewExpireTimer);
  48634. if (nextViewOptions) {
  48635. if (nextViewOptions.disableAnimate) direction = DIRECTION_NONE;
  48636. if (nextViewOptions.disableBack) viewHistory.views[viewId].backViewId = null;
  48637. if (nextViewOptions.historyRoot) {
  48638. for (x = 0; x < hist.stack.length; x++) {
  48639. if (hist.stack[x].viewId === viewId) {
  48640. hist.stack[x].index = 0;
  48641. hist.stack[x].backViewId = hist.stack[x].forwardViewId = null;
  48642. } else {
  48643. delete viewHistory.views[hist.stack[x].viewId];
  48644. }
  48645. }
  48646. hist.stack = [viewHistory.views[viewId]];
  48647. }
  48648. nextViewOptions = null;
  48649. }
  48650. setNavViews(viewId);
  48651. if (viewHistory.backView && historyId == viewHistory.backView.historyId && currentStateId == viewHistory.backView.stateId && url == viewHistory.backView.url) {
  48652. for (x = 0; x < hist.stack.length; x++) {
  48653. if (hist.stack[x].viewId == viewId) {
  48654. action = 'dupNav';
  48655. direction = DIRECTION_NONE;
  48656. if (x > 0) {
  48657. hist.stack[x - 1].forwardViewId = null;
  48658. }
  48659. viewHistory.forwardView = null;
  48660. viewHistory.currentView.index = viewHistory.backView.index;
  48661. viewHistory.currentView.backViewId = viewHistory.backView.backViewId;
  48662. viewHistory.backView = getBackView(viewHistory.backView);
  48663. hist.stack.splice(x, 1);
  48664. break;
  48665. }
  48666. }
  48667. }
  48668. hist.cursor = viewHistory.currentView.index;
  48669. return {
  48670. viewId: viewId,
  48671. action: action,
  48672. direction: direction,
  48673. historyId: historyId,
  48674. enableBack: this.enabledBack(viewHistory.currentView),
  48675. isHistoryRoot: (viewHistory.currentView.index === 0),
  48676. ele: ele
  48677. };
  48678. },
  48679. registerHistory: function(scope) {
  48680. scope.$historyId = ionic.Utils.nextUid();
  48681. },
  48682. createView: function(data) {
  48683. var newView = new View();
  48684. return newView.initialize(data);
  48685. },
  48686. getViewById: getViewById,
  48687. /**
  48688. * @ngdoc method
  48689. * @name $ionicHistory#viewHistory
  48690. * @description The app's view history data, such as all the views and histories, along
  48691. * with how they are ordered and linked together within the navigation stack.
  48692. * @returns {object} Returns an object containing the apps view history data.
  48693. */
  48694. viewHistory: function() {
  48695. return viewHistory;
  48696. },
  48697. /**
  48698. * @ngdoc method
  48699. * @name $ionicHistory#currentView
  48700. * @description The app's current view.
  48701. * @returns {object} Returns the current view.
  48702. */
  48703. currentView: function(view) {
  48704. if (arguments.length) {
  48705. viewHistory.currentView = view;
  48706. }
  48707. return viewHistory.currentView;
  48708. },
  48709. /**
  48710. * @ngdoc method
  48711. * @name $ionicHistory#currentHistoryId
  48712. * @description The ID of the history stack which is the parent container of the current view.
  48713. * @returns {string} Returns the current history ID.
  48714. */
  48715. currentHistoryId: function() {
  48716. return viewHistory.currentView ? viewHistory.currentView.historyId : null;
  48717. },
  48718. /**
  48719. * @ngdoc method
  48720. * @name $ionicHistory#currentTitle
  48721. * @description Gets and sets the current view's title.
  48722. * @param {string=} val The title to update the current view with.
  48723. * @returns {string} Returns the current view's title.
  48724. */
  48725. currentTitle: function(val) {
  48726. if (viewHistory.currentView) {
  48727. if (arguments.length) {
  48728. viewHistory.currentView.title = val;
  48729. }
  48730. return viewHistory.currentView.title;
  48731. }
  48732. },
  48733. /**
  48734. * @ngdoc method
  48735. * @name $ionicHistory#backView
  48736. * @description Returns the view that was before the current view in the history stack.
  48737. * If the user navigated from View A to View B, then View A would be the back view, and
  48738. * View B would be the current view.
  48739. * @returns {object} Returns the back view.
  48740. */
  48741. backView: function(view) {
  48742. if (arguments.length) {
  48743. viewHistory.backView = view;
  48744. }
  48745. return viewHistory.backView;
  48746. },
  48747. /**
  48748. * @ngdoc method
  48749. * @name $ionicHistory#backTitle
  48750. * @description Gets the back view's title.
  48751. * @returns {string} Returns the back view's title.
  48752. */
  48753. backTitle: function(view) {
  48754. var backView = (view && getViewById(view.backViewId)) || viewHistory.backView;
  48755. return backView && backView.title;
  48756. },
  48757. /**
  48758. * @ngdoc method
  48759. * @name $ionicHistory#forwardView
  48760. * @description Returns the view that was in front of the current view in the history stack.
  48761. * A forward view would exist if the user navigated from View A to View B, then
  48762. * navigated back to View A. At this point then View B would be the forward view, and View
  48763. * A would be the current view.
  48764. * @returns {object} Returns the forward view.
  48765. */
  48766. forwardView: function(view) {
  48767. if (arguments.length) {
  48768. viewHistory.forwardView = view;
  48769. }
  48770. return viewHistory.forwardView;
  48771. },
  48772. /**
  48773. * @ngdoc method
  48774. * @name $ionicHistory#currentStateName
  48775. * @description Returns the current state name.
  48776. * @returns {string}
  48777. */
  48778. currentStateName: function() {
  48779. return ($state && $state.current ? $state.current.name : null);
  48780. },
  48781. isCurrentStateNavView: function(navView) {
  48782. return !!($state && $state.current && $state.current.views && $state.current.views[navView]);
  48783. },
  48784. goToHistoryRoot: function(historyId) {
  48785. if (historyId) {
  48786. var hist = getHistoryById(historyId);
  48787. if (hist && hist.stack.length) {
  48788. if (viewHistory.currentView && viewHistory.currentView.viewId === hist.stack[0].viewId) {
  48789. return;
  48790. }
  48791. forcedNav = {
  48792. viewId: hist.stack[0].viewId,
  48793. action: ACTION_MOVE_BACK,
  48794. direction: DIRECTION_BACK
  48795. };
  48796. hist.stack[0].go();
  48797. }
  48798. }
  48799. },
  48800. /**
  48801. * @ngdoc method
  48802. * @name $ionicHistory#goBack
  48803. * @param {number=} backCount Optional negative integer setting how many views to go
  48804. * back. By default it'll go back one view by using the value `-1`. To go back two
  48805. * views you would use `-2`. If the number goes farther back than the number of views
  48806. * in the current history's stack then it'll go to the first view in the current history's
  48807. * stack. If the number is zero or greater then it'll do nothing. It also does not
  48808. * cross history stacks, meaning it can only go as far back as the current history.
  48809. * @description Navigates the app to the back view, if a back view exists.
  48810. */
  48811. goBack: function(backCount) {
  48812. if (isDefined(backCount) && backCount !== -1) {
  48813. if (backCount > -1) return;
  48814. var currentHistory = viewHistory.histories[this.currentHistoryId()];
  48815. var newCursor = currentHistory.cursor + backCount + 1;
  48816. if (newCursor < 1) {
  48817. newCursor = 1;
  48818. }
  48819. currentHistory.cursor = newCursor;
  48820. setNavViews(currentHistory.stack[newCursor].viewId);
  48821. var cursor = newCursor - 1;
  48822. var clearStateIds = [];
  48823. var fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);
  48824. while (fwdView) {
  48825. clearStateIds.push(fwdView.stateId || fwdView.viewId);
  48826. cursor++;
  48827. if (cursor >= currentHistory.stack.length) break;
  48828. fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);
  48829. }
  48830. var self = this;
  48831. if (clearStateIds.length) {
  48832. $timeout(function() {
  48833. self.clearCache(clearStateIds);
  48834. }, 300);
  48835. }
  48836. }
  48837. viewHistory.backView && viewHistory.backView.go();
  48838. },
  48839. /**
  48840. * @ngdoc method
  48841. * @name $ionicHistory#removeBackView
  48842. * @description Remove the previous view from the history completely, including the
  48843. * cached element and scope (if they exist).
  48844. */
  48845. removeBackView: function() {
  48846. var self = this;
  48847. var currentHistory = viewHistory.histories[this.currentHistoryId()];
  48848. var currentCursor = currentHistory.cursor;
  48849. var currentView = currentHistory.stack[currentCursor];
  48850. var backView = currentHistory.stack[currentCursor - 1];
  48851. var replacementView = currentHistory.stack[currentCursor - 2];
  48852. // fail if we dont have enough views in the history
  48853. if (!backView || !replacementView) {
  48854. return;
  48855. }
  48856. // remove the old backView and the cached element/scope
  48857. currentHistory.stack.splice(currentCursor - 1, 1);
  48858. self.clearCache([backView.viewId]);
  48859. // make the replacementView and currentView point to each other (bypass the old backView)
  48860. currentView.backViewId = replacementView.viewId;
  48861. currentView.index = currentView.index - 1;
  48862. replacementView.forwardViewId = currentView.viewId;
  48863. // update the cursor and set new backView
  48864. viewHistory.backView = replacementView;
  48865. currentHistory.currentCursor += -1;
  48866. },
  48867. enabledBack: function(view) {
  48868. var backView = getBackView(view);
  48869. return !!(backView && backView.historyId === view.historyId);
  48870. },
  48871. /**
  48872. * @ngdoc method
  48873. * @name $ionicHistory#clearHistory
  48874. * @description Clears out the app's entire history, except for the current view.
  48875. */
  48876. clearHistory: function() {
  48877. var
  48878. histories = viewHistory.histories,
  48879. currentView = viewHistory.currentView;
  48880. if (histories) {
  48881. for (var historyId in histories) {
  48882. if (histories[historyId].stack) {
  48883. histories[historyId].stack = [];
  48884. histories[historyId].cursor = -1;
  48885. }
  48886. if (currentView && currentView.historyId === historyId) {
  48887. currentView.backViewId = currentView.forwardViewId = null;
  48888. histories[historyId].stack.push(currentView);
  48889. } else if (histories[historyId].destroy) {
  48890. histories[historyId].destroy();
  48891. }
  48892. }
  48893. }
  48894. for (var viewId in viewHistory.views) {
  48895. if (viewId !== currentView.viewId) {
  48896. delete viewHistory.views[viewId];
  48897. }
  48898. }
  48899. if (currentView) {
  48900. setNavViews(currentView.viewId);
  48901. }
  48902. },
  48903. /**
  48904. * @ngdoc method
  48905. * @name $ionicHistory#clearCache
  48906. * @return promise
  48907. * @description Removes all cached views within every {@link ionic.directive:ionNavView}.
  48908. * This both removes the view element from the DOM, and destroy it's scope.
  48909. */
  48910. clearCache: function(stateIds) {
  48911. return $timeout(function() {
  48912. $ionicNavViewDelegate._instances.forEach(function(instance) {
  48913. instance.clearCache(stateIds);
  48914. });
  48915. });
  48916. },
  48917. /**
  48918. * @ngdoc method
  48919. * @name $ionicHistory#nextViewOptions
  48920. * @description Sets options for the next view. This method can be useful to override
  48921. * certain view/transition defaults right before a view transition happens. For example,
  48922. * the {@link ionic.directive:menuClose} directive uses this method internally to ensure
  48923. * an animated view transition does not happen when a side menu is open, and also sets
  48924. * the next view as the root of its history stack. After the transition these options
  48925. * are set back to null.
  48926. *
  48927. * Available options:
  48928. *
  48929. * * `disableAnimate`: Do not animate the next transition.
  48930. * * `disableBack`: The next view should forget its back view, and set it to null.
  48931. * * `historyRoot`: The next view should become the root view in its history stack.
  48932. *
  48933. * ```js
  48934. * $ionicHistory.nextViewOptions({
  48935. * disableAnimate: true,
  48936. * disableBack: true
  48937. * });
  48938. * ```
  48939. */
  48940. nextViewOptions: function(opts) {
  48941. deregisterStateChangeListener && deregisterStateChangeListener();
  48942. if (arguments.length) {
  48943. $timeout.cancel(nextViewExpireTimer);
  48944. if (opts === null) {
  48945. nextViewOptions = opts;
  48946. } else {
  48947. nextViewOptions = nextViewOptions || {};
  48948. extend(nextViewOptions, opts);
  48949. if (nextViewOptions.expire) {
  48950. deregisterStateChangeListener = $rootScope.$on('$stateChangeSuccess', function() {
  48951. nextViewExpireTimer = $timeout(function() {
  48952. nextViewOptions = null;
  48953. }, nextViewOptions.expire);
  48954. });
  48955. }
  48956. }
  48957. }
  48958. return nextViewOptions;
  48959. },
  48960. isAbstractEle: function(ele, viewLocals) {
  48961. if (viewLocals && viewLocals.$$state && viewLocals.$$state.self['abstract']) {
  48962. return true;
  48963. }
  48964. return !!(ele && (isAbstractTag(ele) || isAbstractTag(ele.children())));
  48965. },
  48966. isActiveScope: function(scope) {
  48967. if (!scope) return false;
  48968. var climbScope = scope;
  48969. var currentHistoryId = this.currentHistoryId();
  48970. var foundHistoryId;
  48971. while (climbScope) {
  48972. if (climbScope.$$disconnected) {
  48973. return false;
  48974. }
  48975. if (!foundHistoryId && climbScope.hasOwnProperty('$historyId')) {
  48976. foundHistoryId = true;
  48977. }
  48978. if (currentHistoryId) {
  48979. if (climbScope.hasOwnProperty('$historyId') && currentHistoryId == climbScope.$historyId) {
  48980. return true;
  48981. }
  48982. if (climbScope.hasOwnProperty('$activeHistoryId')) {
  48983. if (currentHistoryId == climbScope.$activeHistoryId) {
  48984. if (climbScope.hasOwnProperty('$historyId')) {
  48985. return true;
  48986. }
  48987. if (!foundHistoryId) {
  48988. return true;
  48989. }
  48990. }
  48991. }
  48992. }
  48993. if (foundHistoryId && climbScope.hasOwnProperty('$activeHistoryId')) {
  48994. foundHistoryId = false;
  48995. }
  48996. climbScope = climbScope.$parent;
  48997. }
  48998. return currentHistoryId ? currentHistoryId == 'root' : true;
  48999. }
  49000. };
  49001. function isAbstractTag(ele) {
  49002. return ele && ele.length && /ion-side-menus|ion-tabs/i.test(ele[0].tagName);
  49003. }
  49004. function canSwipeBack(ele, viewLocals) {
  49005. if (viewLocals && viewLocals.$$state && viewLocals.$$state.self.canSwipeBack === false) {
  49006. return false;
  49007. }
  49008. if (ele && ele.attr('can-swipe-back') === 'false') {
  49009. return false;
  49010. }
  49011. var eleChild = ele.find('ion-view');
  49012. if (eleChild && eleChild.attr('can-swipe-back') === 'false') {
  49013. return false;
  49014. }
  49015. return true;
  49016. }
  49017. }])
  49018. .run([
  49019. '$rootScope',
  49020. '$state',
  49021. '$location',
  49022. '$document',
  49023. '$ionicPlatform',
  49024. '$ionicHistory',
  49025. 'IONIC_BACK_PRIORITY',
  49026. function($rootScope, $state, $location, $document, $ionicPlatform, $ionicHistory, IONIC_BACK_PRIORITY) {
  49027. // always reset the keyboard state when change stage
  49028. $rootScope.$on('$ionicView.beforeEnter', function() {
  49029. ionic.keyboard && ionic.keyboard.hide && ionic.keyboard.hide();
  49030. });
  49031. $rootScope.$on('$ionicHistory.change', function(e, data) {
  49032. if (!data) return null;
  49033. var viewHistory = $ionicHistory.viewHistory();
  49034. var hist = (data.historyId ? viewHistory.histories[ data.historyId ] : null);
  49035. if (hist && hist.cursor > -1 && hist.cursor < hist.stack.length) {
  49036. // the history they're going to already exists
  49037. // go to it's last view in its stack
  49038. var view = hist.stack[ hist.cursor ];
  49039. return view.go(data);
  49040. }
  49041. // this history does not have a URL, but it does have a uiSref
  49042. // figure out its URL from the uiSref
  49043. if (!data.url && data.uiSref) {
  49044. data.url = $state.href(data.uiSref);
  49045. }
  49046. if (data.url) {
  49047. // don't let it start with a #, messes with $location.url()
  49048. if (data.url.indexOf('#') === 0) {
  49049. data.url = data.url.replace('#', '');
  49050. }
  49051. if (data.url !== $location.url()) {
  49052. // we've got a good URL, ready GO!
  49053. $location.url(data.url);
  49054. }
  49055. }
  49056. });
  49057. $rootScope.$ionicGoBack = function(backCount) {
  49058. $ionicHistory.goBack(backCount);
  49059. };
  49060. // Set the document title when a new view is shown
  49061. $rootScope.$on('$ionicView.afterEnter', function(ev, data) {
  49062. if (data && data.title) {
  49063. $document[0].title = data.title;
  49064. }
  49065. });
  49066. // Triggered when devices with a hardware back button (Android) is clicked by the user
  49067. // This is a Cordova/Phonegap platform specifc method
  49068. function onHardwareBackButton(e) {
  49069. var backView = $ionicHistory.backView();
  49070. if (backView) {
  49071. // there is a back view, go to it
  49072. backView.go();
  49073. } else {
  49074. // there is no back view, so close the app instead
  49075. ionic.Platform.exitApp();
  49076. }
  49077. e.preventDefault();
  49078. return false;
  49079. }
  49080. $ionicPlatform.registerBackButtonAction(
  49081. onHardwareBackButton,
  49082. IONIC_BACK_PRIORITY.view
  49083. );
  49084. }]);
  49085. /**
  49086. * @ngdoc provider
  49087. * @name $ionicConfigProvider
  49088. * @module ionic
  49089. * @description
  49090. * Ionic automatically takes platform configurations into account to adjust things like what
  49091. * transition style to use and whether tab icons should show on the top or bottom. For example,
  49092. * iOS will move forward by transitioning the entering view from right to center and the leaving
  49093. * view from center to left. However, Android will transition with the entering view going from
  49094. * bottom to center, covering the previous view, which remains stationary. It should be noted
  49095. * that when a platform is not iOS or Android, then it'll default to iOS. So if you are
  49096. * developing on a desktop browser, it's going to take on iOS default configs.
  49097. *
  49098. * These configs can be changed using the `$ionicConfigProvider` during the configuration phase
  49099. * of your app. Additionally, `$ionicConfig` can also set and get config values during the run
  49100. * phase and within the app itself.
  49101. *
  49102. * By default, all base config variables are set to `'platform'`, which means it'll take on the
  49103. * default config of the platform on which it's running. Config variables can be set at this
  49104. * level so all platforms follow the same setting, rather than its platform config.
  49105. * The following code would set the same config variable for all platforms:
  49106. *
  49107. * ```js
  49108. * $ionicConfigProvider.views.maxCache(10);
  49109. * ```
  49110. *
  49111. * Additionally, each platform can have it's own config within the `$ionicConfigProvider.platform`
  49112. * property. The config below would only apply to Android devices.
  49113. *
  49114. * ```js
  49115. * $ionicConfigProvider.platform.android.views.maxCache(5);
  49116. * ```
  49117. *
  49118. * @usage
  49119. * ```js
  49120. * var myApp = angular.module('reallyCoolApp', ['ionic']);
  49121. *
  49122. * myApp.config(function($ionicConfigProvider) {
  49123. * $ionicConfigProvider.views.maxCache(5);
  49124. *
  49125. * // note that you can also chain configs
  49126. * $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left');
  49127. * });
  49128. * ```
  49129. */
  49130. /**
  49131. * @ngdoc method
  49132. * @name $ionicConfigProvider#views.transition
  49133. * @description Animation style when transitioning between views. Default `platform`.
  49134. *
  49135. * @param {string} transition Which style of view transitioning to use.
  49136. *
  49137. * * `platform`: Dynamically choose the correct transition style depending on the platform
  49138. * the app is running from. If the platform is not `ios` or `android` then it will default
  49139. * to `ios`.
  49140. * * `ios`: iOS style transition.
  49141. * * `android`: Android style transition.
  49142. * * `none`: Do not perform animated transitions.
  49143. *
  49144. * @returns {string} value
  49145. */
  49146. /**
  49147. * @ngdoc method
  49148. * @name $ionicConfigProvider#views.maxCache
  49149. * @description Maximum number of view elements to cache in the DOM. When the max number is
  49150. * exceeded, the view with the longest time period since it was accessed is removed. Views that
  49151. * stay in the DOM cache the view's scope, current state, and scroll position. The scope is
  49152. * disconnected from the `$watch` cycle when it is cached and reconnected when it enters again.
  49153. * When the maximum cache is `0`, the leaving view's element will be removed from the DOM after
  49154. * each view transition, and the next time the same view is shown, it will have to re-compile,
  49155. * attach to the DOM, and link the element again. This disables caching, in effect.
  49156. * @param {number} maxNumber Maximum number of views to retain. Default `10`.
  49157. * @returns {number} How many views Ionic will hold onto until the a view is removed.
  49158. */
  49159. /**
  49160. * @ngdoc method
  49161. * @name $ionicConfigProvider#views.forwardCache
  49162. * @description By default, when navigating, views that were recently visited are cached, and
  49163. * the same instance data and DOM elements are referenced when navigating back. However, when
  49164. * navigating back in the history, the "forward" views are removed from the cache. If you
  49165. * navigate forward to the same view again, it'll create a new DOM element and controller
  49166. * instance. Basically, any forward views are reset each time. Set this config to `true` to have
  49167. * forward views cached and not reset on each load.
  49168. * @param {boolean} value
  49169. * @returns {boolean}
  49170. */
  49171. /**
  49172. * @ngdoc method
  49173. * @name $ionicConfigProvider#views.swipeBackEnabled
  49174. * @description By default on iOS devices, swipe to go back functionality is enabled by default.
  49175. * This method can be used to disable it globally, or on a per-view basis.
  49176. * Note: This functionality is only supported on iOS.
  49177. * @param {boolean} value
  49178. * @returns {boolean}
  49179. */
  49180. /**
  49181. * @ngdoc method
  49182. * @name $ionicConfigProvider#scrolling.jsScrolling
  49183. * @description Whether to use JS or Native scrolling. Defaults to native scrolling. Setting this to
  49184. * `true` has the same effect as setting each `ion-content` to have `overflow-scroll='false'`.
  49185. * @param {boolean} value Defaults to `false` as of Ionic 1.2
  49186. * @returns {boolean}
  49187. */
  49188. /**
  49189. * @ngdoc method
  49190. * @name $ionicConfigProvider#backButton.icon
  49191. * @description Back button icon.
  49192. * @param {string} value
  49193. * @returns {string}
  49194. */
  49195. /**
  49196. * @ngdoc method
  49197. * @name $ionicConfigProvider#backButton.text
  49198. * @description Back button text.
  49199. * @param {string} value Defaults to `Back`.
  49200. * @returns {string}
  49201. */
  49202. /**
  49203. * @ngdoc method
  49204. * @name $ionicConfigProvider#backButton.previousTitleText
  49205. * @description If the previous title text should become the back button text. This
  49206. * is the default for iOS.
  49207. * @param {boolean} value
  49208. * @returns {boolean}
  49209. */
  49210. /**
  49211. * @ngdoc method
  49212. * @name $ionicConfigProvider#form.checkbox
  49213. * @description Checkbox style. Android defaults to `square` and iOS defaults to `circle`.
  49214. * @param {string} value
  49215. * @returns {string}
  49216. */
  49217. /**
  49218. * @ngdoc method
  49219. * @name $ionicConfigProvider#form.toggle
  49220. * @description Toggle item style. Android defaults to `small` and iOS defaults to `large`.
  49221. * @param {string} value
  49222. * @returns {string}
  49223. */
  49224. /**
  49225. * @ngdoc method
  49226. * @name $ionicConfigProvider#spinner.icon
  49227. * @description Default spinner icon to use.
  49228. * @param {string} value Can be: `android`, `ios`, `ios-small`, `bubbles`, `circles`, `crescent`,
  49229. * `dots`, `lines`, `ripple`, or `spiral`.
  49230. * @returns {string}
  49231. */
  49232. /**
  49233. * @ngdoc method
  49234. * @name $ionicConfigProvider#tabs.style
  49235. * @description Tab style. Android defaults to `striped` and iOS defaults to `standard`.
  49236. * @param {string} value Available values include `striped` and `standard`.
  49237. * @returns {string}
  49238. */
  49239. /**
  49240. * @ngdoc method
  49241. * @name $ionicConfigProvider#tabs.position
  49242. * @description Tab position. Android defaults to `top` and iOS defaults to `bottom`.
  49243. * @param {string} value Available values include `top` and `bottom`.
  49244. * @returns {string}
  49245. */
  49246. /**
  49247. * @ngdoc method
  49248. * @name $ionicConfigProvider#templates.maxPrefetch
  49249. * @description Sets the maximum number of templates to prefetch from the templateUrls defined in
  49250. * $stateProvider.state. If set to `0`, the user will have to wait
  49251. * for a template to be fetched the first time when navigating to a new page. Default `30`.
  49252. * @param {integer} value Max number of template to prefetch from the templateUrls defined in
  49253. * `$stateProvider.state()`.
  49254. * @returns {integer}
  49255. */
  49256. /**
  49257. * @ngdoc method
  49258. * @name $ionicConfigProvider#navBar.alignTitle
  49259. * @description Which side of the navBar to align the title. Default `center`.
  49260. *
  49261. * @param {string} value side of the navBar to align the title.
  49262. *
  49263. * * `platform`: Dynamically choose the correct title style depending on the platform
  49264. * the app is running from. If the platform is `ios`, it will default to `center`.
  49265. * If the platform is `android`, it will default to `left`. If the platform is not
  49266. * `ios` or `android`, it will default to `center`.
  49267. *
  49268. * * `left`: Left align the title in the navBar
  49269. * * `center`: Center align the title in the navBar
  49270. * * `right`: Right align the title in the navBar.
  49271. *
  49272. * @returns {string} value
  49273. */
  49274. /**
  49275. * @ngdoc method
  49276. * @name $ionicConfigProvider#navBar.positionPrimaryButtons
  49277. * @description Which side of the navBar to align the primary navBar buttons. Default `left`.
  49278. *
  49279. * @param {string} value side of the navBar to align the primary navBar buttons.
  49280. *
  49281. * * `platform`: Dynamically choose the correct title style depending on the platform
  49282. * the app is running from. If the platform is `ios`, it will default to `left`.
  49283. * If the platform is `android`, it will default to `right`. If the platform is not
  49284. * `ios` or `android`, it will default to `left`.
  49285. *
  49286. * * `left`: Left align the primary navBar buttons in the navBar
  49287. * * `right`: Right align the primary navBar buttons in the navBar.
  49288. *
  49289. * @returns {string} value
  49290. */
  49291. /**
  49292. * @ngdoc method
  49293. * @name $ionicConfigProvider#navBar.positionSecondaryButtons
  49294. * @description Which side of the navBar to align the secondary navBar buttons. Default `right`.
  49295. *
  49296. * @param {string} value side of the navBar to align the secondary navBar buttons.
  49297. *
  49298. * * `platform`: Dynamically choose the correct title style depending on the platform
  49299. * the app is running from. If the platform is `ios`, it will default to `right`.
  49300. * If the platform is `android`, it will default to `right`. If the platform is not
  49301. * `ios` or `android`, it will default to `right`.
  49302. *
  49303. * * `left`: Left align the secondary navBar buttons in the navBar
  49304. * * `right`: Right align the secondary navBar buttons in the navBar.
  49305. *
  49306. * @returns {string} value
  49307. */
  49308. IonicModule
  49309. .provider('$ionicConfig', function() {
  49310. var provider = this;
  49311. provider.platform = {};
  49312. var PLATFORM = 'platform';
  49313. var configProperties = {
  49314. views: {
  49315. maxCache: PLATFORM,
  49316. forwardCache: PLATFORM,
  49317. transition: PLATFORM,
  49318. swipeBackEnabled: PLATFORM,
  49319. swipeBackHitWidth: PLATFORM
  49320. },
  49321. navBar: {
  49322. alignTitle: PLATFORM,
  49323. positionPrimaryButtons: PLATFORM,
  49324. positionSecondaryButtons: PLATFORM,
  49325. transition: PLATFORM
  49326. },
  49327. backButton: {
  49328. icon: PLATFORM,
  49329. text: PLATFORM,
  49330. previousTitleText: PLATFORM
  49331. },
  49332. form: {
  49333. checkbox: PLATFORM,
  49334. toggle: PLATFORM
  49335. },
  49336. scrolling: {
  49337. jsScrolling: PLATFORM
  49338. },
  49339. spinner: {
  49340. icon: PLATFORM
  49341. },
  49342. tabs: {
  49343. style: PLATFORM,
  49344. position: PLATFORM
  49345. },
  49346. templates: {
  49347. maxPrefetch: PLATFORM
  49348. },
  49349. platform: {}
  49350. };
  49351. createConfig(configProperties, provider, '');
  49352. // Default
  49353. // -------------------------
  49354. setPlatformConfig('default', {
  49355. views: {
  49356. maxCache: 10,
  49357. forwardCache: false,
  49358. transition: 'ios',
  49359. swipeBackEnabled: true,
  49360. swipeBackHitWidth: 45
  49361. },
  49362. navBar: {
  49363. alignTitle: 'center',
  49364. positionPrimaryButtons: 'left',
  49365. positionSecondaryButtons: 'right',
  49366. transition: 'view'
  49367. },
  49368. backButton: {
  49369. icon: 'ion-ios-arrow-back',
  49370. text: 'Back',
  49371. previousTitleText: true
  49372. },
  49373. form: {
  49374. checkbox: 'circle',
  49375. toggle: 'large'
  49376. },
  49377. scrolling: {
  49378. jsScrolling: true
  49379. },
  49380. spinner: {
  49381. icon: 'ios'
  49382. },
  49383. tabs: {
  49384. style: 'standard',
  49385. position: 'bottom'
  49386. },
  49387. templates: {
  49388. maxPrefetch: 30
  49389. }
  49390. });
  49391. // iOS (it is the default already)
  49392. // -------------------------
  49393. setPlatformConfig('ios', {});
  49394. // Android
  49395. // -------------------------
  49396. setPlatformConfig('android', {
  49397. views: {
  49398. transition: 'android',
  49399. swipeBackEnabled: false
  49400. },
  49401. navBar: {
  49402. alignTitle: 'left',
  49403. positionPrimaryButtons: 'right',
  49404. positionSecondaryButtons: 'right'
  49405. },
  49406. backButton: {
  49407. icon: 'ion-android-arrow-back',
  49408. text: false,
  49409. previousTitleText: false
  49410. },
  49411. form: {
  49412. checkbox: 'square',
  49413. toggle: 'small'
  49414. },
  49415. spinner: {
  49416. icon: 'android'
  49417. },
  49418. tabs: {
  49419. style: 'striped',
  49420. position: 'top'
  49421. },
  49422. scrolling: {
  49423. jsScrolling: false
  49424. }
  49425. });
  49426. // Windows Phone
  49427. // -------------------------
  49428. setPlatformConfig('windowsphone', {
  49429. //scrolling: {
  49430. // jsScrolling: false
  49431. //}
  49432. spinner: {
  49433. icon: 'android'
  49434. }
  49435. });
  49436. provider.transitions = {
  49437. views: {},
  49438. navBar: {}
  49439. };
  49440. // iOS Transitions
  49441. // -----------------------
  49442. provider.transitions.views.ios = function(enteringEle, leavingEle, direction, shouldAnimate) {
  49443. function setStyles(ele, opacity, x, boxShadowOpacity) {
  49444. var css = {};
  49445. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;
  49446. css.opacity = opacity;
  49447. if (boxShadowOpacity > -1) {
  49448. css.boxShadow = '0 0 10px rgba(0,0,0,' + (d.shouldAnimate ? boxShadowOpacity * 0.45 : 0.3) + ')';
  49449. }
  49450. css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';
  49451. ionic.DomUtil.cachedStyles(ele, css);
  49452. }
  49453. var d = {
  49454. run: function(step) {
  49455. if (direction == 'forward') {
  49456. setStyles(enteringEle, 1, (1 - step) * 99, 1 - step); // starting at 98% prevents a flicker
  49457. setStyles(leavingEle, (1 - 0.1 * step), step * -33, -1);
  49458. } else if (direction == 'back') {
  49459. setStyles(enteringEle, (1 - 0.1 * (1 - step)), (1 - step) * -33, -1);
  49460. setStyles(leavingEle, 1, step * 100, 1 - step);
  49461. } else {
  49462. // swap, enter, exit
  49463. setStyles(enteringEle, 1, 0, -1);
  49464. setStyles(leavingEle, 0, 0, -1);
  49465. }
  49466. },
  49467. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49468. };
  49469. return d;
  49470. };
  49471. provider.transitions.navBar.ios = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {
  49472. function setStyles(ctrl, opacity, titleX, backTextX) {
  49473. var css = {};
  49474. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : '0ms';
  49475. css.opacity = opacity === 1 ? '' : opacity;
  49476. ctrl.setCss('buttons-left', css);
  49477. ctrl.setCss('buttons-right', css);
  49478. ctrl.setCss('back-button', css);
  49479. css[ionic.CSS.TRANSFORM] = 'translate3d(' + backTextX + 'px,0,0)';
  49480. ctrl.setCss('back-text', css);
  49481. css[ionic.CSS.TRANSFORM] = 'translate3d(' + titleX + 'px,0,0)';
  49482. ctrl.setCss('title', css);
  49483. }
  49484. function enter(ctrlA, ctrlB, step) {
  49485. if (!ctrlA || !ctrlB) return;
  49486. var titleX = (ctrlA.titleTextX() + ctrlA.titleWidth()) * (1 - step);
  49487. var backTextX = (ctrlB && (ctrlB.titleTextX() - ctrlA.backButtonTextLeft()) * (1 - step)) || 0;
  49488. setStyles(ctrlA, step, titleX, backTextX);
  49489. }
  49490. function leave(ctrlA, ctrlB, step) {
  49491. if (!ctrlA || !ctrlB) return;
  49492. var titleX = (-(ctrlA.titleTextX() - ctrlB.backButtonTextLeft()) - (ctrlA.titleLeftRight())) * step;
  49493. setStyles(ctrlA, 1 - step, titleX, 0);
  49494. }
  49495. var d = {
  49496. run: function(step) {
  49497. var enteringHeaderCtrl = enteringHeaderBar.controller();
  49498. var leavingHeaderCtrl = leavingHeaderBar && leavingHeaderBar.controller();
  49499. if (d.direction == 'back') {
  49500. leave(enteringHeaderCtrl, leavingHeaderCtrl, 1 - step);
  49501. enter(leavingHeaderCtrl, enteringHeaderCtrl, 1 - step);
  49502. } else {
  49503. enter(enteringHeaderCtrl, leavingHeaderCtrl, step);
  49504. leave(leavingHeaderCtrl, enteringHeaderCtrl, step);
  49505. }
  49506. },
  49507. direction: direction,
  49508. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49509. };
  49510. return d;
  49511. };
  49512. // Android Transitions
  49513. // -----------------------
  49514. provider.transitions.views.android = function(enteringEle, leavingEle, direction, shouldAnimate) {
  49515. shouldAnimate = shouldAnimate && (direction == 'forward' || direction == 'back');
  49516. function setStyles(ele, x, opacity) {
  49517. var css = {};
  49518. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;
  49519. css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';
  49520. css.opacity = opacity;
  49521. ionic.DomUtil.cachedStyles(ele, css);
  49522. }
  49523. var d = {
  49524. run: function(step) {
  49525. if (direction == 'forward') {
  49526. setStyles(enteringEle, (1 - step) * 99, 1); // starting at 98% prevents a flicker
  49527. setStyles(leavingEle, step * -100, 1);
  49528. } else if (direction == 'back') {
  49529. setStyles(enteringEle, (1 - step) * -100, 1);
  49530. setStyles(leavingEle, step * 100, 1);
  49531. } else {
  49532. // swap, enter, exit
  49533. setStyles(enteringEle, 0, 1);
  49534. setStyles(leavingEle, 0, 0);
  49535. }
  49536. },
  49537. shouldAnimate: shouldAnimate
  49538. };
  49539. return d;
  49540. };
  49541. provider.transitions.navBar.android = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {
  49542. function setStyles(ctrl, opacity) {
  49543. if (!ctrl) return;
  49544. var css = {};
  49545. css.opacity = opacity === 1 ? '' : opacity;
  49546. ctrl.setCss('buttons-left', css);
  49547. ctrl.setCss('buttons-right', css);
  49548. ctrl.setCss('back-button', css);
  49549. ctrl.setCss('back-text', css);
  49550. ctrl.setCss('title', css);
  49551. }
  49552. return {
  49553. run: function(step) {
  49554. setStyles(enteringHeaderBar.controller(), step);
  49555. setStyles(leavingHeaderBar && leavingHeaderBar.controller(), 1 - step);
  49556. },
  49557. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49558. };
  49559. };
  49560. // No Transition
  49561. // -----------------------
  49562. provider.transitions.views.none = function(enteringEle, leavingEle) {
  49563. return {
  49564. run: function(step) {
  49565. provider.transitions.views.android(enteringEle, leavingEle, false, false).run(step);
  49566. },
  49567. shouldAnimate: false
  49568. };
  49569. };
  49570. provider.transitions.navBar.none = function(enteringHeaderBar, leavingHeaderBar) {
  49571. return {
  49572. run: function(step) {
  49573. provider.transitions.navBar.ios(enteringHeaderBar, leavingHeaderBar, false, false).run(step);
  49574. provider.transitions.navBar.android(enteringHeaderBar, leavingHeaderBar, false, false).run(step);
  49575. },
  49576. shouldAnimate: false
  49577. };
  49578. };
  49579. // private: used to set platform configs
  49580. function setPlatformConfig(platformName, platformConfigs) {
  49581. configProperties.platform[platformName] = platformConfigs;
  49582. provider.platform[platformName] = {};
  49583. addConfig(configProperties, configProperties.platform[platformName]);
  49584. createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
  49585. }
  49586. // private: used to recursively add new platform configs
  49587. function addConfig(configObj, platformObj) {
  49588. for (var n in configObj) {
  49589. if (n != PLATFORM && configObj.hasOwnProperty(n)) {
  49590. if (angular.isObject(configObj[n])) {
  49591. if (!isDefined(platformObj[n])) {
  49592. platformObj[n] = {};
  49593. }
  49594. addConfig(configObj[n], platformObj[n]);
  49595. } else if (!isDefined(platformObj[n])) {
  49596. platformObj[n] = null;
  49597. }
  49598. }
  49599. }
  49600. }
  49601. // private: create methods for each config to get/set
  49602. function createConfig(configObj, providerObj, platformPath) {
  49603. forEach(configObj, function(value, namespace) {
  49604. if (angular.isObject(configObj[namespace])) {
  49605. // recursively drill down the config object so we can create a method for each one
  49606. providerObj[namespace] = {};
  49607. createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);
  49608. } else {
  49609. // create a method for the provider/config methods that will be exposed
  49610. providerObj[namespace] = function(newValue) {
  49611. if (arguments.length) {
  49612. configObj[namespace] = newValue;
  49613. return providerObj;
  49614. }
  49615. if (configObj[namespace] == PLATFORM) {
  49616. // if the config is set to 'platform', then get this config's platform value
  49617. var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);
  49618. if (platformConfig || platformConfig === false) {
  49619. return platformConfig;
  49620. }
  49621. // didnt find a specific platform config, now try the default
  49622. return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
  49623. }
  49624. return configObj[namespace];
  49625. };
  49626. }
  49627. });
  49628. }
  49629. function stringObj(obj, str) {
  49630. str = str.split(".");
  49631. for (var i = 0; i < str.length; i++) {
  49632. if (obj && isDefined(obj[str[i]])) {
  49633. obj = obj[str[i]];
  49634. } else {
  49635. return null;
  49636. }
  49637. }
  49638. return obj;
  49639. }
  49640. provider.setPlatformConfig = setPlatformConfig;
  49641. // private: Service definition for internal Ionic use
  49642. /**
  49643. * @ngdoc service
  49644. * @name $ionicConfig
  49645. * @module ionic
  49646. * @private
  49647. */
  49648. provider.$get = function() {
  49649. return provider;
  49650. };
  49651. })
  49652. // Fix for URLs in Cordova apps on Windows Phone
  49653. // http://blogs.msdn.com/b/msdn_answers/archive/2015/02/10/
  49654. // running-cordova-apps-on-windows-and-windows-phone-8-1-using-ionic-angularjs-and-other-frameworks.aspx
  49655. .config(['$compileProvider', function($compileProvider) {
  49656. $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|sms|tel|geo|ftp|mailto|file|ghttps?|ms-appx-web|ms-appx|x-wmapp0):/);
  49657. $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|content|blob|ms-appx|ms-appx-web|x-wmapp0):|data:image\//);
  49658. }]);
  49659. var LOADING_TPL =
  49660. '<div class="loading-container">' +
  49661. '<div class="loading">' +
  49662. '</div>' +
  49663. '</div>';
  49664. /**
  49665. * @ngdoc service
  49666. * @name $ionicLoading
  49667. * @module ionic
  49668. * @description
  49669. * An overlay that can be used to indicate activity while blocking user
  49670. * interaction.
  49671. *
  49672. * @usage
  49673. * ```js
  49674. * angular.module('LoadingApp', ['ionic'])
  49675. * .controller('LoadingCtrl', function($scope, $ionicLoading) {
  49676. * $scope.show = function() {
  49677. * $ionicLoading.show({
  49678. * template: 'Loading...'
  49679. * }).then(function(){
  49680. * console.log("The loading indicator is now displayed");
  49681. * });
  49682. * };
  49683. * $scope.hide = function(){
  49684. * $ionicLoading.hide().then(function(){
  49685. * console.log("The loading indicator is now hidden");
  49686. * });
  49687. * };
  49688. * });
  49689. * ```
  49690. */
  49691. /**
  49692. * @ngdoc object
  49693. * @name $ionicLoadingConfig
  49694. * @module ionic
  49695. * @description
  49696. * Set the default options to be passed to the {@link ionic.service:$ionicLoading} service.
  49697. *
  49698. * @usage
  49699. * ```js
  49700. * var app = angular.module('myApp', ['ionic'])
  49701. * app.constant('$ionicLoadingConfig', {
  49702. * template: 'Default Loading Template...'
  49703. * });
  49704. * app.controller('AppCtrl', function($scope, $ionicLoading) {
  49705. * $scope.showLoading = function() {
  49706. * //options default to values in $ionicLoadingConfig
  49707. * $ionicLoading.show().then(function(){
  49708. * console.log("The loading indicator is now displayed");
  49709. * });
  49710. * };
  49711. * });
  49712. * ```
  49713. */
  49714. IonicModule
  49715. .constant('$ionicLoadingConfig', {
  49716. template: '<ion-spinner></ion-spinner>'
  49717. })
  49718. .factory('$ionicLoading', [
  49719. '$ionicLoadingConfig',
  49720. '$ionicBody',
  49721. '$ionicTemplateLoader',
  49722. '$ionicBackdrop',
  49723. '$timeout',
  49724. '$q',
  49725. '$log',
  49726. '$compile',
  49727. '$ionicPlatform',
  49728. '$rootScope',
  49729. 'IONIC_BACK_PRIORITY',
  49730. function($ionicLoadingConfig, $ionicBody, $ionicTemplateLoader, $ionicBackdrop, $timeout, $q, $log, $compile, $ionicPlatform, $rootScope, IONIC_BACK_PRIORITY) {
  49731. var loaderInstance;
  49732. //default values
  49733. var deregisterBackAction = noop;
  49734. var deregisterStateListener1 = noop;
  49735. var deregisterStateListener2 = noop;
  49736. var loadingShowDelay = $q.when();
  49737. return {
  49738. /**
  49739. * @ngdoc method
  49740. * @name $ionicLoading#show
  49741. * @description Shows a loading indicator. If the indicator is already shown,
  49742. * it will set the options given and keep the indicator shown.
  49743. * @returns {promise} A promise which is resolved when the loading indicator is presented.
  49744. * @param {object} opts The options for the loading indicator. Available properties:
  49745. * - `{string=}` `template` The html content of the indicator.
  49746. * - `{string=}` `templateUrl` The url of an html template to load as the content of the indicator.
  49747. * - `{object=}` `scope` The scope to be a child of. Default: creates a child of $rootScope.
  49748. * - `{boolean=}` `noBackdrop` Whether to hide the backdrop. By default it will be shown.
  49749. * - `{boolean=}` `hideOnStateChange` Whether to hide the loading spinner when navigating
  49750. * to a new state. Default false.
  49751. * - `{number=}` `delay` How many milliseconds to delay showing the indicator. By default there is no delay.
  49752. * - `{number=}` `duration` How many milliseconds to wait until automatically
  49753. * hiding the indicator. By default, the indicator will be shown until `.hide()` is called.
  49754. */
  49755. show: showLoader,
  49756. /**
  49757. * @ngdoc method
  49758. * @name $ionicLoading#hide
  49759. * @description Hides the loading indicator, if shown.
  49760. * @returns {promise} A promise which is resolved when the loading indicator is hidden.
  49761. */
  49762. hide: hideLoader,
  49763. /**
  49764. * @private for testing
  49765. */
  49766. _getLoader: getLoader
  49767. };
  49768. function getLoader() {
  49769. if (!loaderInstance) {
  49770. loaderInstance = $ionicTemplateLoader.compile({
  49771. template: LOADING_TPL,
  49772. appendTo: $ionicBody.get()
  49773. })
  49774. .then(function(self) {
  49775. self.show = function(options) {
  49776. var templatePromise = options.templateUrl ?
  49777. $ionicTemplateLoader.load(options.templateUrl) :
  49778. //options.content: deprecated
  49779. $q.when(options.template || options.content || '');
  49780. self.scope = options.scope || self.scope;
  49781. if (!self.isShown) {
  49782. //options.showBackdrop: deprecated
  49783. self.hasBackdrop = !options.noBackdrop && options.showBackdrop !== false;
  49784. if (self.hasBackdrop) {
  49785. $ionicBackdrop.retain();
  49786. $ionicBackdrop.getElement().addClass('backdrop-loading');
  49787. }
  49788. }
  49789. if (options.duration) {
  49790. $timeout.cancel(self.durationTimeout);
  49791. self.durationTimeout = $timeout(
  49792. angular.bind(self, self.hide),
  49793. +options.duration
  49794. );
  49795. }
  49796. deregisterBackAction();
  49797. //Disable hardware back button while loading
  49798. deregisterBackAction = $ionicPlatform.registerBackButtonAction(
  49799. noop,
  49800. IONIC_BACK_PRIORITY.loading
  49801. );
  49802. templatePromise.then(function(html) {
  49803. if (html) {
  49804. var loading = self.element.children();
  49805. loading.html(html);
  49806. $compile(loading.contents())(self.scope);
  49807. }
  49808. //Don't show until template changes
  49809. if (self.isShown) {
  49810. self.element.addClass('visible');
  49811. ionic.requestAnimationFrame(function() {
  49812. if (self.isShown) {
  49813. self.element.addClass('active');
  49814. $ionicBody.addClass('loading-active');
  49815. }
  49816. });
  49817. }
  49818. });
  49819. self.isShown = true;
  49820. };
  49821. self.hide = function() {
  49822. deregisterBackAction();
  49823. if (self.isShown) {
  49824. if (self.hasBackdrop) {
  49825. $ionicBackdrop.release();
  49826. $ionicBackdrop.getElement().removeClass('backdrop-loading');
  49827. }
  49828. self.element.removeClass('active');
  49829. $ionicBody.removeClass('loading-active');
  49830. self.element.removeClass('visible');
  49831. ionic.requestAnimationFrame(function() {
  49832. !self.isShown && self.element.removeClass('visible');
  49833. });
  49834. }
  49835. $timeout.cancel(self.durationTimeout);
  49836. self.isShown = false;
  49837. var loading = self.element.children();
  49838. loading.html("");
  49839. };
  49840. return self;
  49841. });
  49842. }
  49843. return loaderInstance;
  49844. }
  49845. function showLoader(options) {
  49846. options = extend({}, $ionicLoadingConfig || {}, options || {});
  49847. // use a default delay of 100 to avoid some issues reported on github
  49848. // https://github.com/driftyco/ionic/issues/3717
  49849. var delay = options.delay || options.showDelay || 0;
  49850. deregisterStateListener1();
  49851. deregisterStateListener2();
  49852. if (options.hideOnStateChange) {
  49853. deregisterStateListener1 = $rootScope.$on('$stateChangeSuccess', hideLoader);
  49854. deregisterStateListener2 = $rootScope.$on('$stateChangeError', hideLoader);
  49855. }
  49856. //If loading.show() was called previously, cancel it and show with our new options
  49857. $timeout.cancel(loadingShowDelay);
  49858. loadingShowDelay = $timeout(noop, delay);
  49859. return loadingShowDelay.then(getLoader).then(function(loader) {
  49860. return loader.show(options);
  49861. });
  49862. }
  49863. function hideLoader() {
  49864. deregisterStateListener1();
  49865. deregisterStateListener2();
  49866. $timeout.cancel(loadingShowDelay);
  49867. return getLoader().then(function(loader) {
  49868. return loader.hide();
  49869. });
  49870. }
  49871. }]);
  49872. /**
  49873. * @ngdoc service
  49874. * @name $ionicModal
  49875. * @module ionic
  49876. * @codepen gblny
  49877. * @description
  49878. *
  49879. * Related: {@link ionic.controller:ionicModal ionicModal controller}.
  49880. *
  49881. * The Modal is a content pane that can go over the user's main view
  49882. * temporarily. Usually used for making a choice or editing an item.
  49883. *
  49884. * Put the content of the modal inside of an `<ion-modal-view>` element.
  49885. *
  49886. * **Notes:**
  49887. * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
  49888. * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are
  49889. * called when the modal is removed.
  49890. *
  49891. * - This example assumes your modal is in your main index file or another template file. If it is in its own
  49892. * template file, remove the script tags and call it by file name.
  49893. *
  49894. * @usage
  49895. * ```html
  49896. * <script id="my-modal.html" type="text/ng-template">
  49897. * <ion-modal-view>
  49898. * <ion-header-bar>
  49899. * <h1 class="title">My Modal title</h1>
  49900. * </ion-header-bar>
  49901. * <ion-content>
  49902. * Hello!
  49903. * </ion-content>
  49904. * </ion-modal-view>
  49905. * </script>
  49906. * ```
  49907. * ```js
  49908. * angular.module('testApp', ['ionic'])
  49909. * .controller('MyController', function($scope, $ionicModal) {
  49910. * $ionicModal.fromTemplateUrl('my-modal.html', {
  49911. * scope: $scope,
  49912. * animation: 'slide-in-up'
  49913. * }).then(function(modal) {
  49914. * $scope.modal = modal;
  49915. * });
  49916. * $scope.openModal = function() {
  49917. * $scope.modal.show();
  49918. * };
  49919. * $scope.closeModal = function() {
  49920. * $scope.modal.hide();
  49921. * };
  49922. * // Cleanup the modal when we're done with it!
  49923. * $scope.$on('$destroy', function() {
  49924. * $scope.modal.remove();
  49925. * });
  49926. * // Execute action on hide modal
  49927. * $scope.$on('modal.hidden', function() {
  49928. * // Execute action
  49929. * });
  49930. * // Execute action on remove modal
  49931. * $scope.$on('modal.removed', function() {
  49932. * // Execute action
  49933. * });
  49934. * });
  49935. * ```
  49936. */
  49937. IonicModule
  49938. .factory('$ionicModal', [
  49939. '$rootScope',
  49940. '$ionicBody',
  49941. '$compile',
  49942. '$timeout',
  49943. '$ionicPlatform',
  49944. '$ionicTemplateLoader',
  49945. '$$q',
  49946. '$log',
  49947. '$ionicClickBlock',
  49948. '$window',
  49949. 'IONIC_BACK_PRIORITY',
  49950. function($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) {
  49951. /**
  49952. * @ngdoc controller
  49953. * @name ionicModal
  49954. * @module ionic
  49955. * @description
  49956. * Instantiated by the {@link ionic.service:$ionicModal} service.
  49957. *
  49958. * Be sure to call [remove()](#remove) when you are done with each modal
  49959. * to clean it up and avoid memory leaks.
  49960. *
  49961. * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
  49962. * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are
  49963. * called when the modal is removed.
  49964. */
  49965. var ModalView = ionic.views.Modal.inherit({
  49966. /**
  49967. * @ngdoc method
  49968. * @name ionicModal#initialize
  49969. * @description Creates a new modal controller instance.
  49970. * @param {object} options An options object with the following properties:
  49971. * - `{object=}` `scope` The scope to be a child of.
  49972. * Default: creates a child of $rootScope.
  49973. * - `{string=}` `animation` The animation to show & hide with.
  49974. * Default: 'slide-in-up'
  49975. * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of
  49976. * the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show
  49977. * on Android, please use the [Ionic keyboard plugin](https://github.com/driftyco/ionic-plugin-keyboard#keyboardshow).
  49978. * Default: false.
  49979. * - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop.
  49980. * Default: true.
  49981. * - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware
  49982. * back button on Android and similar devices. Default: true.
  49983. */
  49984. initialize: function(opts) {
  49985. ionic.views.Modal.prototype.initialize.call(this, opts);
  49986. this.animation = opts.animation || 'slide-in-up';
  49987. },
  49988. /**
  49989. * @ngdoc method
  49990. * @name ionicModal#show
  49991. * @description Show this modal instance.
  49992. * @returns {promise} A promise which is resolved when the modal is finished animating in.
  49993. */
  49994. show: function(target) {
  49995. var self = this;
  49996. if (self.scope.$$destroyed) {
  49997. $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.');
  49998. return $$q.when();
  49999. }
  50000. // on iOS, clicks will sometimes bleed through/ghost click on underlying
  50001. // elements
  50002. $ionicClickBlock.show(600);
  50003. stack.add(self);
  50004. var modalEl = jqLite(self.modalEl);
  50005. self.el.classList.remove('hide');
  50006. $timeout(function() {
  50007. if (!self._isShown) return;
  50008. $ionicBody.addClass(self.viewType + '-open');
  50009. }, 400, false);
  50010. if (!self.el.parentElement) {
  50011. modalEl.addClass(self.animation);
  50012. $ionicBody.append(self.el);
  50013. }
  50014. // if modal was closed while the keyboard was up, reset scroll view on
  50015. // next show since we can only resize it once it's visible
  50016. var scrollCtrl = modalEl.data('$$ionicScrollController');
  50017. scrollCtrl && scrollCtrl.resize();
  50018. if (target && self.positionView) {
  50019. self.positionView(target, modalEl);
  50020. // set up a listener for in case the window size changes
  50021. self._onWindowResize = function() {
  50022. if (self._isShown) self.positionView(target, modalEl);
  50023. };
  50024. ionic.on('resize', self._onWindowResize, window);
  50025. }
  50026. modalEl.addClass('ng-enter active')
  50027. .removeClass('ng-leave ng-leave-active');
  50028. self._isShown = true;
  50029. self._deregisterBackButton = $ionicPlatform.registerBackButtonAction(
  50030. self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop,
  50031. IONIC_BACK_PRIORITY.modal
  50032. );
  50033. ionic.views.Modal.prototype.show.call(self);
  50034. $timeout(function() {
  50035. if (!self._isShown) return;
  50036. modalEl.addClass('ng-enter-active');
  50037. ionic.trigger('resize');
  50038. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self);
  50039. self.el.classList.add('active');
  50040. self.scope.$broadcast('$ionicHeader.align');
  50041. self.scope.$broadcast('$ionicFooter.align');
  50042. self.scope.$broadcast('$ionic.modalPresented');
  50043. }, 20);
  50044. return $timeout(function() {
  50045. if (!self._isShown) return;
  50046. self.$el.on('touchmove', function(e) {
  50047. //Don't allow scrolling while open by dragging on backdrop
  50048. var isInScroll = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'scroll');
  50049. if (!isInScroll) {
  50050. e.preventDefault();
  50051. }
  50052. });
  50053. //After animating in, allow hide on backdrop click
  50054. self.$el.on('click', function(e) {
  50055. if (self.backdropClickToClose && e.target === self.el && stack.isHighest(self)) {
  50056. self.hide();
  50057. }
  50058. });
  50059. }, 400);
  50060. },
  50061. /**
  50062. * @ngdoc method
  50063. * @name ionicModal#hide
  50064. * @description Hide this modal instance.
  50065. * @returns {promise} A promise which is resolved when the modal is finished animating out.
  50066. */
  50067. hide: function() {
  50068. var self = this;
  50069. var modalEl = jqLite(self.modalEl);
  50070. // on iOS, clicks will sometimes bleed through/ghost click on underlying
  50071. // elements
  50072. $ionicClickBlock.show(600);
  50073. stack.remove(self);
  50074. self.el.classList.remove('active');
  50075. modalEl.addClass('ng-leave');
  50076. $timeout(function() {
  50077. if (self._isShown) return;
  50078. modalEl.addClass('ng-leave-active')
  50079. .removeClass('ng-enter ng-enter-active active');
  50080. self.scope.$broadcast('$ionic.modalRemoved');
  50081. }, 20, false);
  50082. self.$el.off('click');
  50083. self._isShown = false;
  50084. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self);
  50085. self._deregisterBackButton && self._deregisterBackButton();
  50086. ionic.views.Modal.prototype.hide.call(self);
  50087. // clean up event listeners
  50088. if (self.positionView) {
  50089. ionic.off('resize', self._onWindowResize, window);
  50090. }
  50091. return $timeout(function() {
  50092. $ionicBody.removeClass(self.viewType + '-open');
  50093. self.el.classList.add('hide');
  50094. }, self.hideDelay || 320);
  50095. },
  50096. /**
  50097. * @ngdoc method
  50098. * @name ionicModal#remove
  50099. * @description Remove this modal instance from the DOM and clean up.
  50100. * @returns {promise} A promise which is resolved when the modal is finished animating out.
  50101. */
  50102. remove: function() {
  50103. var self = this,
  50104. deferred, promise;
  50105. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self);
  50106. // Only hide modal, when it is actually shown!
  50107. // The hide function shows a click-block-div for a split second, because on iOS,
  50108. // clicks will sometimes bleed through/ghost click on underlying elements.
  50109. // However, this will make the app unresponsive for short amount of time.
  50110. // We don't want that, if the modal window is already hidden.
  50111. if (self._isShown) {
  50112. promise = self.hide();
  50113. } else {
  50114. deferred = $$q.defer();
  50115. deferred.resolve();
  50116. promise = deferred.promise;
  50117. }
  50118. return promise.then(function() {
  50119. self.scope.$destroy();
  50120. self.$el.remove();
  50121. });
  50122. },
  50123. /**
  50124. * @ngdoc method
  50125. * @name ionicModal#isShown
  50126. * @returns boolean Whether this modal is currently shown.
  50127. */
  50128. isShown: function() {
  50129. return !!this._isShown;
  50130. }
  50131. });
  50132. var createModal = function(templateString, options) {
  50133. // Create a new scope for the modal
  50134. var scope = options.scope && options.scope.$new() || $rootScope.$new(true);
  50135. options.viewType = options.viewType || 'modal';
  50136. extend(scope, {
  50137. $hasHeader: false,
  50138. $hasSubheader: false,
  50139. $hasFooter: false,
  50140. $hasSubfooter: false,
  50141. $hasTabs: false,
  50142. $hasTabsTop: false
  50143. });
  50144. // Compile the template
  50145. var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope);
  50146. options.$el = element;
  50147. options.el = element[0];
  50148. options.modalEl = options.el.querySelector('.' + options.viewType);
  50149. var modal = new ModalView(options);
  50150. modal.scope = scope;
  50151. // If this wasn't a defined scope, we can assign the viewType to the isolated scope
  50152. // we created
  50153. if (!options.scope) {
  50154. scope[ options.viewType ] = modal;
  50155. }
  50156. return modal;
  50157. };
  50158. var modalStack = [];
  50159. var stack = {
  50160. add: function(modal) {
  50161. modalStack.push(modal);
  50162. },
  50163. remove: function(modal) {
  50164. var index = modalStack.indexOf(modal);
  50165. if (index > -1 && index < modalStack.length) {
  50166. modalStack.splice(index, 1);
  50167. }
  50168. },
  50169. isHighest: function(modal) {
  50170. var index = modalStack.indexOf(modal);
  50171. return (index > -1 && index === modalStack.length - 1);
  50172. }
  50173. };
  50174. return {
  50175. /**
  50176. * @ngdoc method
  50177. * @name $ionicModal#fromTemplate
  50178. * @param {string} templateString The template string to use as the modal's
  50179. * content.
  50180. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
  50181. * @returns {object} An instance of an {@link ionic.controller:ionicModal}
  50182. * controller.
  50183. */
  50184. fromTemplate: function(templateString, options) {
  50185. var modal = createModal(templateString, options || {});
  50186. return modal;
  50187. },
  50188. /**
  50189. * @ngdoc method
  50190. * @name $ionicModal#fromTemplateUrl
  50191. * @param {string} templateUrl The url to load the template from.
  50192. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
  50193. * options object.
  50194. * @returns {promise} A promise that will be resolved with an instance of
  50195. * an {@link ionic.controller:ionicModal} controller.
  50196. */
  50197. fromTemplateUrl: function(url, options, _) {
  50198. var cb;
  50199. //Deprecated: allow a callback as second parameter. Now we return a promise.
  50200. if (angular.isFunction(options)) {
  50201. cb = options;
  50202. options = _;
  50203. }
  50204. return $ionicTemplateLoader.load(url).then(function(templateString) {
  50205. var modal = createModal(templateString, options || {});
  50206. cb && cb(modal);
  50207. return modal;
  50208. });
  50209. },
  50210. stack: stack
  50211. };
  50212. }]);
  50213. /**
  50214. * @ngdoc service
  50215. * @name $ionicNavBarDelegate
  50216. * @module ionic
  50217. * @description
  50218. * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.
  50219. *
  50220. * @usage
  50221. *
  50222. * ```html
  50223. * <body ng-controller="MyCtrl">
  50224. * <ion-nav-bar>
  50225. * <button ng-click="setNavTitle('banana')">
  50226. * Set title to banana!
  50227. * </button>
  50228. * </ion-nav-bar>
  50229. * </body>
  50230. * ```
  50231. * ```js
  50232. * function MyCtrl($scope, $ionicNavBarDelegate) {
  50233. * $scope.setNavTitle = function(title) {
  50234. * $ionicNavBarDelegate.title(title);
  50235. * }
  50236. * }
  50237. * ```
  50238. */
  50239. IonicModule
  50240. .service('$ionicNavBarDelegate', ionic.DelegateService([
  50241. /**
  50242. * @ngdoc method
  50243. * @name $ionicNavBarDelegate#align
  50244. * @description Aligns the title with the buttons in a given direction.
  50245. * @param {string=} direction The direction to the align the title text towards.
  50246. * Available: 'left', 'right', 'center'. Default: 'center'.
  50247. */
  50248. 'align',
  50249. /**
  50250. * @ngdoc method
  50251. * @name $ionicNavBarDelegate#showBackButton
  50252. * @description
  50253. * Set/get whether the {@link ionic.directive:ionNavBackButton} is shown
  50254. * (if it exists and there is a previous view that can be navigated to).
  50255. * @param {boolean=} show Whether to show the back button.
  50256. * @returns {boolean} Whether the back button is shown.
  50257. */
  50258. 'showBackButton',
  50259. /**
  50260. * @ngdoc method
  50261. * @name $ionicNavBarDelegate#showBar
  50262. * @description
  50263. * Set/get whether the {@link ionic.directive:ionNavBar} is shown.
  50264. * @param {boolean} show Whether to show the bar.
  50265. * @returns {boolean} Whether the bar is shown.
  50266. */
  50267. 'showBar',
  50268. /**
  50269. * @ngdoc method
  50270. * @name $ionicNavBarDelegate#title
  50271. * @description
  50272. * Set the title for the {@link ionic.directive:ionNavBar}.
  50273. * @param {string} title The new title to show.
  50274. */
  50275. 'title',
  50276. // DEPRECATED, as of v1.0.0-beta14 -------
  50277. 'changeTitle',
  50278. 'setTitle',
  50279. 'getTitle',
  50280. 'back',
  50281. 'getPreviousTitle'
  50282. // END DEPRECATED -------
  50283. ]));
  50284. IonicModule
  50285. .service('$ionicNavViewDelegate', ionic.DelegateService([
  50286. 'clearCache'
  50287. ]));
  50288. /**
  50289. * @ngdoc service
  50290. * @name $ionicPlatform
  50291. * @module ionic
  50292. * @description
  50293. * An angular abstraction of {@link ionic.utility:ionic.Platform}.
  50294. *
  50295. * Used to detect the current platform, as well as do things like override the
  50296. * Android back button in PhoneGap/Cordova.
  50297. */
  50298. IonicModule
  50299. .constant('IONIC_BACK_PRIORITY', {
  50300. view: 100,
  50301. sideMenu: 150,
  50302. modal: 200,
  50303. actionSheet: 300,
  50304. popup: 400,
  50305. loading: 500
  50306. })
  50307. .provider('$ionicPlatform', function() {
  50308. return {
  50309. $get: ['$q', '$ionicScrollDelegate', function($q, $ionicScrollDelegate) {
  50310. var self = {
  50311. /**
  50312. * @ngdoc method
  50313. * @name $ionicPlatform#onHardwareBackButton
  50314. * @description
  50315. * Some platforms have a hardware back button, so this is one way to
  50316. * bind to it.
  50317. * @param {function} callback the callback to trigger when this event occurs
  50318. */
  50319. onHardwareBackButton: function(cb) {
  50320. ionic.Platform.ready(function() {
  50321. document.addEventListener('backbutton', cb, false);
  50322. });
  50323. },
  50324. /**
  50325. * @ngdoc method
  50326. * @name $ionicPlatform#offHardwareBackButton
  50327. * @description
  50328. * Remove an event listener for the backbutton.
  50329. * @param {function} callback The listener function that was
  50330. * originally bound.
  50331. */
  50332. offHardwareBackButton: function(fn) {
  50333. ionic.Platform.ready(function() {
  50334. document.removeEventListener('backbutton', fn);
  50335. });
  50336. },
  50337. /**
  50338. * @ngdoc method
  50339. * @name $ionicPlatform#registerBackButtonAction
  50340. * @description
  50341. * Register a hardware back button action. Only one action will execute
  50342. * when the back button is clicked, so this method decides which of
  50343. * the registered back button actions has the highest priority.
  50344. *
  50345. * For example, if an actionsheet is showing, the back button should
  50346. * close the actionsheet, but it should not also go back a page view
  50347. * or close a modal which may be open.
  50348. *
  50349. * The priorities for the existing back button hooks are as follows:
  50350. * Return to previous view = 100
  50351. * Close side menu = 150
  50352. * Dismiss modal = 200
  50353. * Close action sheet = 300
  50354. * Dismiss popup = 400
  50355. * Dismiss loading overlay = 500
  50356. *
  50357. * Your back button action will override each of the above actions
  50358. * whose priority is less than the priority you provide. For example,
  50359. * an action assigned a priority of 101 will override the 'return to
  50360. * previous view' action, but not any of the other actions.
  50361. *
  50362. * @param {function} callback Called when the back button is pressed,
  50363. * if this listener is the highest priority.
  50364. * @param {number} priority Only the highest priority will execute.
  50365. * @param {*=} actionId The id to assign this action. Default: a
  50366. * random unique id.
  50367. * @returns {function} A function that, when called, will deregister
  50368. * this backButtonAction.
  50369. */
  50370. $backButtonActions: {},
  50371. registerBackButtonAction: function(fn, priority, actionId) {
  50372. if (!self._hasBackButtonHandler) {
  50373. // add a back button listener if one hasn't been setup yet
  50374. self.$backButtonActions = {};
  50375. self.onHardwareBackButton(self.hardwareBackButtonClick);
  50376. self._hasBackButtonHandler = true;
  50377. }
  50378. var action = {
  50379. id: (actionId ? actionId : ionic.Utils.nextUid()),
  50380. priority: (priority ? priority : 0),
  50381. fn: fn
  50382. };
  50383. self.$backButtonActions[action.id] = action;
  50384. // return a function to de-register this back button action
  50385. return function() {
  50386. delete self.$backButtonActions[action.id];
  50387. };
  50388. },
  50389. /**
  50390. * @private
  50391. */
  50392. hardwareBackButtonClick: function(e) {
  50393. // loop through all the registered back button actions
  50394. // and only run the last one of the highest priority
  50395. var priorityAction, actionId;
  50396. for (actionId in self.$backButtonActions) {
  50397. if (!priorityAction || self.$backButtonActions[actionId].priority >= priorityAction.priority) {
  50398. priorityAction = self.$backButtonActions[actionId];
  50399. }
  50400. }
  50401. if (priorityAction) {
  50402. priorityAction.fn(e);
  50403. return priorityAction;
  50404. }
  50405. },
  50406. is: function(type) {
  50407. return ionic.Platform.is(type);
  50408. },
  50409. /**
  50410. * @ngdoc method
  50411. * @name $ionicPlatform#on
  50412. * @description
  50413. * Add Cordova event listeners, such as `pause`, `resume`, `volumedownbutton`, `batterylow`,
  50414. * `offline`, etc. More information about available event types can be found in
  50415. * [Cordova's event documentation](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).
  50416. * @param {string} type Cordova [event type](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).
  50417. * @param {function} callback Called when the Cordova event is fired.
  50418. * @returns {function} Returns a deregistration function to remove the event listener.
  50419. */
  50420. on: function(type, cb) {
  50421. ionic.Platform.ready(function() {
  50422. document.addEventListener(type, cb, false);
  50423. });
  50424. return function() {
  50425. ionic.Platform.ready(function() {
  50426. document.removeEventListener(type, cb);
  50427. });
  50428. };
  50429. },
  50430. /**
  50431. * @ngdoc method
  50432. * @name $ionicPlatform#ready
  50433. * @description
  50434. * Trigger a callback once the device is ready,
  50435. * or immediately if the device is already ready.
  50436. * @param {function=} callback The function to call.
  50437. * @returns {promise} A promise which is resolved when the device is ready.
  50438. */
  50439. ready: function(cb) {
  50440. var q = $q.defer();
  50441. ionic.Platform.ready(function() {
  50442. window.addEventListener('statusTap', function() {
  50443. $ionicScrollDelegate.scrollTop(true);
  50444. });
  50445. q.resolve();
  50446. cb && cb();
  50447. });
  50448. return q.promise;
  50449. }
  50450. };
  50451. return self;
  50452. }]
  50453. };
  50454. });
  50455. /**
  50456. * @ngdoc service
  50457. * @name $ionicPopover
  50458. * @module ionic
  50459. * @description
  50460. *
  50461. * Related: {@link ionic.controller:ionicPopover ionicPopover controller}.
  50462. *
  50463. * The Popover is a view that floats above an app’s content. Popovers provide an
  50464. * easy way to present or gather information from the user and are
  50465. * commonly used in the following situations:
  50466. *
  50467. * - Show more info about the current view
  50468. * - Select a commonly used tool or configuration
  50469. * - Present a list of actions to perform inside one of your views
  50470. *
  50471. * Put the content of the popover inside of an `<ion-popover-view>` element.
  50472. *
  50473. * @usage
  50474. * ```html
  50475. * <p>
  50476. * <button ng-click="openPopover($event)">Open Popover</button>
  50477. * </p>
  50478. *
  50479. * <script id="my-popover.html" type="text/ng-template">
  50480. * <ion-popover-view>
  50481. * <ion-header-bar>
  50482. * <h1 class="title">My Popover Title</h1>
  50483. * </ion-header-bar>
  50484. * <ion-content>
  50485. * Hello!
  50486. * </ion-content>
  50487. * </ion-popover-view>
  50488. * </script>
  50489. * ```
  50490. * ```js
  50491. * angular.module('testApp', ['ionic'])
  50492. * .controller('MyController', function($scope, $ionicPopover) {
  50493. *
  50494. * // .fromTemplate() method
  50495. * var template = '<ion-popover-view><ion-header-bar> <h1 class="title">My Popover Title</h1> </ion-header-bar> <ion-content> Hello! </ion-content></ion-popover-view>';
  50496. *
  50497. * $scope.popover = $ionicPopover.fromTemplate(template, {
  50498. * scope: $scope
  50499. * });
  50500. *
  50501. * // .fromTemplateUrl() method
  50502. * $ionicPopover.fromTemplateUrl('my-popover.html', {
  50503. * scope: $scope
  50504. * }).then(function(popover) {
  50505. * $scope.popover = popover;
  50506. * });
  50507. *
  50508. *
  50509. * $scope.openPopover = function($event) {
  50510. * $scope.popover.show($event);
  50511. * };
  50512. * $scope.closePopover = function() {
  50513. * $scope.popover.hide();
  50514. * };
  50515. * //Cleanup the popover when we're done with it!
  50516. * $scope.$on('$destroy', function() {
  50517. * $scope.popover.remove();
  50518. * });
  50519. * // Execute action on hide popover
  50520. * $scope.$on('popover.hidden', function() {
  50521. * // Execute action
  50522. * });
  50523. * // Execute action on remove popover
  50524. * $scope.$on('popover.removed', function() {
  50525. * // Execute action
  50526. * });
  50527. * });
  50528. * ```
  50529. */
  50530. IonicModule
  50531. .factory('$ionicPopover', ['$ionicModal', '$ionicPosition', '$document', '$window',
  50532. function($ionicModal, $ionicPosition, $document, $window) {
  50533. var POPOVER_BODY_PADDING = 6;
  50534. var POPOVER_OPTIONS = {
  50535. viewType: 'popover',
  50536. hideDelay: 1,
  50537. animation: 'none',
  50538. positionView: positionView
  50539. };
  50540. function positionView(target, popoverEle) {
  50541. var targetEle = jqLite(target.target || target);
  50542. var buttonOffset = $ionicPosition.offset(targetEle);
  50543. var popoverWidth = popoverEle.prop('offsetWidth');
  50544. var popoverHeight = popoverEle.prop('offsetHeight');
  50545. // Use innerWidth and innerHeight, because clientWidth and clientHeight
  50546. // doesn't work consistently for body on all platforms
  50547. var bodyWidth = $window.innerWidth;
  50548. var bodyHeight = $window.innerHeight;
  50549. var popoverCSS = {
  50550. left: buttonOffset.left + buttonOffset.width / 2 - popoverWidth / 2
  50551. };
  50552. var arrowEle = jqLite(popoverEle[0].querySelector('.popover-arrow'));
  50553. if (popoverCSS.left < POPOVER_BODY_PADDING) {
  50554. popoverCSS.left = POPOVER_BODY_PADDING;
  50555. } else if (popoverCSS.left + popoverWidth + POPOVER_BODY_PADDING > bodyWidth) {
  50556. popoverCSS.left = bodyWidth - popoverWidth - POPOVER_BODY_PADDING;
  50557. }
  50558. // If the popover when popped down stretches past bottom of screen,
  50559. // make it pop up if there's room above
  50560. if (buttonOffset.top + buttonOffset.height + popoverHeight > bodyHeight &&
  50561. buttonOffset.top - popoverHeight > 0) {
  50562. popoverCSS.top = buttonOffset.top - popoverHeight;
  50563. popoverEle.addClass('popover-bottom');
  50564. } else {
  50565. popoverCSS.top = buttonOffset.top + buttonOffset.height;
  50566. popoverEle.removeClass('popover-bottom');
  50567. }
  50568. arrowEle.css({
  50569. left: buttonOffset.left + buttonOffset.width / 2 -
  50570. arrowEle.prop('offsetWidth') / 2 - popoverCSS.left + 'px'
  50571. });
  50572. popoverEle.css({
  50573. top: popoverCSS.top + 'px',
  50574. left: popoverCSS.left + 'px',
  50575. marginLeft: '0',
  50576. opacity: '1'
  50577. });
  50578. }
  50579. /**
  50580. * @ngdoc controller
  50581. * @name ionicPopover
  50582. * @module ionic
  50583. * @description
  50584. * Instantiated by the {@link ionic.service:$ionicPopover} service.
  50585. *
  50586. * Be sure to call [remove()](#remove) when you are done with each popover
  50587. * to clean it up and avoid memory leaks.
  50588. *
  50589. * Note: a popover will broadcast 'popover.shown', 'popover.hidden', and 'popover.removed' events from its originating
  50590. * scope, passing in itself as an event argument. Both the popover.removed and popover.hidden events are
  50591. * called when the popover is removed.
  50592. */
  50593. /**
  50594. * @ngdoc method
  50595. * @name ionicPopover#initialize
  50596. * @description Creates a new popover controller instance.
  50597. * @param {object} options An options object with the following properties:
  50598. * - `{object=}` `scope` The scope to be a child of.
  50599. * Default: creates a child of $rootScope.
  50600. * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of
  50601. * the popover when shown. Default: false.
  50602. * - `{boolean=}` `backdropClickToClose` Whether to close the popover on clicking the backdrop.
  50603. * Default: true.
  50604. * - `{boolean=}` `hardwareBackButtonClose` Whether the popover can be closed using the hardware
  50605. * back button on Android and similar devices. Default: true.
  50606. */
  50607. /**
  50608. * @ngdoc method
  50609. * @name ionicPopover#show
  50610. * @description Show this popover instance.
  50611. * @param {$event} $event The $event or target element which the popover should align
  50612. * itself next to.
  50613. * @returns {promise} A promise which is resolved when the popover is finished animating in.
  50614. */
  50615. /**
  50616. * @ngdoc method
  50617. * @name ionicPopover#hide
  50618. * @description Hide this popover instance.
  50619. * @returns {promise} A promise which is resolved when the popover is finished animating out.
  50620. */
  50621. /**
  50622. * @ngdoc method
  50623. * @name ionicPopover#remove
  50624. * @description Remove this popover instance from the DOM and clean up.
  50625. * @returns {promise} A promise which is resolved when the popover is finished animating out.
  50626. */
  50627. /**
  50628. * @ngdoc method
  50629. * @name ionicPopover#isShown
  50630. * @returns boolean Whether this popover is currently shown.
  50631. */
  50632. return {
  50633. /**
  50634. * @ngdoc method
  50635. * @name $ionicPopover#fromTemplate
  50636. * @param {string} templateString The template string to use as the popovers's
  50637. * content.
  50638. * @param {object} options Options to be passed to the initialize method.
  50639. * @returns {object} An instance of an {@link ionic.controller:ionicPopover}
  50640. * controller (ionicPopover is built on top of $ionicPopover).
  50641. */
  50642. fromTemplate: function(templateString, options) {
  50643. return $ionicModal.fromTemplate(templateString, ionic.Utils.extend({}, POPOVER_OPTIONS, options));
  50644. },
  50645. /**
  50646. * @ngdoc method
  50647. * @name $ionicPopover#fromTemplateUrl
  50648. * @param {string} templateUrl The url to load the template from.
  50649. * @param {object} options Options to be passed to the initialize method.
  50650. * @returns {promise} A promise that will be resolved with an instance of
  50651. * an {@link ionic.controller:ionicPopover} controller (ionicPopover is built on top of $ionicPopover).
  50652. */
  50653. fromTemplateUrl: function(url, options) {
  50654. return $ionicModal.fromTemplateUrl(url, ionic.Utils.extend({}, POPOVER_OPTIONS, options));
  50655. }
  50656. };
  50657. }]);
  50658. var POPUP_TPL =
  50659. '<div class="popup-container" ng-class="cssClass">' +
  50660. '<div class="popup">' +
  50661. '<div class="popup-head">' +
  50662. '<h3 class="popup-title" ng-bind-html="title"></h3>' +
  50663. '<h5 class="popup-sub-title" ng-bind-html="subTitle" ng-if="subTitle"></h5>' +
  50664. '</div>' +
  50665. '<div class="popup-body">' +
  50666. '</div>' +
  50667. '<div class="popup-buttons" ng-show="buttons.length">' +
  50668. '<button ng-repeat="button in buttons" ng-click="$buttonTapped(button, $event)" class="button" ng-class="button.type || \'button-default\'" ng-bind-html="button.text"></button>' +
  50669. '</div>' +
  50670. '</div>' +
  50671. '</div>';
  50672. /**
  50673. * @ngdoc service
  50674. * @name $ionicPopup
  50675. * @module ionic
  50676. * @restrict E
  50677. * @codepen zkmhJ
  50678. * @description
  50679. *
  50680. * The Ionic Popup service allows programmatically creating and showing popup
  50681. * windows that require the user to respond in order to continue.
  50682. *
  50683. * The popup system has support for more flexible versions of the built in `alert()`, `prompt()`,
  50684. * and `confirm()` functions that users are used to, in addition to allowing popups with completely
  50685. * custom content and look.
  50686. *
  50687. * An input can be given an `autofocus` attribute so it automatically receives focus when
  50688. * the popup first shows. However, depending on certain use-cases this can cause issues with
  50689. * the tap/click system, which is why Ionic prefers using the `autofocus` attribute as
  50690. * an opt-in feature and not the default.
  50691. *
  50692. * @usage
  50693. * A few basic examples, see below for details about all of the options available.
  50694. *
  50695. * ```js
  50696. *angular.module('mySuperApp', ['ionic'])
  50697. *.controller('PopupCtrl',function($scope, $ionicPopup, $timeout) {
  50698. *
  50699. * // Triggered on a button click, or some other target
  50700. * $scope.showPopup = function() {
  50701. * $scope.data = {};
  50702. *
  50703. * // An elaborate, custom popup
  50704. * var myPopup = $ionicPopup.show({
  50705. * template: '<input type="password" ng-model="data.wifi">',
  50706. * title: 'Enter Wi-Fi Password',
  50707. * subTitle: 'Please use normal things',
  50708. * scope: $scope,
  50709. * buttons: [
  50710. * { text: 'Cancel' },
  50711. * {
  50712. * text: '<b>Save</b>',
  50713. * type: 'button-positive',
  50714. * onTap: function(e) {
  50715. * if (!$scope.data.wifi) {
  50716. * //don't allow the user to close unless he enters wifi password
  50717. * e.preventDefault();
  50718. * } else {
  50719. * return $scope.data.wifi;
  50720. * }
  50721. * }
  50722. * }
  50723. * ]
  50724. * });
  50725. *
  50726. * myPopup.then(function(res) {
  50727. * console.log('Tapped!', res);
  50728. * });
  50729. *
  50730. * $timeout(function() {
  50731. * myPopup.close(); //close the popup after 3 seconds for some reason
  50732. * }, 3000);
  50733. * };
  50734. *
  50735. * // A confirm dialog
  50736. * $scope.showConfirm = function() {
  50737. * var confirmPopup = $ionicPopup.confirm({
  50738. * title: 'Consume Ice Cream',
  50739. * template: 'Are you sure you want to eat this ice cream?'
  50740. * });
  50741. *
  50742. * confirmPopup.then(function(res) {
  50743. * if(res) {
  50744. * console.log('You are sure');
  50745. * } else {
  50746. * console.log('You are not sure');
  50747. * }
  50748. * });
  50749. * };
  50750. *
  50751. * // An alert dialog
  50752. * $scope.showAlert = function() {
  50753. * var alertPopup = $ionicPopup.alert({
  50754. * title: 'Don\'t eat that!',
  50755. * template: 'It might taste good'
  50756. * });
  50757. *
  50758. * alertPopup.then(function(res) {
  50759. * console.log('Thank you for not eating my delicious ice cream cone');
  50760. * });
  50761. * };
  50762. *});
  50763. *```
  50764. */
  50765. IonicModule
  50766. .factory('$ionicPopup', [
  50767. '$ionicTemplateLoader',
  50768. '$ionicBackdrop',
  50769. '$q',
  50770. '$timeout',
  50771. '$rootScope',
  50772. '$ionicBody',
  50773. '$compile',
  50774. '$ionicPlatform',
  50775. '$ionicModal',
  50776. 'IONIC_BACK_PRIORITY',
  50777. function($ionicTemplateLoader, $ionicBackdrop, $q, $timeout, $rootScope, $ionicBody, $compile, $ionicPlatform, $ionicModal, IONIC_BACK_PRIORITY) {
  50778. //TODO allow this to be configured
  50779. var config = {
  50780. stackPushDelay: 75
  50781. };
  50782. var popupStack = [];
  50783. var $ionicPopup = {
  50784. /**
  50785. * @ngdoc method
  50786. * @description
  50787. * Show a complex popup. This is the master show function for all popups.
  50788. *
  50789. * A complex popup has a `buttons` array, with each button having a `text` and `type`
  50790. * field, in addition to an `onTap` function. The `onTap` function, called when
  50791. * the corresponding button on the popup is tapped, will by default close the popup
  50792. * and resolve the popup promise with its return value. If you wish to prevent the
  50793. * default and keep the popup open on button tap, call `event.preventDefault()` on the
  50794. * passed in tap event. Details below.
  50795. *
  50796. * @name $ionicPopup#show
  50797. * @param {object} options The options for the new popup, of the form:
  50798. *
  50799. * ```
  50800. * {
  50801. * title: '', // String. The title of the popup.
  50802. * cssClass: '', // String, The custom CSS class name
  50803. * subTitle: '', // String (optional). The sub-title of the popup.
  50804. * template: '', // String (optional). The html template to place in the popup body.
  50805. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50806. * scope: null, // Scope (optional). A scope to link to the popup content.
  50807. * buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.
  50808. * text: 'Cancel',
  50809. * type: 'button-default',
  50810. * onTap: function(e) {
  50811. * // e.preventDefault() will stop the popup from closing when tapped.
  50812. * e.preventDefault();
  50813. * }
  50814. * }, {
  50815. * text: 'OK',
  50816. * type: 'button-positive',
  50817. * onTap: function(e) {
  50818. * // Returning a value will cause the promise to resolve with the given value.
  50819. * return scope.data.response;
  50820. * }
  50821. * }]
  50822. * }
  50823. * ```
  50824. *
  50825. * @returns {object} A promise which is resolved when the popup is closed. Has an additional
  50826. * `close` function, which can be used to programmatically close the popup.
  50827. */
  50828. show: showPopup,
  50829. /**
  50830. * @ngdoc method
  50831. * @name $ionicPopup#alert
  50832. * @description Show a simple alert popup with a message and one button that the user can
  50833. * tap to close the popup.
  50834. *
  50835. * @param {object} options The options for showing the alert, of the form:
  50836. *
  50837. * ```
  50838. * {
  50839. * title: '', // String. The title of the popup.
  50840. * cssClass: '', // String, The custom CSS class name
  50841. * subTitle: '', // String (optional). The sub-title of the popup.
  50842. * template: '', // String (optional). The html template to place in the popup body.
  50843. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50844. * okText: '', // String (default: 'OK'). The text of the OK button.
  50845. * okType: '', // String (default: 'button-positive'). The type of the OK button.
  50846. * }
  50847. * ```
  50848. *
  50849. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50850. * function `close`, which can be called with any value to programmatically close the popup
  50851. * with the given value.
  50852. */
  50853. alert: showAlert,
  50854. /**
  50855. * @ngdoc method
  50856. * @name $ionicPopup#confirm
  50857. * @description
  50858. * Show a simple confirm popup with a Cancel and OK button.
  50859. *
  50860. * Resolves the promise with true if the user presses the OK button, and false if the
  50861. * user presses the Cancel button.
  50862. *
  50863. * @param {object} options The options for showing the confirm popup, of the form:
  50864. *
  50865. * ```
  50866. * {
  50867. * title: '', // String. The title of the popup.
  50868. * cssClass: '', // String, The custom CSS class name
  50869. * subTitle: '', // String (optional). The sub-title of the popup.
  50870. * template: '', // String (optional). The html template to place in the popup body.
  50871. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50872. * cancelText: '', // String (default: 'Cancel'). The text of the Cancel button.
  50873. * cancelType: '', // String (default: 'button-default'). The type of the Cancel button.
  50874. * okText: '', // String (default: 'OK'). The text of the OK button.
  50875. * okType: '', // String (default: 'button-positive'). The type of the OK button.
  50876. * }
  50877. * ```
  50878. *
  50879. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50880. * function `close`, which can be called with any value to programmatically close the popup
  50881. * with the given value.
  50882. */
  50883. confirm: showConfirm,
  50884. /**
  50885. * @ngdoc method
  50886. * @name $ionicPopup#prompt
  50887. * @description Show a simple prompt popup, which has an input, OK button, and Cancel button.
  50888. * Resolves the promise with the value of the input if the user presses OK, and with undefined
  50889. * if the user presses Cancel.
  50890. *
  50891. * ```javascript
  50892. * $ionicPopup.prompt({
  50893. * title: 'Password Check',
  50894. * template: 'Enter your secret password',
  50895. * inputType: 'password',
  50896. * inputPlaceholder: 'Your password'
  50897. * }).then(function(res) {
  50898. * console.log('Your password is', res);
  50899. * });
  50900. * ```
  50901. * @param {object} options The options for showing the prompt popup, of the form:
  50902. *
  50903. * ```
  50904. * {
  50905. * title: '', // String. The title of the popup.
  50906. * cssClass: '', // String, The custom CSS class name
  50907. * subTitle: '', // String (optional). The sub-title of the popup.
  50908. * template: '', // String (optional). The html template to place in the popup body.
  50909. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50910. * inputType: // String (default: 'text'). The type of input to use
  50911. * defaultText: // String (default: ''). The initial value placed into the input.
  50912. * maxLength: // Integer (default: null). Specify a maxlength attribute for the input.
  50913. * inputPlaceholder: // String (default: ''). A placeholder to use for the input.
  50914. * cancelText: // String (default: 'Cancel'. The text of the Cancel button.
  50915. * cancelType: // String (default: 'button-default'). The type of the Cancel button.
  50916. * okText: // String (default: 'OK'). The text of the OK button.
  50917. * okType: // String (default: 'button-positive'). The type of the OK button.
  50918. * }
  50919. * ```
  50920. *
  50921. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50922. * function `close`, which can be called with any value to programmatically close the popup
  50923. * with the given value.
  50924. */
  50925. prompt: showPrompt,
  50926. /**
  50927. * @private for testing
  50928. */
  50929. _createPopup: createPopup,
  50930. _popupStack: popupStack
  50931. };
  50932. return $ionicPopup;
  50933. function createPopup(options) {
  50934. options = extend({
  50935. scope: null,
  50936. title: '',
  50937. buttons: []
  50938. }, options || {});
  50939. var self = {};
  50940. self.scope = (options.scope || $rootScope).$new();
  50941. self.element = jqLite(POPUP_TPL);
  50942. self.responseDeferred = $q.defer();
  50943. $ionicBody.get().appendChild(self.element[0]);
  50944. $compile(self.element)(self.scope);
  50945. extend(self.scope, {
  50946. title: options.title,
  50947. buttons: options.buttons,
  50948. subTitle: options.subTitle,
  50949. cssClass: options.cssClass,
  50950. $buttonTapped: function(button, event) {
  50951. var result = (button.onTap || noop).apply(self, [event]);
  50952. event = event.originalEvent || event; //jquery events
  50953. if (!event.defaultPrevented) {
  50954. self.responseDeferred.resolve(result);
  50955. }
  50956. }
  50957. });
  50958. $q.when(
  50959. options.templateUrl ?
  50960. $ionicTemplateLoader.load(options.templateUrl) :
  50961. (options.template || options.content || '')
  50962. ).then(function(template) {
  50963. var popupBody = jqLite(self.element[0].querySelector('.popup-body'));
  50964. if (template) {
  50965. popupBody.html(template);
  50966. $compile(popupBody.contents())(self.scope);
  50967. } else {
  50968. popupBody.remove();
  50969. }
  50970. });
  50971. self.show = function() {
  50972. if (self.isShown || self.removed) return;
  50973. $ionicModal.stack.add(self);
  50974. self.isShown = true;
  50975. ionic.requestAnimationFrame(function() {
  50976. //if hidden while waiting for raf, don't show
  50977. if (!self.isShown) return;
  50978. self.element.removeClass('popup-hidden');
  50979. self.element.addClass('popup-showing active');
  50980. focusInput(self.element);
  50981. });
  50982. };
  50983. self.hide = function(callback) {
  50984. callback = callback || noop;
  50985. if (!self.isShown) return callback();
  50986. $ionicModal.stack.remove(self);
  50987. self.isShown = false;
  50988. self.element.removeClass('active');
  50989. self.element.addClass('popup-hidden');
  50990. $timeout(callback, 250, false);
  50991. };
  50992. self.remove = function() {
  50993. if (self.removed) return;
  50994. self.hide(function() {
  50995. self.element.remove();
  50996. self.scope.$destroy();
  50997. });
  50998. self.removed = true;
  50999. };
  51000. return self;
  51001. }
  51002. function onHardwareBackButton() {
  51003. var last = popupStack[popupStack.length - 1];
  51004. last && last.responseDeferred.resolve();
  51005. }
  51006. function showPopup(options) {
  51007. var popup = $ionicPopup._createPopup(options);
  51008. var showDelay = 0;
  51009. if (popupStack.length > 0) {
  51010. showDelay = config.stackPushDelay;
  51011. $timeout(popupStack[popupStack.length - 1].hide, showDelay, false);
  51012. } else {
  51013. //Add popup-open & backdrop if this is first popup
  51014. $ionicBody.addClass('popup-open');
  51015. $ionicBackdrop.retain();
  51016. //only show the backdrop on the first popup
  51017. $ionicPopup._backButtonActionDone = $ionicPlatform.registerBackButtonAction(
  51018. onHardwareBackButton,
  51019. IONIC_BACK_PRIORITY.popup
  51020. );
  51021. }
  51022. // Expose a 'close' method on the returned promise
  51023. popup.responseDeferred.promise.close = function popupClose(result) {
  51024. if (!popup.removed) popup.responseDeferred.resolve(result);
  51025. };
  51026. //DEPRECATED: notify the promise with an object with a close method
  51027. popup.responseDeferred.notify({ close: popup.responseDeferred.close });
  51028. doShow();
  51029. return popup.responseDeferred.promise;
  51030. function doShow() {
  51031. popupStack.push(popup);
  51032. $timeout(popup.show, showDelay, false);
  51033. popup.responseDeferred.promise.then(function(result) {
  51034. var index = popupStack.indexOf(popup);
  51035. if (index !== -1) {
  51036. popupStack.splice(index, 1);
  51037. }
  51038. popup.remove();
  51039. if (popupStack.length > 0) {
  51040. popupStack[popupStack.length - 1].show();
  51041. } else {
  51042. $ionicBackdrop.release();
  51043. //Remove popup-open & backdrop if this is last popup
  51044. $timeout(function() {
  51045. // wait to remove this due to a 300ms delay native
  51046. // click which would trigging whatever was underneath this
  51047. if (!popupStack.length) {
  51048. $ionicBody.removeClass('popup-open');
  51049. }
  51050. }, 400, false);
  51051. ($ionicPopup._backButtonActionDone || noop)();
  51052. }
  51053. return result;
  51054. });
  51055. }
  51056. }
  51057. function focusInput(element) {
  51058. var focusOn = element[0].querySelector('[autofocus]');
  51059. if (focusOn) {
  51060. focusOn.focus();
  51061. }
  51062. }
  51063. function showAlert(opts) {
  51064. return showPopup(extend({
  51065. buttons: [{
  51066. text: opts.okText || 'OK',
  51067. type: opts.okType || 'button-positive',
  51068. onTap: function() {
  51069. return true;
  51070. }
  51071. }]
  51072. }, opts || {}));
  51073. }
  51074. function showConfirm(opts) {
  51075. return showPopup(extend({
  51076. buttons: [{
  51077. text: opts.cancelText || 'Cancel',
  51078. type: opts.cancelType || 'button-default',
  51079. onTap: function() { return false; }
  51080. }, {
  51081. text: opts.okText || 'OK',
  51082. type: opts.okType || 'button-positive',
  51083. onTap: function() { return true; }
  51084. }]
  51085. }, opts || {}));
  51086. }
  51087. function showPrompt(opts) {
  51088. var scope = $rootScope.$new(true);
  51089. scope.data = {};
  51090. scope.data.fieldtype = opts.inputType ? opts.inputType : 'text';
  51091. scope.data.response = opts.defaultText ? opts.defaultText : '';
  51092. scope.data.placeholder = opts.inputPlaceholder ? opts.inputPlaceholder : '';
  51093. scope.data.maxlength = opts.maxLength ? parseInt(opts.maxLength) : '';
  51094. var text = '';
  51095. if (opts.template && /<[a-z][\s\S]*>/i.test(opts.template) === false) {
  51096. text = '<span>' + opts.template + '</span>';
  51097. delete opts.template;
  51098. }
  51099. return showPopup(extend({
  51100. template: text + '<input ng-model="data.response" '
  51101. + 'type="{{ data.fieldtype }}"'
  51102. + 'maxlength="{{ data.maxlength }}"'
  51103. + 'placeholder="{{ data.placeholder }}"'
  51104. + '>',
  51105. scope: scope,
  51106. buttons: [{
  51107. text: opts.cancelText || 'Cancel',
  51108. type: opts.cancelType || 'button-default',
  51109. onTap: function() {}
  51110. }, {
  51111. text: opts.okText || 'OK',
  51112. type: opts.okType || 'button-positive',
  51113. onTap: function() {
  51114. return scope.data.response || '';
  51115. }
  51116. }]
  51117. }, opts || {}));
  51118. }
  51119. }]);
  51120. /**
  51121. * @ngdoc service
  51122. * @name $ionicPosition
  51123. * @module ionic
  51124. * @description
  51125. * A set of utility methods that can be use to retrieve position of DOM elements.
  51126. * It is meant to be used where we need to absolute-position DOM elements in
  51127. * relation to other, existing elements (this is the case for tooltips, popovers, etc.).
  51128. *
  51129. * Adapted from [AngularUI Bootstrap](https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js),
  51130. * ([license](https://github.com/angular-ui/bootstrap/blob/master/LICENSE))
  51131. */
  51132. IonicModule
  51133. .factory('$ionicPosition', ['$document', '$window', function($document, $window) {
  51134. function getStyle(el, cssprop) {
  51135. if (el.currentStyle) { //IE
  51136. return el.currentStyle[cssprop];
  51137. } else if ($window.getComputedStyle) {
  51138. return $window.getComputedStyle(el)[cssprop];
  51139. }
  51140. // finally try and get inline style
  51141. return el.style[cssprop];
  51142. }
  51143. /**
  51144. * Checks if a given element is statically positioned
  51145. * @param element - raw DOM element
  51146. */
  51147. function isStaticPositioned(element) {
  51148. return (getStyle(element, 'position') || 'static') === 'static';
  51149. }
  51150. /**
  51151. * returns the closest, non-statically positioned parentOffset of a given element
  51152. * @param element
  51153. */
  51154. var parentOffsetEl = function(element) {
  51155. var docDomEl = $document[0];
  51156. var offsetParent = element.offsetParent || docDomEl;
  51157. while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {
  51158. offsetParent = offsetParent.offsetParent;
  51159. }
  51160. return offsetParent || docDomEl;
  51161. };
  51162. return {
  51163. /**
  51164. * @ngdoc method
  51165. * @name $ionicPosition#position
  51166. * @description Get the current coordinates of the element, relative to the offset parent.
  51167. * Read-only equivalent of [jQuery's position function](http://api.jquery.com/position/).
  51168. * @param {element} element The element to get the position of.
  51169. * @returns {object} Returns an object containing the properties top, left, width and height.
  51170. */
  51171. position: function(element) {
  51172. var elBCR = this.offset(element);
  51173. var offsetParentBCR = { top: 0, left: 0 };
  51174. var offsetParentEl = parentOffsetEl(element[0]);
  51175. if (offsetParentEl != $document[0]) {
  51176. offsetParentBCR = this.offset(jqLite(offsetParentEl));
  51177. offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
  51178. offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
  51179. }
  51180. var boundingClientRect = element[0].getBoundingClientRect();
  51181. return {
  51182. width: boundingClientRect.width || element.prop('offsetWidth'),
  51183. height: boundingClientRect.height || element.prop('offsetHeight'),
  51184. top: elBCR.top - offsetParentBCR.top,
  51185. left: elBCR.left - offsetParentBCR.left
  51186. };
  51187. },
  51188. /**
  51189. * @ngdoc method
  51190. * @name $ionicPosition#offset
  51191. * @description Get the current coordinates of the element, relative to the document.
  51192. * Read-only equivalent of [jQuery's offset function](http://api.jquery.com/offset/).
  51193. * @param {element} element The element to get the offset of.
  51194. * @returns {object} Returns an object containing the properties top, left, width and height.
  51195. */
  51196. offset: function(element) {
  51197. var boundingClientRect = element[0].getBoundingClientRect();
  51198. return {
  51199. width: boundingClientRect.width || element.prop('offsetWidth'),
  51200. height: boundingClientRect.height || element.prop('offsetHeight'),
  51201. top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
  51202. left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
  51203. };
  51204. }
  51205. };
  51206. }]);
  51207. /**
  51208. * @ngdoc service
  51209. * @name $ionicScrollDelegate
  51210. * @module ionic
  51211. * @description
  51212. * Delegate for controlling scrollViews (created by
  51213. * {@link ionic.directive:ionContent} and
  51214. * {@link ionic.directive:ionScroll} directives).
  51215. *
  51216. * Methods called directly on the $ionicScrollDelegate service will control all scroll
  51217. * views. Use the {@link ionic.service:$ionicScrollDelegate#$getByHandle $getByHandle}
  51218. * method to control specific scrollViews.
  51219. *
  51220. * @usage
  51221. *
  51222. * ```html
  51223. * <body ng-controller="MainCtrl">
  51224. * <ion-content>
  51225. * <button ng-click="scrollTop()">Scroll to Top!</button>
  51226. * </ion-content>
  51227. * </body>
  51228. * ```
  51229. * ```js
  51230. * function MainCtrl($scope, $ionicScrollDelegate) {
  51231. * $scope.scrollTop = function() {
  51232. * $ionicScrollDelegate.scrollTop();
  51233. * };
  51234. * }
  51235. * ```
  51236. *
  51237. * Example of advanced usage, with two scroll areas using `delegate-handle`
  51238. * for fine control.
  51239. *
  51240. * ```html
  51241. * <body ng-controller="MainCtrl">
  51242. * <ion-content delegate-handle="mainScroll">
  51243. * <button ng-click="scrollMainToTop()">
  51244. * Scroll content to top!
  51245. * </button>
  51246. * <ion-scroll delegate-handle="small" style="height: 100px;">
  51247. * <button ng-click="scrollSmallToTop()">
  51248. * Scroll small area to top!
  51249. * </button>
  51250. * </ion-scroll>
  51251. * </ion-content>
  51252. * </body>
  51253. * ```
  51254. * ```js
  51255. * function MainCtrl($scope, $ionicScrollDelegate) {
  51256. * $scope.scrollMainToTop = function() {
  51257. * $ionicScrollDelegate.$getByHandle('mainScroll').scrollTop();
  51258. * };
  51259. * $scope.scrollSmallToTop = function() {
  51260. * $ionicScrollDelegate.$getByHandle('small').scrollTop();
  51261. * };
  51262. * }
  51263. * ```
  51264. */
  51265. IonicModule
  51266. .service('$ionicScrollDelegate', ionic.DelegateService([
  51267. /**
  51268. * @ngdoc method
  51269. * @name $ionicScrollDelegate#resize
  51270. * @description Tell the scrollView to recalculate the size of its container.
  51271. */
  51272. 'resize',
  51273. /**
  51274. * @ngdoc method
  51275. * @name $ionicScrollDelegate#scrollTop
  51276. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51277. */
  51278. 'scrollTop',
  51279. /**
  51280. * @ngdoc method
  51281. * @name $ionicScrollDelegate#scrollBottom
  51282. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51283. */
  51284. 'scrollBottom',
  51285. /**
  51286. * @ngdoc method
  51287. * @name $ionicScrollDelegate#scrollTo
  51288. * @param {number} left The x-value to scroll to.
  51289. * @param {number} top The y-value to scroll to.
  51290. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51291. */
  51292. 'scrollTo',
  51293. /**
  51294. * @ngdoc method
  51295. * @name $ionicScrollDelegate#scrollBy
  51296. * @param {number} left The x-offset to scroll by.
  51297. * @param {number} top The y-offset to scroll by.
  51298. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51299. */
  51300. 'scrollBy',
  51301. /**
  51302. * @ngdoc method
  51303. * @name $ionicScrollDelegate#zoomTo
  51304. * @param {number} level Level to zoom to.
  51305. * @param {boolean=} animate Whether to animate the zoom.
  51306. * @param {number=} originLeft Zoom in at given left coordinate.
  51307. * @param {number=} originTop Zoom in at given top coordinate.
  51308. */
  51309. 'zoomTo',
  51310. /**
  51311. * @ngdoc method
  51312. * @name $ionicScrollDelegate#zoomBy
  51313. * @param {number} factor The factor to zoom by.
  51314. * @param {boolean=} animate Whether to animate the zoom.
  51315. * @param {number=} originLeft Zoom in at given left coordinate.
  51316. * @param {number=} originTop Zoom in at given top coordinate.
  51317. */
  51318. 'zoomBy',
  51319. /**
  51320. * @ngdoc method
  51321. * @name $ionicScrollDelegate#getScrollPosition
  51322. * @returns {object} The scroll position of this view, with the following properties:
  51323. * - `{number}` `left` The distance the user has scrolled from the left (starts at 0).
  51324. * - `{number}` `top` The distance the user has scrolled from the top (starts at 0).
  51325. * - `{number}` `zoom` The current zoom level.
  51326. */
  51327. 'getScrollPosition',
  51328. /**
  51329. * @ngdoc method
  51330. * @name $ionicScrollDelegate#anchorScroll
  51331. * @description Tell the scrollView to scroll to the element with an id
  51332. * matching window.location.hash.
  51333. *
  51334. * If no matching element is found, it will scroll to top.
  51335. *
  51336. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51337. */
  51338. 'anchorScroll',
  51339. /**
  51340. * @ngdoc method
  51341. * @name $ionicScrollDelegate#freezeScroll
  51342. * @description Does not allow this scroll view to scroll either x or y.
  51343. * @param {boolean=} shouldFreeze Should this scroll view be prevented from scrolling or not.
  51344. * @returns {boolean} If the scroll view is being prevented from scrolling or not.
  51345. */
  51346. 'freezeScroll',
  51347. /**
  51348. * @ngdoc method
  51349. * @name $ionicScrollDelegate#freezeAllScrolls
  51350. * @description Does not allow any of the app's scroll views to scroll either x or y.
  51351. * @param {boolean=} shouldFreeze Should all app scrolls be prevented from scrolling or not.
  51352. */
  51353. 'freezeAllScrolls',
  51354. /**
  51355. * @ngdoc method
  51356. * @name $ionicScrollDelegate#getScrollView
  51357. * @returns {object} The scrollView associated with this delegate.
  51358. */
  51359. 'getScrollView'
  51360. /**
  51361. * @ngdoc method
  51362. * @name $ionicScrollDelegate#$getByHandle
  51363. * @param {string} handle
  51364. * @returns `delegateInstance` A delegate instance that controls only the
  51365. * scrollViews with `delegate-handle` matching the given handle.
  51366. *
  51367. * Example: `$ionicScrollDelegate.$getByHandle('my-handle').scrollTop();`
  51368. */
  51369. ]));
  51370. /**
  51371. * @ngdoc service
  51372. * @name $ionicSideMenuDelegate
  51373. * @module ionic
  51374. *
  51375. * @description
  51376. * Delegate for controlling the {@link ionic.directive:ionSideMenus} directive.
  51377. *
  51378. * Methods called directly on the $ionicSideMenuDelegate service will control all side
  51379. * menus. Use the {@link ionic.service:$ionicSideMenuDelegate#$getByHandle $getByHandle}
  51380. * method to control specific ionSideMenus instances.
  51381. *
  51382. * @usage
  51383. *
  51384. * ```html
  51385. * <body ng-controller="MainCtrl">
  51386. * <ion-side-menus>
  51387. * <ion-side-menu-content>
  51388. * Content!
  51389. * <button ng-click="toggleLeftSideMenu()">
  51390. * Toggle Left Side Menu
  51391. * </button>
  51392. * </ion-side-menu-content>
  51393. * <ion-side-menu side="left">
  51394. * Left Menu!
  51395. * <ion-side-menu>
  51396. * </ion-side-menus>
  51397. * </body>
  51398. * ```
  51399. * ```js
  51400. * function MainCtrl($scope, $ionicSideMenuDelegate) {
  51401. * $scope.toggleLeftSideMenu = function() {
  51402. * $ionicSideMenuDelegate.toggleLeft();
  51403. * };
  51404. * }
  51405. * ```
  51406. */
  51407. IonicModule
  51408. .service('$ionicSideMenuDelegate', ionic.DelegateService([
  51409. /**
  51410. * @ngdoc method
  51411. * @name $ionicSideMenuDelegate#toggleLeft
  51412. * @description Toggle the left side menu (if it exists).
  51413. * @param {boolean=} isOpen Whether to open or close the menu.
  51414. * Default: Toggles the menu.
  51415. */
  51416. 'toggleLeft',
  51417. /**
  51418. * @ngdoc method
  51419. * @name $ionicSideMenuDelegate#toggleRight
  51420. * @description Toggle the right side menu (if it exists).
  51421. * @param {boolean=} isOpen Whether to open or close the menu.
  51422. * Default: Toggles the menu.
  51423. */
  51424. 'toggleRight',
  51425. /**
  51426. * @ngdoc method
  51427. * @name $ionicSideMenuDelegate#getOpenRatio
  51428. * @description Gets the ratio of open amount over menu width. For example, a
  51429. * menu of width 100 that is opened by 50 pixels is 50% opened, and would return
  51430. * a ratio of 0.5.
  51431. *
  51432. * @returns {float} 0 if nothing is open, between 0 and 1 if left menu is
  51433. * opened/opening, and between 0 and -1 if right menu is opened/opening.
  51434. */
  51435. 'getOpenRatio',
  51436. /**
  51437. * @ngdoc method
  51438. * @name $ionicSideMenuDelegate#isOpen
  51439. * @returns {boolean} Whether either the left or right menu is currently opened.
  51440. */
  51441. 'isOpen',
  51442. /**
  51443. * @ngdoc method
  51444. * @name $ionicSideMenuDelegate#isOpenLeft
  51445. * @returns {boolean} Whether the left menu is currently opened.
  51446. */
  51447. 'isOpenLeft',
  51448. /**
  51449. * @ngdoc method
  51450. * @name $ionicSideMenuDelegate#isOpenRight
  51451. * @returns {boolean} Whether the right menu is currently opened.
  51452. */
  51453. 'isOpenRight',
  51454. /**
  51455. * @ngdoc method
  51456. * @name $ionicSideMenuDelegate#canDragContent
  51457. * @param {boolean=} canDrag Set whether the content can or cannot be dragged to open
  51458. * side menus.
  51459. * @returns {boolean} Whether the content can be dragged to open side menus.
  51460. */
  51461. 'canDragContent',
  51462. /**
  51463. * @ngdoc method
  51464. * @name $ionicSideMenuDelegate#edgeDragThreshold
  51465. * @param {boolean|number=} value Set whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. Accepts three different values:
  51466. * - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.
  51467. * - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
  51468. * - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
  51469. * @returns {boolean} Whether the drag can start only from within the edge of screen threshold.
  51470. */
  51471. 'edgeDragThreshold'
  51472. /**
  51473. * @ngdoc method
  51474. * @name $ionicSideMenuDelegate#$getByHandle
  51475. * @param {string} handle
  51476. * @returns `delegateInstance` A delegate instance that controls only the
  51477. * {@link ionic.directive:ionSideMenus} directives with `delegate-handle` matching
  51478. * the given handle.
  51479. *
  51480. * Example: `$ionicSideMenuDelegate.$getByHandle('my-handle').toggleLeft();`
  51481. */
  51482. ]));
  51483. /**
  51484. * @ngdoc service
  51485. * @name $ionicSlideBoxDelegate
  51486. * @module ionic
  51487. * @description
  51488. * Delegate that controls the {@link ionic.directive:ionSlideBox} directive.
  51489. *
  51490. * Methods called directly on the $ionicSlideBoxDelegate service will control all slide boxes. Use the {@link ionic.service:$ionicSlideBoxDelegate#$getByHandle $getByHandle}
  51491. * method to control specific slide box instances.
  51492. *
  51493. * @usage
  51494. *
  51495. * ```html
  51496. * <ion-view>
  51497. * <ion-slide-box>
  51498. * <ion-slide>
  51499. * <div class="box blue">
  51500. * <button ng-click="nextSlide()">Next slide!</button>
  51501. * </div>
  51502. * </ion-slide>
  51503. * <ion-slide>
  51504. * <div class="box red">
  51505. * Slide 2!
  51506. * </div>
  51507. * </ion-slide>
  51508. * </ion-slide-box>
  51509. * </ion-view>
  51510. * ```
  51511. * ```js
  51512. * function MyCtrl($scope, $ionicSlideBoxDelegate) {
  51513. * $scope.nextSlide = function() {
  51514. * $ionicSlideBoxDelegate.next();
  51515. * }
  51516. * }
  51517. * ```
  51518. */
  51519. IonicModule
  51520. .service('$ionicSlideBoxDelegate', ionic.DelegateService([
  51521. /**
  51522. * @ngdoc method
  51523. * @name $ionicSlideBoxDelegate#update
  51524. * @description
  51525. * Update the slidebox (for example if using Angular with ng-repeat,
  51526. * resize it for the elements inside).
  51527. */
  51528. 'update',
  51529. /**
  51530. * @ngdoc method
  51531. * @name $ionicSlideBoxDelegate#slide
  51532. * @param {number} to The index to slide to.
  51533. * @param {number=} speed The number of milliseconds the change should take.
  51534. */
  51535. 'slide',
  51536. 'select',
  51537. /**
  51538. * @ngdoc method
  51539. * @name $ionicSlideBoxDelegate#enableSlide
  51540. * @param {boolean=} shouldEnable Whether to enable sliding the slidebox.
  51541. * @returns {boolean} Whether sliding is enabled.
  51542. */
  51543. 'enableSlide',
  51544. /**
  51545. * @ngdoc method
  51546. * @name $ionicSlideBoxDelegate#previous
  51547. * @param {number=} speed The number of milliseconds the change should take.
  51548. * @description Go to the previous slide. Wraps around if at the beginning.
  51549. */
  51550. 'previous',
  51551. /**
  51552. * @ngdoc method
  51553. * @name $ionicSlideBoxDelegate#next
  51554. * @param {number=} speed The number of milliseconds the change should take.
  51555. * @description Go to the next slide. Wraps around if at the end.
  51556. */
  51557. 'next',
  51558. /**
  51559. * @ngdoc method
  51560. * @name $ionicSlideBoxDelegate#stop
  51561. * @description Stop sliding. The slideBox will not move again until
  51562. * explicitly told to do so.
  51563. */
  51564. 'stop',
  51565. 'autoPlay',
  51566. /**
  51567. * @ngdoc method
  51568. * @name $ionicSlideBoxDelegate#start
  51569. * @description Start sliding again if the slideBox was stopped.
  51570. */
  51571. 'start',
  51572. /**
  51573. * @ngdoc method
  51574. * @name $ionicSlideBoxDelegate#currentIndex
  51575. * @returns number The index of the current slide.
  51576. */
  51577. 'currentIndex',
  51578. 'selected',
  51579. /**
  51580. * @ngdoc method
  51581. * @name $ionicSlideBoxDelegate#slidesCount
  51582. * @returns number The number of slides there are currently.
  51583. */
  51584. 'slidesCount',
  51585. 'count',
  51586. 'loop'
  51587. /**
  51588. * @ngdoc method
  51589. * @name $ionicSlideBoxDelegate#$getByHandle
  51590. * @param {string} handle
  51591. * @returns `delegateInstance` A delegate instance that controls only the
  51592. * {@link ionic.directive:ionSlideBox} directives with `delegate-handle` matching
  51593. * the given handle.
  51594. *
  51595. * Example: `$ionicSlideBoxDelegate.$getByHandle('my-handle').stop();`
  51596. */
  51597. ]));
  51598. /**
  51599. * @ngdoc service
  51600. * @name $ionicTabsDelegate
  51601. * @module ionic
  51602. *
  51603. * @description
  51604. * Delegate for controlling the {@link ionic.directive:ionTabs} directive.
  51605. *
  51606. * Methods called directly on the $ionicTabsDelegate service will control all ionTabs
  51607. * directives. Use the {@link ionic.service:$ionicTabsDelegate#$getByHandle $getByHandle}
  51608. * method to control specific ionTabs instances.
  51609. *
  51610. * @usage
  51611. *
  51612. * ```html
  51613. * <body ng-controller="MyCtrl">
  51614. * <ion-tabs>
  51615. *
  51616. * <ion-tab title="Tab 1">
  51617. * Hello tab 1!
  51618. * <button ng-click="selectTabWithIndex(1)">Select tab 2!</button>
  51619. * </ion-tab>
  51620. * <ion-tab title="Tab 2">Hello tab 2!</ion-tab>
  51621. *
  51622. * </ion-tabs>
  51623. * </body>
  51624. * ```
  51625. * ```js
  51626. * function MyCtrl($scope, $ionicTabsDelegate) {
  51627. * $scope.selectTabWithIndex = function(index) {
  51628. * $ionicTabsDelegate.select(index);
  51629. * }
  51630. * }
  51631. * ```
  51632. */
  51633. IonicModule
  51634. .service('$ionicTabsDelegate', ionic.DelegateService([
  51635. /**
  51636. * @ngdoc method
  51637. * @name $ionicTabsDelegate#select
  51638. * @description Select the tab matching the given index.
  51639. *
  51640. * @param {number} index Index of the tab to select.
  51641. */
  51642. 'select',
  51643. /**
  51644. * @ngdoc method
  51645. * @name $ionicTabsDelegate#selectedIndex
  51646. * @returns `number` The index of the selected tab, or -1.
  51647. */
  51648. 'selectedIndex',
  51649. /**
  51650. * @ngdoc method
  51651. * @name $ionicTabsDelegate#showBar
  51652. * @description
  51653. * Set/get whether the {@link ionic.directive:ionTabs} is shown
  51654. * @param {boolean} show Whether to show the bar.
  51655. * @returns {boolean} Whether the bar is shown.
  51656. */
  51657. 'showBar'
  51658. /**
  51659. * @ngdoc method
  51660. * @name $ionicTabsDelegate#$getByHandle
  51661. * @param {string} handle
  51662. * @returns `delegateInstance` A delegate instance that controls only the
  51663. * {@link ionic.directive:ionTabs} directives with `delegate-handle` matching
  51664. * the given handle.
  51665. *
  51666. * Example: `$ionicTabsDelegate.$getByHandle('my-handle').select(0);`
  51667. */
  51668. ]));
  51669. // closure to keep things neat
  51670. (function() {
  51671. var templatesToCache = [];
  51672. /**
  51673. * @ngdoc service
  51674. * @name $ionicTemplateCache
  51675. * @module ionic
  51676. * @description A service that preemptively caches template files to eliminate transition flicker and boost performance.
  51677. * @usage
  51678. * State templates are cached automatically, but you can optionally cache other templates.
  51679. *
  51680. * ```js
  51681. * $ionicTemplateCache('myNgIncludeTemplate.html');
  51682. * ```
  51683. *
  51684. * Optionally disable all preemptive caching with the `$ionicConfigProvider` or individual states by setting `prefetchTemplate`
  51685. * in the `$state` definition
  51686. *
  51687. * ```js
  51688. * angular.module('myApp', ['ionic'])
  51689. * .config(function($stateProvider, $ionicConfigProvider) {
  51690. *
  51691. * // disable preemptive template caching globally
  51692. * $ionicConfigProvider.templates.prefetch(false);
  51693. *
  51694. * // disable individual states
  51695. * $stateProvider
  51696. * .state('tabs', {
  51697. * url: "/tab",
  51698. * abstract: true,
  51699. * prefetchTemplate: false,
  51700. * templateUrl: "tabs-templates/tabs.html"
  51701. * })
  51702. * .state('tabs.home', {
  51703. * url: "/home",
  51704. * views: {
  51705. * 'home-tab': {
  51706. * prefetchTemplate: false,
  51707. * templateUrl: "tabs-templates/home.html",
  51708. * controller: 'HomeTabCtrl'
  51709. * }
  51710. * }
  51711. * });
  51712. * });
  51713. * ```
  51714. */
  51715. IonicModule
  51716. .factory('$ionicTemplateCache', [
  51717. '$http',
  51718. '$templateCache',
  51719. '$timeout',
  51720. function($http, $templateCache, $timeout) {
  51721. var toCache = templatesToCache,
  51722. hasRun;
  51723. function $ionicTemplateCache(templates) {
  51724. if (typeof templates === 'undefined') {
  51725. return run();
  51726. }
  51727. if (isString(templates)) {
  51728. templates = [templates];
  51729. }
  51730. forEach(templates, function(template) {
  51731. toCache.push(template);
  51732. });
  51733. if (hasRun) {
  51734. run();
  51735. }
  51736. }
  51737. // run through methods - internal method
  51738. function run() {
  51739. var template;
  51740. $ionicTemplateCache._runCount++;
  51741. hasRun = true;
  51742. // ignore if race condition already zeroed out array
  51743. if (toCache.length === 0) return;
  51744. var i = 0;
  51745. while (i < 4 && (template = toCache.pop())) {
  51746. // note that inline templates are ignored by this request
  51747. if (isString(template)) $http.get(template, { cache: $templateCache });
  51748. i++;
  51749. }
  51750. // only preload 3 templates a second
  51751. if (toCache.length) {
  51752. $timeout(run, 1000);
  51753. }
  51754. }
  51755. // exposing for testing
  51756. $ionicTemplateCache._runCount = 0;
  51757. // default method
  51758. return $ionicTemplateCache;
  51759. }])
  51760. // Intercepts the $stateprovider.state() command to look for templateUrls that can be cached
  51761. .config([
  51762. '$stateProvider',
  51763. '$ionicConfigProvider',
  51764. function($stateProvider, $ionicConfigProvider) {
  51765. var stateProviderState = $stateProvider.state;
  51766. $stateProvider.state = function(stateName, definition) {
  51767. // don't even bother if it's disabled. note, another config may run after this, so it's not a catch-all
  51768. if (typeof definition === 'object') {
  51769. var enabled = definition.prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();
  51770. if (enabled && isString(definition.templateUrl)) templatesToCache.push(definition.templateUrl);
  51771. if (angular.isObject(definition.views)) {
  51772. for (var key in definition.views) {
  51773. enabled = definition.views[key].prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();
  51774. if (enabled && isString(definition.views[key].templateUrl)) templatesToCache.push(definition.views[key].templateUrl);
  51775. }
  51776. }
  51777. }
  51778. return stateProviderState.call($stateProvider, stateName, definition);
  51779. };
  51780. }])
  51781. // process the templateUrls collected by the $stateProvider, adding them to the cache
  51782. .run(['$ionicTemplateCache', function($ionicTemplateCache) {
  51783. $ionicTemplateCache();
  51784. }]);
  51785. })();
  51786. IonicModule
  51787. .factory('$ionicTemplateLoader', [
  51788. '$compile',
  51789. '$controller',
  51790. '$http',
  51791. '$q',
  51792. '$rootScope',
  51793. '$templateCache',
  51794. function($compile, $controller, $http, $q, $rootScope, $templateCache) {
  51795. return {
  51796. load: fetchTemplate,
  51797. compile: loadAndCompile
  51798. };
  51799. function fetchTemplate(url) {
  51800. return $http.get(url, {cache: $templateCache})
  51801. .then(function(response) {
  51802. return response.data && response.data.trim();
  51803. });
  51804. }
  51805. function loadAndCompile(options) {
  51806. options = extend({
  51807. template: '',
  51808. templateUrl: '',
  51809. scope: null,
  51810. controller: null,
  51811. locals: {},
  51812. appendTo: null
  51813. }, options || {});
  51814. var templatePromise = options.templateUrl ?
  51815. this.load(options.templateUrl) :
  51816. $q.when(options.template);
  51817. return templatePromise.then(function(template) {
  51818. var controller;
  51819. var scope = options.scope || $rootScope.$new();
  51820. //Incase template doesn't have just one root element, do this
  51821. var element = jqLite('<div>').html(template).contents();
  51822. if (options.controller) {
  51823. controller = $controller(
  51824. options.controller,
  51825. extend(options.locals, {
  51826. $scope: scope
  51827. })
  51828. );
  51829. element.children().data('$ngControllerController', controller);
  51830. }
  51831. if (options.appendTo) {
  51832. jqLite(options.appendTo).append(element);
  51833. }
  51834. $compile(element)(scope);
  51835. return {
  51836. element: element,
  51837. scope: scope
  51838. };
  51839. });
  51840. }
  51841. }]);
  51842. /**
  51843. * @private
  51844. * DEPRECATED, as of v1.0.0-beta14 -------
  51845. */
  51846. IonicModule
  51847. .factory('$ionicViewService', ['$ionicHistory', '$log', function($ionicHistory, $log) {
  51848. function warn(oldMethod, newMethod) {
  51849. $log.warn('$ionicViewService' + oldMethod + ' is deprecated, please use $ionicHistory' + newMethod + ' instead: http://ionicframework.com/docs/nightly/api/service/$ionicHistory/');
  51850. }
  51851. warn('', '');
  51852. var methodsMap = {
  51853. getCurrentView: 'currentView',
  51854. getBackView: 'backView',
  51855. getForwardView: 'forwardView',
  51856. getCurrentStateName: 'currentStateName',
  51857. nextViewOptions: 'nextViewOptions',
  51858. clearHistory: 'clearHistory'
  51859. };
  51860. forEach(methodsMap, function(newMethod, oldMethod) {
  51861. methodsMap[oldMethod] = function() {
  51862. warn('.' + oldMethod, '.' + newMethod);
  51863. return $ionicHistory[newMethod].apply(this, arguments);
  51864. };
  51865. });
  51866. return methodsMap;
  51867. }]);
  51868. /**
  51869. * @private
  51870. * TODO document
  51871. */
  51872. IonicModule.factory('$ionicViewSwitcher', [
  51873. '$timeout',
  51874. '$document',
  51875. '$q',
  51876. '$ionicClickBlock',
  51877. '$ionicConfig',
  51878. '$ionicNavBarDelegate',
  51879. function($timeout, $document, $q, $ionicClickBlock, $ionicConfig, $ionicNavBarDelegate) {
  51880. var TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
  51881. var DATA_NO_CACHE = '$noCache';
  51882. var DATA_DESTROY_ELE = '$destroyEle';
  51883. var DATA_ELE_IDENTIFIER = '$eleId';
  51884. var DATA_VIEW_ACCESSED = '$accessed';
  51885. var DATA_FALLBACK_TIMER = '$fallbackTimer';
  51886. var DATA_VIEW = '$viewData';
  51887. var NAV_VIEW_ATTR = 'nav-view';
  51888. var VIEW_STATUS_ACTIVE = 'active';
  51889. var VIEW_STATUS_CACHED = 'cached';
  51890. var VIEW_STATUS_STAGED = 'stage';
  51891. var transitionCounter = 0;
  51892. var nextTransition, nextDirection;
  51893. ionic.transition = ionic.transition || {};
  51894. ionic.transition.isActive = false;
  51895. var isActiveTimer;
  51896. var cachedAttr = ionic.DomUtil.cachedAttr;
  51897. var transitionPromises = [];
  51898. var defaultTimeout = 1100;
  51899. var ionicViewSwitcher = {
  51900. create: function(navViewCtrl, viewLocals, enteringView, leavingView, renderStart, renderEnd) {
  51901. // get a reference to an entering/leaving element if they exist
  51902. // loop through to see if the view is already in the navViewElement
  51903. var enteringEle, leavingEle;
  51904. var transitionId = ++transitionCounter;
  51905. var alreadyInDom;
  51906. var switcher = {
  51907. init: function(registerData, callback) {
  51908. ionicViewSwitcher.isTransitioning(true);
  51909. switcher.loadViewElements(registerData);
  51910. switcher.render(registerData, function() {
  51911. callback && callback();
  51912. });
  51913. },
  51914. loadViewElements: function(registerData) {
  51915. var x, l, viewEle;
  51916. var viewElements = navViewCtrl.getViewElements();
  51917. var enteringEleIdentifier = getViewElementIdentifier(viewLocals, enteringView);
  51918. var navViewActiveEleId = navViewCtrl.activeEleId();
  51919. for (x = 0, l = viewElements.length; x < l; x++) {
  51920. viewEle = viewElements.eq(x);
  51921. if (viewEle.data(DATA_ELE_IDENTIFIER) === enteringEleIdentifier) {
  51922. // we found an existing element in the DOM that should be entering the view
  51923. if (viewEle.data(DATA_NO_CACHE)) {
  51924. // the existing element should not be cached, don't use it
  51925. viewEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier + ionic.Utils.nextUid());
  51926. viewEle.data(DATA_DESTROY_ELE, true);
  51927. } else {
  51928. enteringEle = viewEle;
  51929. }
  51930. } else if (isDefined(navViewActiveEleId) && viewEle.data(DATA_ELE_IDENTIFIER) === navViewActiveEleId) {
  51931. leavingEle = viewEle;
  51932. }
  51933. if (enteringEle && leavingEle) break;
  51934. }
  51935. alreadyInDom = !!enteringEle;
  51936. if (!alreadyInDom) {
  51937. // still no existing element to use
  51938. // create it using existing template/scope/locals
  51939. enteringEle = registerData.ele || ionicViewSwitcher.createViewEle(viewLocals);
  51940. // existing elements in the DOM are looked up by their state name and state id
  51941. enteringEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier);
  51942. }
  51943. if (renderEnd) {
  51944. navViewCtrl.activeEleId(enteringEleIdentifier);
  51945. }
  51946. registerData.ele = null;
  51947. },
  51948. render: function(registerData, callback) {
  51949. if (alreadyInDom) {
  51950. // it was already found in the DOM, just reconnect the scope
  51951. ionic.Utils.reconnectScope(enteringEle.scope());
  51952. } else {
  51953. // the entering element is not already in the DOM
  51954. // set that the entering element should be "staged" and its
  51955. // styles of where this element will go before it hits the DOM
  51956. navViewAttr(enteringEle, VIEW_STATUS_STAGED);
  51957. var enteringData = getTransitionData(viewLocals, enteringEle, registerData.direction, enteringView);
  51958. var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;
  51959. transitionFn(enteringEle, null, enteringData.direction, true).run(0);
  51960. enteringEle.data(DATA_VIEW, {
  51961. viewId: enteringData.viewId,
  51962. historyId: enteringData.historyId,
  51963. stateName: enteringData.stateName,
  51964. stateParams: enteringData.stateParams
  51965. });
  51966. // if the current state has cache:false
  51967. // or the element has cache-view="false" attribute
  51968. if (viewState(viewLocals).cache === false || viewState(viewLocals).cache === 'false' ||
  51969. enteringEle.attr('cache-view') == 'false' || $ionicConfig.views.maxCache() === 0) {
  51970. enteringEle.data(DATA_NO_CACHE, true);
  51971. }
  51972. // append the entering element to the DOM, create a new scope and run link
  51973. var viewScope = navViewCtrl.appendViewElement(enteringEle, viewLocals);
  51974. delete enteringData.direction;
  51975. delete enteringData.transition;
  51976. viewScope.$emit('$ionicView.loaded', enteringData);
  51977. }
  51978. // update that this view was just accessed
  51979. enteringEle.data(DATA_VIEW_ACCESSED, Date.now());
  51980. callback && callback();
  51981. },
  51982. transition: function(direction, enableBack, allowAnimate) {
  51983. var deferred;
  51984. var enteringData = getTransitionData(viewLocals, enteringEle, direction, enteringView);
  51985. var leavingData = extend(extend({}, enteringData), getViewData(leavingView));
  51986. enteringData.transitionId = leavingData.transitionId = transitionId;
  51987. enteringData.fromCache = !!alreadyInDom;
  51988. enteringData.enableBack = !!enableBack;
  51989. enteringData.renderStart = renderStart;
  51990. enteringData.renderEnd = renderEnd;
  51991. cachedAttr(enteringEle.parent(), 'nav-view-transition', enteringData.transition);
  51992. cachedAttr(enteringEle.parent(), 'nav-view-direction', enteringData.direction);
  51993. // cancel any previous transition complete fallbacks
  51994. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  51995. // get the transition ready and see if it'll animate
  51996. var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;
  51997. var viewTransition = transitionFn(enteringEle, leavingEle, enteringData.direction,
  51998. enteringData.shouldAnimate && allowAnimate && renderEnd);
  51999. if (viewTransition.shouldAnimate) {
  52000. // attach transitionend events (and fallback timer)
  52001. enteringEle.on(TRANSITIONEND_EVENT, completeOnTransitionEnd);
  52002. enteringEle.data(DATA_FALLBACK_TIMER, $timeout(transitionComplete, defaultTimeout));
  52003. $ionicClickBlock.show(defaultTimeout);
  52004. }
  52005. if (renderStart) {
  52006. // notify the views "before" the transition starts
  52007. switcher.emit('before', enteringData, leavingData);
  52008. // stage entering element, opacity 0, no transition duration
  52009. navViewAttr(enteringEle, VIEW_STATUS_STAGED);
  52010. // render the elements in the correct location for their starting point
  52011. viewTransition.run(0);
  52012. }
  52013. if (renderEnd) {
  52014. // create a promise so we can keep track of when all transitions finish
  52015. // only required if this transition should complete
  52016. deferred = $q.defer();
  52017. transitionPromises.push(deferred.promise);
  52018. }
  52019. if (renderStart && renderEnd) {
  52020. // CSS "auto" transitioned, not manually transitioned
  52021. // wait a frame so the styles apply before auto transitioning
  52022. $timeout(function() {
  52023. ionic.requestAnimationFrame(onReflow);
  52024. });
  52025. } else if (!renderEnd) {
  52026. // just the start of a manual transition
  52027. // but it will not render the end of the transition
  52028. navViewAttr(enteringEle, 'entering');
  52029. navViewAttr(leavingEle, 'leaving');
  52030. // return the transition run method so each step can be ran manually
  52031. return {
  52032. run: viewTransition.run,
  52033. cancel: function(shouldAnimate) {
  52034. if (shouldAnimate) {
  52035. enteringEle.on(TRANSITIONEND_EVENT, cancelOnTransitionEnd);
  52036. enteringEle.data(DATA_FALLBACK_TIMER, $timeout(cancelTransition, defaultTimeout));
  52037. $ionicClickBlock.show(defaultTimeout);
  52038. } else {
  52039. cancelTransition();
  52040. }
  52041. viewTransition.shouldAnimate = shouldAnimate;
  52042. viewTransition.run(0);
  52043. viewTransition = null;
  52044. }
  52045. };
  52046. } else if (renderEnd) {
  52047. // just the end of a manual transition
  52048. // happens after the manual transition has completed
  52049. // and a full history change has happened
  52050. onReflow();
  52051. }
  52052. function onReflow() {
  52053. // remove that we're staging the entering element so it can auto transition
  52054. navViewAttr(enteringEle, viewTransition.shouldAnimate ? 'entering' : VIEW_STATUS_ACTIVE);
  52055. navViewAttr(leavingEle, viewTransition.shouldAnimate ? 'leaving' : VIEW_STATUS_CACHED);
  52056. // start the auto transition and let the CSS take over
  52057. viewTransition.run(1);
  52058. // trigger auto transitions on the associated nav bars
  52059. $ionicNavBarDelegate._instances.forEach(function(instance) {
  52060. instance.triggerTransitionStart(transitionId);
  52061. });
  52062. if (!viewTransition.shouldAnimate) {
  52063. // no animated auto transition
  52064. transitionComplete();
  52065. }
  52066. }
  52067. // Make sure that transitionend events bubbling up from children won't fire
  52068. // transitionComplete. Will only go forward if ev.target == the element listening.
  52069. function completeOnTransitionEnd(ev) {
  52070. if (ev.target !== this) return;
  52071. transitionComplete();
  52072. }
  52073. function transitionComplete() {
  52074. if (transitionComplete.x) return;
  52075. transitionComplete.x = true;
  52076. enteringEle.off(TRANSITIONEND_EVENT, completeOnTransitionEnd);
  52077. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  52078. leavingEle && $timeout.cancel(leavingEle.data(DATA_FALLBACK_TIMER));
  52079. // resolve that this one transition (there could be many w/ nested views)
  52080. deferred && deferred.resolve(navViewCtrl);
  52081. // the most recent transition added has completed and all the active
  52082. // transition promises should be added to the services array of promises
  52083. if (transitionId === transitionCounter) {
  52084. $q.all(transitionPromises).then(ionicViewSwitcher.transitionEnd);
  52085. // emit that the views have finished transitioning
  52086. // each parent nav-view will update which views are active and cached
  52087. switcher.emit('after', enteringData, leavingData);
  52088. switcher.cleanup(enteringData);
  52089. }
  52090. // tell the nav bars that the transition has ended
  52091. $ionicNavBarDelegate._instances.forEach(function(instance) {
  52092. instance.triggerTransitionEnd();
  52093. });
  52094. // remove any references that could cause memory issues
  52095. nextTransition = nextDirection = enteringView = leavingView = enteringEle = leavingEle = null;
  52096. }
  52097. // Make sure that transitionend events bubbling up from children won't fire
  52098. // transitionComplete. Will only go forward if ev.target == the element listening.
  52099. function cancelOnTransitionEnd(ev) {
  52100. if (ev.target !== this) return;
  52101. cancelTransition();
  52102. }
  52103. function cancelTransition() {
  52104. navViewAttr(enteringEle, VIEW_STATUS_CACHED);
  52105. navViewAttr(leavingEle, VIEW_STATUS_ACTIVE);
  52106. enteringEle.off(TRANSITIONEND_EVENT, cancelOnTransitionEnd);
  52107. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  52108. ionicViewSwitcher.transitionEnd([navViewCtrl]);
  52109. }
  52110. },
  52111. emit: function(step, enteringData, leavingData) {
  52112. var enteringScope = getScopeForElement(enteringEle, enteringData);
  52113. var leavingScope = getScopeForElement(leavingEle, leavingData);
  52114. var prefixesAreEqual;
  52115. if ( !enteringData.viewId || enteringData.abstractView ) {
  52116. // it's an abstract view, so treat it accordingly
  52117. // we only get access to the leaving scope once in the transition,
  52118. // so dispatch all events right away if it exists
  52119. if ( leavingScope ) {
  52120. leavingScope.$emit('$ionicView.beforeLeave', leavingData);
  52121. leavingScope.$emit('$ionicView.leave', leavingData);
  52122. leavingScope.$emit('$ionicView.afterLeave', leavingData);
  52123. leavingScope.$broadcast('$ionicParentView.beforeLeave', leavingData);
  52124. leavingScope.$broadcast('$ionicParentView.leave', leavingData);
  52125. leavingScope.$broadcast('$ionicParentView.afterLeave', leavingData);
  52126. }
  52127. }
  52128. else {
  52129. // it's a regular view, so do the normal process
  52130. if (step == 'after') {
  52131. if (enteringScope) {
  52132. enteringScope.$emit('$ionicView.enter', enteringData);
  52133. enteringScope.$broadcast('$ionicParentView.enter', enteringData);
  52134. }
  52135. if (leavingScope) {
  52136. leavingScope.$emit('$ionicView.leave', leavingData);
  52137. leavingScope.$broadcast('$ionicParentView.leave', leavingData);
  52138. }
  52139. else if (enteringScope && leavingData && leavingData.viewId && enteringData.stateName !== leavingData.stateName) {
  52140. // we only want to dispatch this when we are doing a single-tier
  52141. // state change such as changing a tab, so compare the state
  52142. // for the same state-prefix but different suffix
  52143. prefixesAreEqual = compareStatePrefixes(enteringData.stateName, leavingData.stateName);
  52144. if ( prefixesAreEqual ) {
  52145. enteringScope.$emit('$ionicNavView.leave', leavingData);
  52146. }
  52147. }
  52148. }
  52149. if (enteringScope) {
  52150. enteringScope.$emit('$ionicView.' + step + 'Enter', enteringData);
  52151. enteringScope.$broadcast('$ionicParentView.' + step + 'Enter', enteringData);
  52152. }
  52153. if (leavingScope) {
  52154. leavingScope.$emit('$ionicView.' + step + 'Leave', leavingData);
  52155. leavingScope.$broadcast('$ionicParentView.' + step + 'Leave', leavingData);
  52156. } else if (enteringScope && leavingData && leavingData.viewId && enteringData.stateName !== leavingData.stateName) {
  52157. // we only want to dispatch this when we are doing a single-tier
  52158. // state change such as changing a tab, so compare the state
  52159. // for the same state-prefix but different suffix
  52160. prefixesAreEqual = compareStatePrefixes(enteringData.stateName, leavingData.stateName);
  52161. if ( prefixesAreEqual ) {
  52162. enteringScope.$emit('$ionicNavView.' + step + 'Leave', leavingData);
  52163. }
  52164. }
  52165. }
  52166. },
  52167. cleanup: function(transData) {
  52168. // check if any views should be removed
  52169. if (leavingEle && transData.direction == 'back' && !$ionicConfig.views.forwardCache()) {
  52170. // if they just navigated back we can destroy the forward view
  52171. // do not remove forward views if cacheForwardViews config is true
  52172. destroyViewEle(leavingEle);
  52173. }
  52174. var viewElements = navViewCtrl.getViewElements();
  52175. var viewElementsLength = viewElements.length;
  52176. var x, viewElement;
  52177. var removeOldestAccess = (viewElementsLength - 1) > $ionicConfig.views.maxCache();
  52178. var removableEle;
  52179. var oldestAccess = Date.now();
  52180. for (x = 0; x < viewElementsLength; x++) {
  52181. viewElement = viewElements.eq(x);
  52182. if (removeOldestAccess && viewElement.data(DATA_VIEW_ACCESSED) < oldestAccess) {
  52183. // remember what was the oldest element to be accessed so it can be destroyed
  52184. oldestAccess = viewElement.data(DATA_VIEW_ACCESSED);
  52185. removableEle = viewElements.eq(x);
  52186. } else if (viewElement.data(DATA_DESTROY_ELE) && navViewAttr(viewElement) != VIEW_STATUS_ACTIVE) {
  52187. destroyViewEle(viewElement);
  52188. }
  52189. }
  52190. destroyViewEle(removableEle);
  52191. if (enteringEle.data(DATA_NO_CACHE)) {
  52192. enteringEle.data(DATA_DESTROY_ELE, true);
  52193. }
  52194. },
  52195. enteringEle: function() { return enteringEle; },
  52196. leavingEle: function() { return leavingEle; }
  52197. };
  52198. return switcher;
  52199. },
  52200. transitionEnd: function(navViewCtrls) {
  52201. forEach(navViewCtrls, function(navViewCtrl) {
  52202. navViewCtrl.transitionEnd();
  52203. });
  52204. ionicViewSwitcher.isTransitioning(false);
  52205. $ionicClickBlock.hide();
  52206. transitionPromises = [];
  52207. },
  52208. nextTransition: function(val) {
  52209. nextTransition = val;
  52210. },
  52211. nextDirection: function(val) {
  52212. nextDirection = val;
  52213. },
  52214. isTransitioning: function(val) {
  52215. if (arguments.length) {
  52216. ionic.transition.isActive = !!val;
  52217. $timeout.cancel(isActiveTimer);
  52218. if (val) {
  52219. isActiveTimer = $timeout(function() {
  52220. ionicViewSwitcher.isTransitioning(false);
  52221. }, 999);
  52222. }
  52223. }
  52224. return ionic.transition.isActive;
  52225. },
  52226. createViewEle: function(viewLocals) {
  52227. var containerEle = $document[0].createElement('div');
  52228. if (viewLocals && viewLocals.$template) {
  52229. containerEle.innerHTML = viewLocals.$template;
  52230. if (containerEle.children.length === 1) {
  52231. containerEle.children[0].classList.add('pane');
  52232. if ( viewLocals.$$state && viewLocals.$$state.self && viewLocals.$$state.self['abstract'] ) {
  52233. angular.element(containerEle.children[0]).attr("abstract", "true");
  52234. }
  52235. else {
  52236. if ( viewLocals.$$state && viewLocals.$$state.self ) {
  52237. angular.element(containerEle.children[0]).attr("state", viewLocals.$$state.self.name);
  52238. }
  52239. }
  52240. return jqLite(containerEle.children[0]);
  52241. }
  52242. }
  52243. containerEle.className = "pane";
  52244. return jqLite(containerEle);
  52245. },
  52246. viewEleIsActive: function(viewEle, isActiveAttr) {
  52247. navViewAttr(viewEle, isActiveAttr ? VIEW_STATUS_ACTIVE : VIEW_STATUS_CACHED);
  52248. },
  52249. getTransitionData: getTransitionData,
  52250. navViewAttr: navViewAttr,
  52251. destroyViewEle: destroyViewEle
  52252. };
  52253. return ionicViewSwitcher;
  52254. function getViewElementIdentifier(locals, view) {
  52255. if (viewState(locals)['abstract']) return viewState(locals).name;
  52256. if (view) return view.stateId || view.viewId;
  52257. return ionic.Utils.nextUid();
  52258. }
  52259. function viewState(locals) {
  52260. return locals && locals.$$state && locals.$$state.self || {};
  52261. }
  52262. function getTransitionData(viewLocals, enteringEle, direction, view) {
  52263. // Priority
  52264. // 1) attribute directive on the button/link to this view
  52265. // 2) entering element's attribute
  52266. // 3) entering view's $state config property
  52267. // 4) view registration data
  52268. // 5) global config
  52269. // 6) fallback value
  52270. var state = viewState(viewLocals);
  52271. var viewTransition = nextTransition || cachedAttr(enteringEle, 'view-transition') || state.viewTransition || $ionicConfig.views.transition() || 'ios';
  52272. var navBarTransition = $ionicConfig.navBar.transition();
  52273. direction = nextDirection || cachedAttr(enteringEle, 'view-direction') || state.viewDirection || direction || 'none';
  52274. return extend(getViewData(view), {
  52275. transition: viewTransition,
  52276. navBarTransition: navBarTransition === 'view' ? viewTransition : navBarTransition,
  52277. direction: direction,
  52278. shouldAnimate: (viewTransition !== 'none' && direction !== 'none')
  52279. });
  52280. }
  52281. function getViewData(view) {
  52282. view = view || {};
  52283. return {
  52284. viewId: view.viewId,
  52285. historyId: view.historyId,
  52286. stateId: view.stateId,
  52287. stateName: view.stateName,
  52288. stateParams: view.stateParams
  52289. };
  52290. }
  52291. function navViewAttr(ele, value) {
  52292. if (arguments.length > 1) {
  52293. cachedAttr(ele, NAV_VIEW_ATTR, value);
  52294. } else {
  52295. return cachedAttr(ele, NAV_VIEW_ATTR);
  52296. }
  52297. }
  52298. function destroyViewEle(ele) {
  52299. // we found an element that should be removed
  52300. // destroy its scope, then remove the element
  52301. if (ele && ele.length) {
  52302. var viewScope = ele.scope();
  52303. if (viewScope) {
  52304. viewScope.$emit('$ionicView.unloaded', ele.data(DATA_VIEW));
  52305. viewScope.$destroy();
  52306. }
  52307. ele.remove();
  52308. }
  52309. }
  52310. function compareStatePrefixes(enteringStateName, exitingStateName) {
  52311. var enteringStateSuffixIndex = enteringStateName.lastIndexOf('.');
  52312. var exitingStateSuffixIndex = exitingStateName.lastIndexOf('.');
  52313. // if either of the prefixes are empty, just return false
  52314. if ( enteringStateSuffixIndex < 0 || exitingStateSuffixIndex < 0 ) {
  52315. return false;
  52316. }
  52317. var enteringPrefix = enteringStateName.substring(0, enteringStateSuffixIndex);
  52318. var exitingPrefix = exitingStateName.substring(0, exitingStateSuffixIndex);
  52319. return enteringPrefix === exitingPrefix;
  52320. }
  52321. function getScopeForElement(element, stateData) {
  52322. if ( !element ) {
  52323. return null;
  52324. }
  52325. // check if it's abstract
  52326. var attributeValue = angular.element(element).attr("abstract");
  52327. var stateValue = angular.element(element).attr("state");
  52328. if ( attributeValue !== "true" ) {
  52329. // it's not an abstract view, so make sure the element
  52330. // matches the state. Due to abstract view weirdness,
  52331. // sometimes it doesn't. If it doesn't, don't dispatch events
  52332. // so leave the scope undefined
  52333. if ( stateValue === stateData.stateName ) {
  52334. return angular.element(element).scope();
  52335. }
  52336. return null;
  52337. }
  52338. else {
  52339. // it is an abstract element, so look for element with the "state" attributeValue
  52340. // set to the name of the stateData state
  52341. var elements = aggregateNavViewChildren(element);
  52342. for ( var i = 0; i < elements.length; i++ ) {
  52343. var state = angular.element(elements[i]).attr("state");
  52344. if ( state === stateData.stateName ) {
  52345. stateData.abstractView = true;
  52346. return angular.element(elements[i]).scope();
  52347. }
  52348. }
  52349. // we didn't find a match, so return null
  52350. return null;
  52351. }
  52352. }
  52353. function aggregateNavViewChildren(element) {
  52354. var aggregate = [];
  52355. var navViews = angular.element(element).find("ion-nav-view");
  52356. for ( var i = 0; i < navViews.length; i++ ) {
  52357. var children = angular.element(navViews[i]).children();
  52358. var childrenAggregated = [];
  52359. for ( var j = 0; j < children.length; j++ ) {
  52360. childrenAggregated = childrenAggregated.concat(children[j]);
  52361. }
  52362. aggregate = aggregate.concat(childrenAggregated);
  52363. }
  52364. return aggregate;
  52365. }
  52366. }]);
  52367. /**
  52368. * ================== angular-ios9-uiwebview.patch.js v1.1.1 ==================
  52369. *
  52370. * This patch works around iOS9 UIWebView regression that causes infinite digest
  52371. * errors in Angular.
  52372. *
  52373. * The patch can be applied to Angular 1.2.0 – 1.4.5. Newer versions of Angular
  52374. * have the workaround baked in.
  52375. *
  52376. * To apply this patch load/bundle this file with your application and add a
  52377. * dependency on the "ngIOS9UIWebViewPatch" module to your main app module.
  52378. *
  52379. * For example:
  52380. *
  52381. * ```
  52382. * angular.module('myApp', ['ngRoute'])`
  52383. * ```
  52384. *
  52385. * becomes
  52386. *
  52387. * ```
  52388. * angular.module('myApp', ['ngRoute', 'ngIOS9UIWebViewPatch'])
  52389. * ```
  52390. *
  52391. *
  52392. * More info:
  52393. * - https://openradar.appspot.com/22186109
  52394. * - https://github.com/angular/angular.js/issues/12241
  52395. * - https://github.com/driftyco/ionic/issues/4082
  52396. *
  52397. *
  52398. * @license AngularJS
  52399. * (c) 2010-2015 Google, Inc. http://angularjs.org
  52400. * License: MIT
  52401. */
  52402. angular.module('ngIOS9UIWebViewPatch', ['ng']).config(['$provide', function($provide) {
  52403. 'use strict';
  52404. $provide.decorator('$browser', ['$delegate', '$window', function($delegate, $window) {
  52405. if (isIOS9UIWebView($window.navigator.userAgent)) {
  52406. return applyIOS9Shim($delegate);
  52407. }
  52408. return $delegate;
  52409. function isIOS9UIWebView(userAgent) {
  52410. return /(iPhone|iPad|iPod).* OS 9_\d/.test(userAgent) && !/Version\/9\./.test(userAgent);
  52411. }
  52412. function applyIOS9Shim(browser) {
  52413. var pendingLocationUrl = null;
  52414. var originalUrlFn = browser.url;
  52415. browser.url = function() {
  52416. if (arguments.length) {
  52417. pendingLocationUrl = arguments[0];
  52418. return originalUrlFn.apply(browser, arguments);
  52419. }
  52420. return pendingLocationUrl || originalUrlFn.apply(browser, arguments);
  52421. };
  52422. window.addEventListener('popstate', clearPendingLocationUrl, false);
  52423. window.addEventListener('hashchange', clearPendingLocationUrl, false);
  52424. function clearPendingLocationUrl() {
  52425. pendingLocationUrl = null;
  52426. }
  52427. return browser;
  52428. }
  52429. }]);
  52430. }]);
  52431. /**
  52432. * @private
  52433. * Parts of Ionic requires that $scope data is attached to the element.
  52434. * We do not want to disable adding $scope data to the $element when
  52435. * $compileProvider.debugInfoEnabled(false) is used.
  52436. */
  52437. IonicModule.config(['$provide', function($provide) {
  52438. $provide.decorator('$compile', ['$delegate', function($compile) {
  52439. $compile.$$addScopeInfo = function $$addScopeInfo($element, scope, isolated, noTemplate) {
  52440. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  52441. $element.data(dataName, scope);
  52442. };
  52443. return $compile;
  52444. }]);
  52445. }]);
  52446. /**
  52447. * @private
  52448. */
  52449. IonicModule.config([
  52450. '$provide',
  52451. function($provide) {
  52452. function $LocationDecorator($location, $timeout) {
  52453. $location.__hash = $location.hash;
  52454. //Fix: when window.location.hash is set, the scrollable area
  52455. //found nearest to body's scrollTop is set to scroll to an element
  52456. //with that ID.
  52457. $location.hash = function(value) {
  52458. if (isDefined(value) && value.length > 0) {
  52459. $timeout(function() {
  52460. var scroll = document.querySelector('.scroll-content');
  52461. if (scroll) {
  52462. scroll.scrollTop = 0;
  52463. }
  52464. }, 0, false);
  52465. }
  52466. return $location.__hash(value);
  52467. };
  52468. return $location;
  52469. }
  52470. $provide.decorator('$location', ['$delegate', '$timeout', $LocationDecorator]);
  52471. }]);
  52472. IonicModule
  52473. .controller('$ionicHeaderBar', [
  52474. '$scope',
  52475. '$element',
  52476. '$attrs',
  52477. '$q',
  52478. '$ionicConfig',
  52479. '$ionicHistory',
  52480. function($scope, $element, $attrs, $q, $ionicConfig, $ionicHistory) {
  52481. var TITLE = 'title';
  52482. var BACK_TEXT = 'back-text';
  52483. var BACK_BUTTON = 'back-button';
  52484. var DEFAULT_TITLE = 'default-title';
  52485. var PREVIOUS_TITLE = 'previous-title';
  52486. var HIDE = 'hide';
  52487. var self = this;
  52488. var titleText = '';
  52489. var previousTitleText = '';
  52490. var titleLeft = 0;
  52491. var titleRight = 0;
  52492. var titleCss = '';
  52493. var isBackEnabled = false;
  52494. var isBackShown = true;
  52495. var isNavBackShown = true;
  52496. var isBackElementShown = false;
  52497. var titleTextWidth = 0;
  52498. self.beforeEnter = function(viewData) {
  52499. $scope.$broadcast('$ionicView.beforeEnter', viewData);
  52500. };
  52501. self.title = function(newTitleText) {
  52502. if (arguments.length && newTitleText !== titleText) {
  52503. getEle(TITLE).innerHTML = newTitleText;
  52504. titleText = newTitleText;
  52505. titleTextWidth = 0;
  52506. }
  52507. return titleText;
  52508. };
  52509. self.enableBack = function(shouldEnable, disableReset) {
  52510. // whether or not the back button show be visible, according
  52511. // to the navigation and history
  52512. if (arguments.length) {
  52513. isBackEnabled = shouldEnable;
  52514. if (!disableReset) self.updateBackButton();
  52515. }
  52516. return isBackEnabled;
  52517. };
  52518. self.showBack = function(shouldShow, disableReset) {
  52519. // different from enableBack() because this will always have the back
  52520. // visually hidden if false, even if the history says it should show
  52521. if (arguments.length) {
  52522. isBackShown = shouldShow;
  52523. if (!disableReset) self.updateBackButton();
  52524. }
  52525. return isBackShown;
  52526. };
  52527. self.showNavBack = function(shouldShow) {
  52528. // different from showBack() because this is for the entire nav bar's
  52529. // setting for all of it's child headers. For internal use.
  52530. isNavBackShown = shouldShow;
  52531. self.updateBackButton();
  52532. };
  52533. self.updateBackButton = function() {
  52534. var ele;
  52535. if ((isBackShown && isNavBackShown && isBackEnabled) !== isBackElementShown) {
  52536. isBackElementShown = isBackShown && isNavBackShown && isBackEnabled;
  52537. ele = getEle(BACK_BUTTON);
  52538. ele && ele.classList[ isBackElementShown ? 'remove' : 'add' ](HIDE);
  52539. }
  52540. if (isBackEnabled) {
  52541. ele = ele || getEle(BACK_BUTTON);
  52542. if (ele) {
  52543. if (self.backButtonIcon !== $ionicConfig.backButton.icon()) {
  52544. ele = getEle(BACK_BUTTON + ' .icon');
  52545. if (ele) {
  52546. self.backButtonIcon = $ionicConfig.backButton.icon();
  52547. ele.className = 'icon ' + self.backButtonIcon;
  52548. }
  52549. }
  52550. if (self.backButtonText !== $ionicConfig.backButton.text()) {
  52551. ele = getEle(BACK_BUTTON + ' .back-text');
  52552. if (ele) {
  52553. ele.textContent = self.backButtonText = $ionicConfig.backButton.text();
  52554. }
  52555. }
  52556. }
  52557. }
  52558. };
  52559. self.titleTextWidth = function() {
  52560. var element = getEle(TITLE);
  52561. if ( element ) {
  52562. // If the element has a nav-bar-title, use that instead
  52563. // to calculate the width of the title
  52564. var children = angular.element(element).children();
  52565. for ( var i = 0; i < children.length; i++ ) {
  52566. if ( angular.element(children[i]).hasClass('nav-bar-title') ) {
  52567. element = children[i];
  52568. break;
  52569. }
  52570. }
  52571. }
  52572. var bounds = ionic.DomUtil.getTextBounds(element);
  52573. titleTextWidth = Math.min(bounds && bounds.width || 30);
  52574. return titleTextWidth;
  52575. };
  52576. self.titleWidth = function() {
  52577. var titleWidth = self.titleTextWidth();
  52578. var offsetWidth = getEle(TITLE).offsetWidth;
  52579. if (offsetWidth < titleWidth) {
  52580. titleWidth = offsetWidth + (titleLeft - titleRight - 5);
  52581. }
  52582. return titleWidth;
  52583. };
  52584. self.titleTextX = function() {
  52585. return ($element[0].offsetWidth / 2) - (self.titleWidth() / 2);
  52586. };
  52587. self.titleLeftRight = function() {
  52588. return titleLeft - titleRight;
  52589. };
  52590. self.backButtonTextLeft = function() {
  52591. var offsetLeft = 0;
  52592. var ele = getEle(BACK_TEXT);
  52593. while (ele) {
  52594. offsetLeft += ele.offsetLeft;
  52595. ele = ele.parentElement;
  52596. }
  52597. return offsetLeft;
  52598. };
  52599. self.resetBackButton = function(viewData) {
  52600. if ($ionicConfig.backButton.previousTitleText()) {
  52601. var previousTitleEle = getEle(PREVIOUS_TITLE);
  52602. if (previousTitleEle) {
  52603. previousTitleEle.classList.remove(HIDE);
  52604. var view = (viewData && $ionicHistory.getViewById(viewData.viewId));
  52605. var newPreviousTitleText = $ionicHistory.backTitle(view);
  52606. if (newPreviousTitleText !== previousTitleText) {
  52607. previousTitleText = previousTitleEle.innerHTML = newPreviousTitleText;
  52608. }
  52609. }
  52610. var defaultTitleEle = getEle(DEFAULT_TITLE);
  52611. if (defaultTitleEle) {
  52612. defaultTitleEle.classList.remove(HIDE);
  52613. }
  52614. }
  52615. };
  52616. self.align = function(textAlign) {
  52617. var titleEle = getEle(TITLE);
  52618. textAlign = textAlign || $attrs.alignTitle || $ionicConfig.navBar.alignTitle();
  52619. var widths = self.calcWidths(textAlign, false);
  52620. if (isBackShown && previousTitleText && $ionicConfig.backButton.previousTitleText()) {
  52621. var previousTitleWidths = self.calcWidths(textAlign, true);
  52622. var availableTitleWidth = $element[0].offsetWidth - previousTitleWidths.titleLeft - previousTitleWidths.titleRight;
  52623. if (self.titleTextWidth() <= availableTitleWidth) {
  52624. widths = previousTitleWidths;
  52625. }
  52626. }
  52627. return self.updatePositions(titleEle, widths.titleLeft, widths.titleRight, widths.buttonsLeft, widths.buttonsRight, widths.css, widths.showPrevTitle);
  52628. };
  52629. self.calcWidths = function(textAlign, isPreviousTitle) {
  52630. var titleEle = getEle(TITLE);
  52631. var backBtnEle = getEle(BACK_BUTTON);
  52632. var x, y, z, b, c, d, childSize, bounds;
  52633. var childNodes = $element[0].childNodes;
  52634. var buttonsLeft = 0;
  52635. var buttonsRight = 0;
  52636. var isCountRightOfTitle;
  52637. var updateTitleLeft = 0;
  52638. var updateTitleRight = 0;
  52639. var updateCss = '';
  52640. var backButtonWidth = 0;
  52641. // Compute how wide the left children are
  52642. // Skip all titles (there may still be two titles, one leaving the dom)
  52643. // Once we encounter a titleEle, realize we are now counting the right-buttons, not left
  52644. for (x = 0; x < childNodes.length; x++) {
  52645. c = childNodes[x];
  52646. childSize = 0;
  52647. if (c.nodeType == 1) {
  52648. // element node
  52649. if (c === titleEle) {
  52650. isCountRightOfTitle = true;
  52651. continue;
  52652. }
  52653. if (c.classList.contains(HIDE)) {
  52654. continue;
  52655. }
  52656. if (isBackShown && c === backBtnEle) {
  52657. for (y = 0; y < c.childNodes.length; y++) {
  52658. b = c.childNodes[y];
  52659. if (b.nodeType == 1) {
  52660. if (b.classList.contains(BACK_TEXT)) {
  52661. for (z = 0; z < b.children.length; z++) {
  52662. d = b.children[z];
  52663. if (isPreviousTitle) {
  52664. if (d.classList.contains(DEFAULT_TITLE)) continue;
  52665. backButtonWidth += d.offsetWidth;
  52666. } else {
  52667. if (d.classList.contains(PREVIOUS_TITLE)) continue;
  52668. backButtonWidth += d.offsetWidth;
  52669. }
  52670. }
  52671. } else {
  52672. backButtonWidth += b.offsetWidth;
  52673. }
  52674. } else if (b.nodeType == 3 && b.nodeValue.trim()) {
  52675. bounds = ionic.DomUtil.getTextBounds(b);
  52676. backButtonWidth += bounds && bounds.width || 0;
  52677. }
  52678. }
  52679. childSize = backButtonWidth || c.offsetWidth;
  52680. } else {
  52681. // not the title, not the back button, not a hidden element
  52682. childSize = c.offsetWidth;
  52683. }
  52684. } else if (c.nodeType == 3 && c.nodeValue.trim()) {
  52685. // text node
  52686. bounds = ionic.DomUtil.getTextBounds(c);
  52687. childSize = bounds && bounds.width || 0;
  52688. }
  52689. if (isCountRightOfTitle) {
  52690. buttonsRight += childSize;
  52691. } else {
  52692. buttonsLeft += childSize;
  52693. }
  52694. }
  52695. // Size and align the header titleEle based on the sizes of the left and
  52696. // right children, and the desired alignment mode
  52697. if (textAlign == 'left') {
  52698. updateCss = 'title-left';
  52699. if (buttonsLeft) {
  52700. updateTitleLeft = buttonsLeft + 15;
  52701. }
  52702. if (buttonsRight) {
  52703. updateTitleRight = buttonsRight + 15;
  52704. }
  52705. } else if (textAlign == 'right') {
  52706. updateCss = 'title-right';
  52707. if (buttonsLeft) {
  52708. updateTitleLeft = buttonsLeft + 15;
  52709. }
  52710. if (buttonsRight) {
  52711. updateTitleRight = buttonsRight + 15;
  52712. }
  52713. } else {
  52714. // center the default
  52715. var margin = Math.max(buttonsLeft, buttonsRight) + 10;
  52716. if (margin > 10) {
  52717. updateTitleLeft = updateTitleRight = margin;
  52718. }
  52719. }
  52720. return {
  52721. backButtonWidth: backButtonWidth,
  52722. buttonsLeft: buttonsLeft,
  52723. buttonsRight: buttonsRight,
  52724. titleLeft: updateTitleLeft,
  52725. titleRight: updateTitleRight,
  52726. showPrevTitle: isPreviousTitle,
  52727. css: updateCss
  52728. };
  52729. };
  52730. self.updatePositions = function(titleEle, updateTitleLeft, updateTitleRight, buttonsLeft, buttonsRight, updateCss, showPreviousTitle) {
  52731. var deferred = $q.defer();
  52732. // only make DOM updates when there are actual changes
  52733. if (titleEle) {
  52734. if (updateTitleLeft !== titleLeft) {
  52735. titleEle.style.left = updateTitleLeft ? updateTitleLeft + 'px' : '';
  52736. titleLeft = updateTitleLeft;
  52737. }
  52738. if (updateTitleRight !== titleRight) {
  52739. titleEle.style.right = updateTitleRight ? updateTitleRight + 'px' : '';
  52740. titleRight = updateTitleRight;
  52741. }
  52742. if (updateCss !== titleCss) {
  52743. updateCss && titleEle.classList.add(updateCss);
  52744. titleCss && titleEle.classList.remove(titleCss);
  52745. titleCss = updateCss;
  52746. }
  52747. }
  52748. if ($ionicConfig.backButton.previousTitleText()) {
  52749. var prevTitle = getEle(PREVIOUS_TITLE);
  52750. var defaultTitle = getEle(DEFAULT_TITLE);
  52751. prevTitle && prevTitle.classList[ showPreviousTitle ? 'remove' : 'add'](HIDE);
  52752. defaultTitle && defaultTitle.classList[ showPreviousTitle ? 'add' : 'remove'](HIDE);
  52753. }
  52754. ionic.requestAnimationFrame(function() {
  52755. if (titleEle && titleEle.offsetWidth + 10 < titleEle.scrollWidth) {
  52756. var minRight = buttonsRight + 5;
  52757. var testRight = $element[0].offsetWidth - titleLeft - self.titleTextWidth() - 20;
  52758. updateTitleRight = testRight < minRight ? minRight : testRight;
  52759. if (updateTitleRight !== titleRight) {
  52760. titleEle.style.right = updateTitleRight + 'px';
  52761. titleRight = updateTitleRight;
  52762. }
  52763. }
  52764. deferred.resolve();
  52765. });
  52766. return deferred.promise;
  52767. };
  52768. self.setCss = function(elementClassname, css) {
  52769. ionic.DomUtil.cachedStyles(getEle(elementClassname), css);
  52770. };
  52771. var eleCache = {};
  52772. function getEle(className) {
  52773. if (!eleCache[className]) {
  52774. eleCache[className] = $element[0].querySelector('.' + className);
  52775. }
  52776. return eleCache[className];
  52777. }
  52778. $scope.$on('$destroy', function() {
  52779. for (var n in eleCache) eleCache[n] = null;
  52780. });
  52781. }]);
  52782. IonicModule
  52783. .controller('$ionInfiniteScroll', [
  52784. '$scope',
  52785. '$attrs',
  52786. '$element',
  52787. '$timeout',
  52788. function($scope, $attrs, $element, $timeout) {
  52789. var self = this;
  52790. self.isLoading = false;
  52791. $scope.icon = function() {
  52792. return isDefined($attrs.icon) ? $attrs.icon : 'ion-load-d';
  52793. };
  52794. $scope.spinner = function() {
  52795. return isDefined($attrs.spinner) ? $attrs.spinner : '';
  52796. };
  52797. $scope.$on('scroll.infiniteScrollComplete', function() {
  52798. finishInfiniteScroll();
  52799. });
  52800. $scope.$on('$destroy', function() {
  52801. if (self.scrollCtrl && self.scrollCtrl.$element) self.scrollCtrl.$element.off('scroll', self.checkBounds);
  52802. if (self.scrollEl && self.scrollEl.removeEventListener) {
  52803. self.scrollEl.removeEventListener('scroll', self.checkBounds);
  52804. }
  52805. });
  52806. // debounce checking infinite scroll events
  52807. self.checkBounds = ionic.Utils.throttle(checkInfiniteBounds, 300);
  52808. function onInfinite() {
  52809. ionic.requestAnimationFrame(function() {
  52810. $element[0].classList.add('active');
  52811. });
  52812. self.isLoading = true;
  52813. $scope.$parent && $scope.$parent.$apply($attrs.onInfinite || '');
  52814. }
  52815. function finishInfiniteScroll() {
  52816. ionic.requestAnimationFrame(function() {
  52817. $element[0].classList.remove('active');
  52818. });
  52819. $timeout(function() {
  52820. if (self.jsScrolling) self.scrollView.resize();
  52821. // only check bounds again immediately if the page isn't cached (scroll el has height)
  52822. if ((self.jsScrolling && self.scrollView.__container && self.scrollView.__container.offsetHeight > 0) ||
  52823. !self.jsScrolling) {
  52824. self.checkBounds();
  52825. }
  52826. }, 30, false);
  52827. self.isLoading = false;
  52828. }
  52829. // check if we've scrolled far enough to trigger an infinite scroll
  52830. function checkInfiniteBounds() {
  52831. if (self.isLoading) return;
  52832. var maxScroll = {};
  52833. if (self.jsScrolling) {
  52834. maxScroll = self.getJSMaxScroll();
  52835. var scrollValues = self.scrollView.getValues();
  52836. if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||
  52837. (maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {
  52838. onInfinite();
  52839. }
  52840. } else {
  52841. maxScroll = self.getNativeMaxScroll();
  52842. if ((
  52843. maxScroll.left !== -1 &&
  52844. self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth
  52845. ) || (
  52846. maxScroll.top !== -1 &&
  52847. self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight
  52848. )) {
  52849. onInfinite();
  52850. }
  52851. }
  52852. }
  52853. // determine the threshold at which we should fire an infinite scroll
  52854. // note: this gets processed every scroll event, can it be cached?
  52855. self.getJSMaxScroll = function() {
  52856. var maxValues = self.scrollView.getScrollMax();
  52857. return {
  52858. left: self.scrollView.options.scrollingX ?
  52859. calculateMaxValue(maxValues.left) :
  52860. -1,
  52861. top: self.scrollView.options.scrollingY ?
  52862. calculateMaxValue(maxValues.top) :
  52863. -1
  52864. };
  52865. };
  52866. self.getNativeMaxScroll = function() {
  52867. var maxValues = {
  52868. left: self.scrollEl.scrollWidth,
  52869. top: self.scrollEl.scrollHeight
  52870. };
  52871. var computedStyle = window.getComputedStyle(self.scrollEl) || {};
  52872. return {
  52873. left: maxValues.left &&
  52874. (computedStyle.overflowX === 'scroll' ||
  52875. computedStyle.overflowX === 'auto' ||
  52876. self.scrollEl.style['overflow-x'] === 'scroll') ?
  52877. calculateMaxValue(maxValues.left) : -1,
  52878. top: maxValues.top &&
  52879. (computedStyle.overflowY === 'scroll' ||
  52880. computedStyle.overflowY === 'auto' ||
  52881. self.scrollEl.style['overflow-y'] === 'scroll' ) ?
  52882. calculateMaxValue(maxValues.top) : -1
  52883. };
  52884. };
  52885. // determine pixel refresh distance based on % or value
  52886. function calculateMaxValue(maximum) {
  52887. var distance = ($attrs.distance || '2.5%').trim();
  52888. var isPercent = distance.indexOf('%') !== -1;
  52889. return isPercent ?
  52890. maximum * (1 - parseFloat(distance) / 100) :
  52891. maximum - parseFloat(distance);
  52892. }
  52893. //for testing
  52894. self.__finishInfiniteScroll = finishInfiniteScroll;
  52895. }]);
  52896. /**
  52897. * @ngdoc service
  52898. * @name $ionicListDelegate
  52899. * @module ionic
  52900. *
  52901. * @description
  52902. * Delegate for controlling the {@link ionic.directive:ionList} directive.
  52903. *
  52904. * Methods called directly on the $ionicListDelegate service will control all lists.
  52905. * Use the {@link ionic.service:$ionicListDelegate#$getByHandle $getByHandle}
  52906. * method to control specific ionList instances.
  52907. *
  52908. * @usage
  52909. * ```html
  52910. * {% raw %}
  52911. * <ion-content ng-controller="MyCtrl">
  52912. * <button class="button" ng-click="showDeleteButtons()"></button>
  52913. * <ion-list>
  52914. * <ion-item ng-repeat="i in items">
  52915. * Hello, {{i}}!
  52916. * <ion-delete-button class="ion-minus-circled"></ion-delete-button>
  52917. * </ion-item>
  52918. * </ion-list>
  52919. * </ion-content>
  52920. * {% endraw %}
  52921. * ```
  52922. * ```js
  52923. * function MyCtrl($scope, $ionicListDelegate) {
  52924. * $scope.showDeleteButtons = function() {
  52925. * $ionicListDelegate.showDelete(true);
  52926. * };
  52927. * }
  52928. * ```
  52929. */
  52930. IonicModule.service('$ionicListDelegate', ionic.DelegateService([
  52931. /**
  52932. * @ngdoc method
  52933. * @name $ionicListDelegate#showReorder
  52934. * @param {boolean=} showReorder Set whether or not this list is showing its reorder buttons.
  52935. * @returns {boolean} Whether the reorder buttons are shown.
  52936. */
  52937. 'showReorder',
  52938. /**
  52939. * @ngdoc method
  52940. * @name $ionicListDelegate#showDelete
  52941. * @param {boolean=} showDelete Set whether or not this list is showing its delete buttons.
  52942. * @returns {boolean} Whether the delete buttons are shown.
  52943. */
  52944. 'showDelete',
  52945. /**
  52946. * @ngdoc method
  52947. * @name $ionicListDelegate#canSwipeItems
  52948. * @param {boolean=} canSwipeItems Set whether or not this list is able to swipe to show
  52949. * option buttons.
  52950. * @returns {boolean} Whether the list is able to swipe to show option buttons.
  52951. */
  52952. 'canSwipeItems',
  52953. /**
  52954. * @ngdoc method
  52955. * @name $ionicListDelegate#closeOptionButtons
  52956. * @description Closes any option buttons on the list that are swiped open.
  52957. */
  52958. 'closeOptionButtons'
  52959. /**
  52960. * @ngdoc method
  52961. * @name $ionicListDelegate#$getByHandle
  52962. * @param {string} handle
  52963. * @returns `delegateInstance` A delegate instance that controls only the
  52964. * {@link ionic.directive:ionList} directives with `delegate-handle` matching
  52965. * the given handle.
  52966. *
  52967. * Example: `$ionicListDelegate.$getByHandle('my-handle').showReorder(true);`
  52968. */
  52969. ]))
  52970. .controller('$ionicList', [
  52971. '$scope',
  52972. '$attrs',
  52973. '$ionicListDelegate',
  52974. '$ionicHistory',
  52975. function($scope, $attrs, $ionicListDelegate, $ionicHistory) {
  52976. var self = this;
  52977. var isSwipeable = true;
  52978. var isReorderShown = false;
  52979. var isDeleteShown = false;
  52980. var deregisterInstance = $ionicListDelegate._registerInstance(
  52981. self, $attrs.delegateHandle, function() {
  52982. return $ionicHistory.isActiveScope($scope);
  52983. }
  52984. );
  52985. $scope.$on('$destroy', deregisterInstance);
  52986. self.showReorder = function(show) {
  52987. if (arguments.length) {
  52988. isReorderShown = !!show;
  52989. }
  52990. return isReorderShown;
  52991. };
  52992. self.showDelete = function(show) {
  52993. if (arguments.length) {
  52994. isDeleteShown = !!show;
  52995. }
  52996. return isDeleteShown;
  52997. };
  52998. self.canSwipeItems = function(can) {
  52999. if (arguments.length) {
  53000. isSwipeable = !!can;
  53001. }
  53002. return isSwipeable;
  53003. };
  53004. self.closeOptionButtons = function() {
  53005. self.listView && self.listView.clearDragEffects();
  53006. };
  53007. }]);
  53008. IonicModule
  53009. .controller('$ionicNavBar', [
  53010. '$scope',
  53011. '$element',
  53012. '$attrs',
  53013. '$compile',
  53014. '$timeout',
  53015. '$ionicNavBarDelegate',
  53016. '$ionicConfig',
  53017. '$ionicHistory',
  53018. function($scope, $element, $attrs, $compile, $timeout, $ionicNavBarDelegate, $ionicConfig, $ionicHistory) {
  53019. var CSS_HIDE = 'hide';
  53020. var DATA_NAV_BAR_CTRL = '$ionNavBarController';
  53021. var PRIMARY_BUTTONS = 'primaryButtons';
  53022. var SECONDARY_BUTTONS = 'secondaryButtons';
  53023. var BACK_BUTTON = 'backButton';
  53024. var ITEM_TYPES = 'primaryButtons secondaryButtons leftButtons rightButtons title'.split(' ');
  53025. var self = this;
  53026. var headerBars = [];
  53027. var navElementHtml = {};
  53028. var isVisible = true;
  53029. var queuedTransitionStart, queuedTransitionEnd, latestTransitionId;
  53030. $element.parent().data(DATA_NAV_BAR_CTRL, self);
  53031. var delegateHandle = $attrs.delegateHandle || 'navBar' + ionic.Utils.nextUid();
  53032. var deregisterInstance = $ionicNavBarDelegate._registerInstance(self, delegateHandle);
  53033. self.init = function() {
  53034. $element.addClass('nav-bar-container');
  53035. ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', $ionicConfig.views.transition());
  53036. // create two nav bar blocks which will trade out which one is shown
  53037. self.createHeaderBar(false);
  53038. self.createHeaderBar(true);
  53039. $scope.$emit('ionNavBar.init', delegateHandle);
  53040. };
  53041. self.createHeaderBar = function(isActive) {
  53042. var containerEle = jqLite('<div class="nav-bar-block">');
  53043. ionic.DomUtil.cachedAttr(containerEle, 'nav-bar', isActive ? 'active' : 'cached');
  53044. var alignTitle = $attrs.alignTitle || $ionicConfig.navBar.alignTitle();
  53045. var headerBarEle = jqLite('<ion-header-bar>').addClass($attrs['class']).attr('align-title', alignTitle);
  53046. if (isDefined($attrs.noTapScroll)) headerBarEle.attr('no-tap-scroll', $attrs.noTapScroll);
  53047. var titleEle = jqLite('<div class="title title-' + alignTitle + '">');
  53048. var navEle = {};
  53049. var lastViewItemEle = {};
  53050. var leftButtonsEle, rightButtonsEle;
  53051. navEle[BACK_BUTTON] = createNavElement(BACK_BUTTON);
  53052. navEle[BACK_BUTTON] && headerBarEle.append(navEle[BACK_BUTTON]);
  53053. // append title in the header, this is the rock to where buttons append
  53054. headerBarEle.append(titleEle);
  53055. forEach(ITEM_TYPES, function(itemType) {
  53056. // create default button elements
  53057. navEle[itemType] = createNavElement(itemType);
  53058. // append and position buttons
  53059. positionItem(navEle[itemType], itemType);
  53060. });
  53061. // add header-item to the root children
  53062. for (var x = 0; x < headerBarEle[0].children.length; x++) {
  53063. headerBarEle[0].children[x].classList.add('header-item');
  53064. }
  53065. // compile header and append to the DOM
  53066. containerEle.append(headerBarEle);
  53067. $element.append($compile(containerEle)($scope.$new()));
  53068. var headerBarCtrl = headerBarEle.data('$ionHeaderBarController');
  53069. headerBarCtrl.backButtonIcon = $ionicConfig.backButton.icon();
  53070. headerBarCtrl.backButtonText = $ionicConfig.backButton.text();
  53071. var headerBarInstance = {
  53072. isActive: isActive,
  53073. title: function(newTitleText) {
  53074. headerBarCtrl.title(newTitleText);
  53075. },
  53076. setItem: function(navBarItemEle, itemType) {
  53077. // first make sure any exiting nav bar item has been removed
  53078. headerBarInstance.removeItem(itemType);
  53079. if (navBarItemEle) {
  53080. if (itemType === 'title') {
  53081. // clear out the text based title
  53082. headerBarInstance.title("");
  53083. }
  53084. // there's a custom nav bar item
  53085. positionItem(navBarItemEle, itemType);
  53086. if (navEle[itemType]) {
  53087. // make sure the default on this itemType is hidden
  53088. navEle[itemType].addClass(CSS_HIDE);
  53089. }
  53090. lastViewItemEle[itemType] = navBarItemEle;
  53091. } else if (navEle[itemType]) {
  53092. // there's a default button for this side and no view button
  53093. navEle[itemType].removeClass(CSS_HIDE);
  53094. }
  53095. },
  53096. removeItem: function(itemType) {
  53097. if (lastViewItemEle[itemType]) {
  53098. lastViewItemEle[itemType].scope().$destroy();
  53099. lastViewItemEle[itemType].remove();
  53100. lastViewItemEle[itemType] = null;
  53101. }
  53102. },
  53103. containerEle: function() {
  53104. return containerEle;
  53105. },
  53106. headerBarEle: function() {
  53107. return headerBarEle;
  53108. },
  53109. afterLeave: function() {
  53110. forEach(ITEM_TYPES, function(itemType) {
  53111. headerBarInstance.removeItem(itemType);
  53112. });
  53113. headerBarCtrl.resetBackButton();
  53114. },
  53115. controller: function() {
  53116. return headerBarCtrl;
  53117. },
  53118. destroy: function() {
  53119. forEach(ITEM_TYPES, function(itemType) {
  53120. headerBarInstance.removeItem(itemType);
  53121. });
  53122. containerEle.scope().$destroy();
  53123. for (var n in navEle) {
  53124. if (navEle[n]) {
  53125. navEle[n].removeData();
  53126. navEle[n] = null;
  53127. }
  53128. }
  53129. leftButtonsEle && leftButtonsEle.removeData();
  53130. rightButtonsEle && rightButtonsEle.removeData();
  53131. titleEle.removeData();
  53132. headerBarEle.removeData();
  53133. containerEle.remove();
  53134. containerEle = headerBarEle = titleEle = leftButtonsEle = rightButtonsEle = null;
  53135. }
  53136. };
  53137. function positionItem(ele, itemType) {
  53138. if (!ele) return;
  53139. if (itemType === 'title') {
  53140. // title element
  53141. titleEle.append(ele);
  53142. } else if (itemType == 'rightButtons' ||
  53143. (itemType == SECONDARY_BUTTONS && $ionicConfig.navBar.positionSecondaryButtons() != 'left') ||
  53144. (itemType == PRIMARY_BUTTONS && $ionicConfig.navBar.positionPrimaryButtons() == 'right')) {
  53145. // right side
  53146. if (!rightButtonsEle) {
  53147. rightButtonsEle = jqLite('<div class="buttons buttons-right">');
  53148. headerBarEle.append(rightButtonsEle);
  53149. }
  53150. if (itemType == SECONDARY_BUTTONS) {
  53151. rightButtonsEle.append(ele);
  53152. } else {
  53153. rightButtonsEle.prepend(ele);
  53154. }
  53155. } else {
  53156. // left side
  53157. if (!leftButtonsEle) {
  53158. leftButtonsEle = jqLite('<div class="buttons buttons-left">');
  53159. if (navEle[BACK_BUTTON]) {
  53160. navEle[BACK_BUTTON].after(leftButtonsEle);
  53161. } else {
  53162. headerBarEle.prepend(leftButtonsEle);
  53163. }
  53164. }
  53165. if (itemType == SECONDARY_BUTTONS) {
  53166. leftButtonsEle.append(ele);
  53167. } else {
  53168. leftButtonsEle.prepend(ele);
  53169. }
  53170. }
  53171. }
  53172. headerBars.push(headerBarInstance);
  53173. return headerBarInstance;
  53174. };
  53175. self.navElement = function(type, html) {
  53176. if (isDefined(html)) {
  53177. navElementHtml[type] = html;
  53178. }
  53179. return navElementHtml[type];
  53180. };
  53181. self.update = function(viewData) {
  53182. var showNavBar = !viewData.hasHeaderBar && viewData.showNavBar;
  53183. viewData.transition = $ionicConfig.views.transition();
  53184. if (!showNavBar) {
  53185. viewData.direction = 'none';
  53186. }
  53187. self.enable(showNavBar);
  53188. var enteringHeaderBar = self.isInitialized ? getOffScreenHeaderBar() : getOnScreenHeaderBar();
  53189. var leavingHeaderBar = self.isInitialized ? getOnScreenHeaderBar() : null;
  53190. var enteringHeaderCtrl = enteringHeaderBar.controller();
  53191. // update if the entering header should show the back button or not
  53192. enteringHeaderCtrl.enableBack(viewData.enableBack, true);
  53193. enteringHeaderCtrl.showBack(viewData.showBack, true);
  53194. enteringHeaderCtrl.updateBackButton();
  53195. // update the entering header bar's title
  53196. self.title(viewData.title, enteringHeaderBar);
  53197. self.showBar(showNavBar);
  53198. // update the nav bar items, depending if the view has their own or not
  53199. if (viewData.navBarItems) {
  53200. forEach(ITEM_TYPES, function(itemType) {
  53201. enteringHeaderBar.setItem(viewData.navBarItems[itemType], itemType);
  53202. });
  53203. }
  53204. // begin transition of entering and leaving header bars
  53205. self.transition(enteringHeaderBar, leavingHeaderBar, viewData);
  53206. self.isInitialized = true;
  53207. navSwipeAttr('');
  53208. };
  53209. self.transition = function(enteringHeaderBar, leavingHeaderBar, viewData) {
  53210. var enteringHeaderBarCtrl = enteringHeaderBar.controller();
  53211. var transitionFn = $ionicConfig.transitions.navBar[viewData.navBarTransition] || $ionicConfig.transitions.navBar.none;
  53212. var transitionId = viewData.transitionId;
  53213. enteringHeaderBarCtrl.beforeEnter(viewData);
  53214. var navBarTransition = transitionFn(enteringHeaderBar, leavingHeaderBar, viewData.direction, viewData.shouldAnimate && self.isInitialized);
  53215. ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', viewData.navBarTransition);
  53216. ionic.DomUtil.cachedAttr($element, 'nav-bar-direction', viewData.direction);
  53217. if (navBarTransition.shouldAnimate && viewData.renderEnd) {
  53218. navBarAttr(enteringHeaderBar, 'stage');
  53219. } else {
  53220. navBarAttr(enteringHeaderBar, 'entering');
  53221. navBarAttr(leavingHeaderBar, 'leaving');
  53222. }
  53223. enteringHeaderBarCtrl.resetBackButton(viewData);
  53224. navBarTransition.run(0);
  53225. self.activeTransition = {
  53226. run: function(step) {
  53227. navBarTransition.shouldAnimate = false;
  53228. navBarTransition.direction = 'back';
  53229. navBarTransition.run(step);
  53230. },
  53231. cancel: function(shouldAnimate, speed, cancelData) {
  53232. navSwipeAttr(speed);
  53233. navBarAttr(leavingHeaderBar, 'active');
  53234. navBarAttr(enteringHeaderBar, 'cached');
  53235. navBarTransition.shouldAnimate = shouldAnimate;
  53236. navBarTransition.run(0);
  53237. self.activeTransition = navBarTransition = null;
  53238. var runApply;
  53239. if (cancelData.showBar !== self.showBar()) {
  53240. self.showBar(cancelData.showBar);
  53241. }
  53242. if (cancelData.showBackButton !== self.showBackButton()) {
  53243. self.showBackButton(cancelData.showBackButton);
  53244. }
  53245. if (runApply) {
  53246. $scope.$apply();
  53247. }
  53248. },
  53249. complete: function(shouldAnimate, speed) {
  53250. navSwipeAttr(speed);
  53251. navBarTransition.shouldAnimate = shouldAnimate;
  53252. navBarTransition.run(1);
  53253. queuedTransitionEnd = transitionEnd;
  53254. }
  53255. };
  53256. $timeout(enteringHeaderBarCtrl.align, 16);
  53257. queuedTransitionStart = function() {
  53258. if (latestTransitionId !== transitionId) return;
  53259. navBarAttr(enteringHeaderBar, 'entering');
  53260. navBarAttr(leavingHeaderBar, 'leaving');
  53261. navBarTransition.run(1);
  53262. queuedTransitionEnd = function() {
  53263. if (latestTransitionId == transitionId || !navBarTransition.shouldAnimate) {
  53264. transitionEnd();
  53265. }
  53266. };
  53267. queuedTransitionStart = null;
  53268. };
  53269. function transitionEnd() {
  53270. for (var x = 0; x < headerBars.length; x++) {
  53271. headerBars[x].isActive = false;
  53272. }
  53273. enteringHeaderBar.isActive = true;
  53274. navBarAttr(enteringHeaderBar, 'active');
  53275. navBarAttr(leavingHeaderBar, 'cached');
  53276. self.activeTransition = navBarTransition = queuedTransitionEnd = null;
  53277. }
  53278. queuedTransitionStart();
  53279. };
  53280. self.triggerTransitionStart = function(triggerTransitionId) {
  53281. latestTransitionId = triggerTransitionId;
  53282. queuedTransitionStart && queuedTransitionStart();
  53283. };
  53284. self.triggerTransitionEnd = function() {
  53285. queuedTransitionEnd && queuedTransitionEnd();
  53286. };
  53287. self.showBar = function(shouldShow) {
  53288. if (arguments.length) {
  53289. self.visibleBar(shouldShow);
  53290. $scope.$parent.$hasHeader = !!shouldShow;
  53291. }
  53292. return !!$scope.$parent.$hasHeader;
  53293. };
  53294. self.visibleBar = function(shouldShow) {
  53295. if (shouldShow && !isVisible) {
  53296. $element.removeClass(CSS_HIDE);
  53297. self.align();
  53298. } else if (!shouldShow && isVisible) {
  53299. $element.addClass(CSS_HIDE);
  53300. }
  53301. isVisible = shouldShow;
  53302. };
  53303. self.enable = function(val) {
  53304. // set primary to show first
  53305. self.visibleBar(val);
  53306. // set non primary to hide second
  53307. for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {
  53308. if ($ionicNavBarDelegate._instances[x] !== self) $ionicNavBarDelegate._instances[x].visibleBar(false);
  53309. }
  53310. };
  53311. /**
  53312. * @ngdoc method
  53313. * @name $ionicNavBar#showBackButton
  53314. * @description Show/hide the nav bar back button when there is a
  53315. * back view. If the back button is not possible, for example, the
  53316. * first view in the stack, then this will not force the back button
  53317. * to show.
  53318. */
  53319. self.showBackButton = function(shouldShow) {
  53320. if (arguments.length) {
  53321. for (var x = 0; x < headerBars.length; x++) {
  53322. headerBars[x].controller().showNavBack(!!shouldShow);
  53323. }
  53324. $scope.$isBackButtonShown = !!shouldShow;
  53325. }
  53326. return $scope.$isBackButtonShown;
  53327. };
  53328. /**
  53329. * @ngdoc method
  53330. * @name $ionicNavBar#showActiveBackButton
  53331. * @description Show/hide only the active header bar's back button.
  53332. */
  53333. self.showActiveBackButton = function(shouldShow) {
  53334. var headerBar = getOnScreenHeaderBar();
  53335. if (headerBar) {
  53336. if (arguments.length) {
  53337. return headerBar.controller().showBack(shouldShow);
  53338. }
  53339. return headerBar.controller().showBack();
  53340. }
  53341. };
  53342. self.title = function(newTitleText, headerBar) {
  53343. if (isDefined(newTitleText)) {
  53344. newTitleText = newTitleText || '';
  53345. headerBar = headerBar || getOnScreenHeaderBar();
  53346. headerBar && headerBar.title(newTitleText);
  53347. $scope.$title = newTitleText;
  53348. $ionicHistory.currentTitle(newTitleText);
  53349. }
  53350. return $scope.$title;
  53351. };
  53352. self.align = function(val, headerBar) {
  53353. headerBar = headerBar || getOnScreenHeaderBar();
  53354. headerBar && headerBar.controller().align(val);
  53355. };
  53356. self.hasTabsTop = function(isTabsTop) {
  53357. $element[isTabsTop ? 'addClass' : 'removeClass']('nav-bar-tabs-top');
  53358. };
  53359. self.hasBarSubheader = function(isBarSubheader) {
  53360. $element[isBarSubheader ? 'addClass' : 'removeClass']('nav-bar-has-subheader');
  53361. };
  53362. // DEPRECATED, as of v1.0.0-beta14 -------
  53363. self.changeTitle = function(val) {
  53364. deprecatedWarning('changeTitle(val)', 'title(val)');
  53365. self.title(val);
  53366. };
  53367. self.setTitle = function(val) {
  53368. deprecatedWarning('setTitle(val)', 'title(val)');
  53369. self.title(val);
  53370. };
  53371. self.getTitle = function() {
  53372. deprecatedWarning('getTitle()', 'title()');
  53373. return self.title();
  53374. };
  53375. self.back = function() {
  53376. deprecatedWarning('back()', '$ionicHistory.goBack()');
  53377. $ionicHistory.goBack();
  53378. };
  53379. self.getPreviousTitle = function() {
  53380. deprecatedWarning('getPreviousTitle()', '$ionicHistory.backTitle()');
  53381. $ionicHistory.goBack();
  53382. };
  53383. function deprecatedWarning(oldMethod, newMethod) {
  53384. var warn = console.warn || console.log;
  53385. warn && warn.call(console, 'navBarController.' + oldMethod + ' is deprecated, please use ' + newMethod + ' instead');
  53386. }
  53387. // END DEPRECATED -------
  53388. function createNavElement(type) {
  53389. if (navElementHtml[type]) {
  53390. return jqLite(navElementHtml[type]);
  53391. }
  53392. }
  53393. function getOnScreenHeaderBar() {
  53394. for (var x = 0; x < headerBars.length; x++) {
  53395. if (headerBars[x].isActive) return headerBars[x];
  53396. }
  53397. }
  53398. function getOffScreenHeaderBar() {
  53399. for (var x = 0; x < headerBars.length; x++) {
  53400. if (!headerBars[x].isActive) return headerBars[x];
  53401. }
  53402. }
  53403. function navBarAttr(ctrl, val) {
  53404. ctrl && ionic.DomUtil.cachedAttr(ctrl.containerEle(), 'nav-bar', val);
  53405. }
  53406. function navSwipeAttr(val) {
  53407. ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);
  53408. }
  53409. $scope.$on('$destroy', function() {
  53410. $scope.$parent.$hasHeader = false;
  53411. $element.parent().removeData(DATA_NAV_BAR_CTRL);
  53412. for (var x = 0; x < headerBars.length; x++) {
  53413. headerBars[x].destroy();
  53414. }
  53415. $element.remove();
  53416. $element = headerBars = null;
  53417. deregisterInstance();
  53418. });
  53419. }]);
  53420. IonicModule
  53421. .controller('$ionicNavView', [
  53422. '$scope',
  53423. '$element',
  53424. '$attrs',
  53425. '$compile',
  53426. '$controller',
  53427. '$ionicNavBarDelegate',
  53428. '$ionicNavViewDelegate',
  53429. '$ionicHistory',
  53430. '$ionicViewSwitcher',
  53431. '$ionicConfig',
  53432. '$ionicScrollDelegate',
  53433. '$ionicSideMenuDelegate',
  53434. function($scope, $element, $attrs, $compile, $controller, $ionicNavBarDelegate, $ionicNavViewDelegate, $ionicHistory, $ionicViewSwitcher, $ionicConfig, $ionicScrollDelegate, $ionicSideMenuDelegate) {
  53435. var DATA_ELE_IDENTIFIER = '$eleId';
  53436. var DATA_DESTROY_ELE = '$destroyEle';
  53437. var DATA_NO_CACHE = '$noCache';
  53438. var VIEW_STATUS_ACTIVE = 'active';
  53439. var VIEW_STATUS_CACHED = 'cached';
  53440. var self = this;
  53441. var direction;
  53442. var isPrimary = false;
  53443. var navBarDelegate;
  53444. var activeEleId;
  53445. var navViewAttr = $ionicViewSwitcher.navViewAttr;
  53446. var disableRenderStartViewId, disableAnimation;
  53447. self.scope = $scope;
  53448. self.element = $element;
  53449. self.init = function() {
  53450. var navViewName = $attrs.name || '';
  53451. // Find the details of the parent view directive (if any) and use it
  53452. // to derive our own qualified view name, then hang our own details
  53453. // off the DOM so child directives can find it.
  53454. var parent = $element.parent().inheritedData('$uiView');
  53455. var parentViewName = ((parent && parent.state) ? parent.state.name : '');
  53456. if (navViewName.indexOf('@') < 0) navViewName = navViewName + '@' + parentViewName;
  53457. var viewData = { name: navViewName, state: null };
  53458. $element.data('$uiView', viewData);
  53459. var deregisterInstance = $ionicNavViewDelegate._registerInstance(self, $attrs.delegateHandle);
  53460. $scope.$on('$destroy', function() {
  53461. deregisterInstance();
  53462. // ensure no scrolls have been left frozen
  53463. if (self.isSwipeFreeze) {
  53464. $ionicScrollDelegate.freezeAllScrolls(false);
  53465. }
  53466. });
  53467. $scope.$on('$ionicHistory.deselect', self.cacheCleanup);
  53468. $scope.$on('$ionicTabs.top', onTabsTop);
  53469. $scope.$on('$ionicSubheader', onBarSubheader);
  53470. $scope.$on('$ionicTabs.beforeLeave', onTabsLeave);
  53471. $scope.$on('$ionicTabs.afterLeave', onTabsLeave);
  53472. $scope.$on('$ionicTabs.leave', onTabsLeave);
  53473. ionic.Platform.ready(function() {
  53474. if ( ionic.Platform.isWebView() && ionic.Platform.isIOS() ) {
  53475. self.initSwipeBack();
  53476. }
  53477. });
  53478. return viewData;
  53479. };
  53480. self.register = function(viewLocals) {
  53481. var leavingView = extend({}, $ionicHistory.currentView());
  53482. // register that a view is coming in and get info on how it should transition
  53483. var registerData = $ionicHistory.register($scope, viewLocals);
  53484. // update which direction
  53485. self.update(registerData);
  53486. // begin rendering and transitioning
  53487. var enteringView = $ionicHistory.getViewById(registerData.viewId) || {};
  53488. var renderStart = (disableRenderStartViewId !== registerData.viewId);
  53489. self.render(registerData, viewLocals, enteringView, leavingView, renderStart, true);
  53490. };
  53491. self.update = function(registerData) {
  53492. // always reset that this is the primary navView
  53493. isPrimary = true;
  53494. // remember what direction this navView should use
  53495. // this may get updated later by a child navView
  53496. direction = registerData.direction;
  53497. var parentNavViewCtrl = $element.parent().inheritedData('$ionNavViewController');
  53498. if (parentNavViewCtrl) {
  53499. // this navView is nested inside another one
  53500. // update the parent to use this direction and not
  53501. // the other it originally was set to
  53502. // inform the parent navView that it is not the primary navView
  53503. parentNavViewCtrl.isPrimary(false);
  53504. if (direction === 'enter' || direction === 'exit') {
  53505. // they're entering/exiting a history
  53506. // find parent navViewController
  53507. parentNavViewCtrl.direction(direction);
  53508. if (direction === 'enter') {
  53509. // reset the direction so this navView doesn't animate
  53510. // because it's parent will
  53511. direction = 'none';
  53512. }
  53513. }
  53514. }
  53515. };
  53516. self.render = function(registerData, viewLocals, enteringView, leavingView, renderStart, renderEnd) {
  53517. // register the view and figure out where it lives in the various
  53518. // histories and nav stacks, along with how views should enter/leave
  53519. var switcher = $ionicViewSwitcher.create(self, viewLocals, enteringView, leavingView, renderStart, renderEnd);
  53520. // init the rendering of views for this navView directive
  53521. switcher.init(registerData, function() {
  53522. // the view is now compiled, in the dom and linked, now lets transition the views.
  53523. // this uses a callback incase THIS nav-view has a nested nav-view, and after the NESTED
  53524. // nav-view links, the NESTED nav-view would update which direction THIS nav-view should use
  53525. // kick off the transition of views
  53526. switcher.transition(self.direction(), registerData.enableBack, !disableAnimation);
  53527. // reset private vars for next time
  53528. disableRenderStartViewId = disableAnimation = null;
  53529. });
  53530. };
  53531. self.beforeEnter = function(transitionData) {
  53532. if (isPrimary) {
  53533. // only update this nav-view's nav-bar if this is the primary nav-view
  53534. navBarDelegate = transitionData.navBarDelegate;
  53535. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53536. associatedNavBarCtrl && associatedNavBarCtrl.update(transitionData);
  53537. navSwipeAttr('');
  53538. }
  53539. };
  53540. self.activeEleId = function(eleId) {
  53541. if (arguments.length) {
  53542. activeEleId = eleId;
  53543. }
  53544. return activeEleId;
  53545. };
  53546. self.transitionEnd = function() {
  53547. var viewElements = $element.children();
  53548. var x, l, viewElement;
  53549. for (x = 0, l = viewElements.length; x < l; x++) {
  53550. viewElement = viewElements.eq(x);
  53551. if (viewElement.data(DATA_ELE_IDENTIFIER) === activeEleId) {
  53552. // this is the active element
  53553. navViewAttr(viewElement, VIEW_STATUS_ACTIVE);
  53554. } else if (navViewAttr(viewElement) === 'leaving' || navViewAttr(viewElement) === VIEW_STATUS_ACTIVE || navViewAttr(viewElement) === VIEW_STATUS_CACHED) {
  53555. // this is a leaving element or was the former active element, or is an cached element
  53556. if (viewElement.data(DATA_DESTROY_ELE) || viewElement.data(DATA_NO_CACHE)) {
  53557. // this element shouldn't stay cached
  53558. $ionicViewSwitcher.destroyViewEle(viewElement);
  53559. } else {
  53560. // keep in the DOM, mark as cached
  53561. navViewAttr(viewElement, VIEW_STATUS_CACHED);
  53562. // disconnect the leaving scope
  53563. ionic.Utils.disconnectScope(viewElement.scope());
  53564. }
  53565. }
  53566. }
  53567. navSwipeAttr('');
  53568. // ensure no scrolls have been left frozen
  53569. if (self.isSwipeFreeze) {
  53570. $ionicScrollDelegate.freezeAllScrolls(false);
  53571. }
  53572. };
  53573. function onTabsLeave(ev, data) {
  53574. var viewElements = $element.children();
  53575. var viewElement, viewScope;
  53576. for (var x = 0, l = viewElements.length; x < l; x++) {
  53577. viewElement = viewElements.eq(x);
  53578. if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {
  53579. viewScope = viewElement.scope();
  53580. viewScope && viewScope.$emit(ev.name.replace('Tabs', 'View'), data);
  53581. viewScope && viewScope.$broadcast(ev.name.replace('Tabs', 'ParentView'), data);
  53582. break;
  53583. }
  53584. }
  53585. }
  53586. self.cacheCleanup = function() {
  53587. var viewElements = $element.children();
  53588. for (var x = 0, l = viewElements.length; x < l; x++) {
  53589. if (viewElements.eq(x).data(DATA_DESTROY_ELE)) {
  53590. $ionicViewSwitcher.destroyViewEle(viewElements.eq(x));
  53591. }
  53592. }
  53593. };
  53594. self.clearCache = function(stateIds) {
  53595. var viewElements = $element.children();
  53596. var viewElement, viewScope, x, l, y, eleIdentifier;
  53597. for (x = 0, l = viewElements.length; x < l; x++) {
  53598. viewElement = viewElements.eq(x);
  53599. if (stateIds) {
  53600. eleIdentifier = viewElement.data(DATA_ELE_IDENTIFIER);
  53601. for (y = 0; y < stateIds.length; y++) {
  53602. if (eleIdentifier === stateIds[y]) {
  53603. $ionicViewSwitcher.destroyViewEle(viewElement);
  53604. }
  53605. }
  53606. continue;
  53607. }
  53608. if (navViewAttr(viewElement) == VIEW_STATUS_CACHED) {
  53609. $ionicViewSwitcher.destroyViewEle(viewElement);
  53610. } else if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {
  53611. viewScope = viewElement.scope();
  53612. viewScope && viewScope.$broadcast('$ionicView.clearCache');
  53613. }
  53614. }
  53615. };
  53616. self.getViewElements = function() {
  53617. return $element.children();
  53618. };
  53619. self.appendViewElement = function(viewEle, viewLocals) {
  53620. // compile the entering element and get the link function
  53621. var linkFn = $compile(viewEle);
  53622. $element.append(viewEle);
  53623. var viewScope = $scope.$new();
  53624. if (viewLocals && viewLocals.$$controller) {
  53625. viewLocals.$scope = viewScope;
  53626. var controller = $controller(viewLocals.$$controller, viewLocals);
  53627. if (viewLocals.$$controllerAs) {
  53628. viewScope[viewLocals.$$controllerAs] = controller;
  53629. }
  53630. $element.children().data('$ngControllerController', controller);
  53631. }
  53632. linkFn(viewScope);
  53633. return viewScope;
  53634. };
  53635. self.title = function(val) {
  53636. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53637. associatedNavBarCtrl && associatedNavBarCtrl.title(val);
  53638. };
  53639. /**
  53640. * @ngdoc method
  53641. * @name $ionicNavView#enableBackButton
  53642. * @description Enable/disable if the back button can be shown or not. For
  53643. * example, the very first view in the navigation stack would not have a
  53644. * back view, so the back button would be disabled.
  53645. */
  53646. self.enableBackButton = function(shouldEnable) {
  53647. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53648. associatedNavBarCtrl && associatedNavBarCtrl.enableBackButton(shouldEnable);
  53649. };
  53650. /**
  53651. * @ngdoc method
  53652. * @name $ionicNavView#showBackButton
  53653. * @description Show/hide the nav bar active back button. If the back button
  53654. * is not possible this will not force the back button to show. The
  53655. * `enableBackButton()` method handles if a back button is even possible or not.
  53656. */
  53657. self.showBackButton = function(shouldShow) {
  53658. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53659. if (associatedNavBarCtrl) {
  53660. if (arguments.length) {
  53661. return associatedNavBarCtrl.showActiveBackButton(shouldShow);
  53662. }
  53663. return associatedNavBarCtrl.showActiveBackButton();
  53664. }
  53665. return true;
  53666. };
  53667. self.showBar = function(val) {
  53668. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53669. if (associatedNavBarCtrl) {
  53670. if (arguments.length) {
  53671. return associatedNavBarCtrl.showBar(val);
  53672. }
  53673. return associatedNavBarCtrl.showBar();
  53674. }
  53675. return true;
  53676. };
  53677. self.isPrimary = function(val) {
  53678. if (arguments.length) {
  53679. isPrimary = val;
  53680. }
  53681. return isPrimary;
  53682. };
  53683. self.direction = function(val) {
  53684. if (arguments.length) {
  53685. direction = val;
  53686. }
  53687. return direction;
  53688. };
  53689. self.initSwipeBack = function() {
  53690. var swipeBackHitWidth = $ionicConfig.views.swipeBackHitWidth();
  53691. var viewTransition, associatedNavBarCtrl, backView;
  53692. var deregDragStart, deregDrag, deregRelease;
  53693. var windowWidth, startDragX, dragPoints;
  53694. var cancelData = {};
  53695. function onDragStart(ev) {
  53696. if (!isPrimary || !$ionicConfig.views.swipeBackEnabled() || $ionicSideMenuDelegate.isOpenRight() ) return;
  53697. startDragX = getDragX(ev);
  53698. if (startDragX > swipeBackHitWidth) return;
  53699. backView = $ionicHistory.backView();
  53700. var currentView = $ionicHistory.currentView();
  53701. if (!backView || backView.historyId !== currentView.historyId || currentView.canSwipeBack === false) return;
  53702. if (!windowWidth) windowWidth = window.innerWidth;
  53703. self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(true);
  53704. var registerData = {
  53705. direction: 'back'
  53706. };
  53707. dragPoints = [];
  53708. cancelData = {
  53709. showBar: self.showBar(),
  53710. showBackButton: self.showBackButton()
  53711. };
  53712. var switcher = $ionicViewSwitcher.create(self, registerData, backView, currentView, true, false);
  53713. switcher.loadViewElements(registerData);
  53714. switcher.render(registerData);
  53715. viewTransition = switcher.transition('back', $ionicHistory.enabledBack(backView), true);
  53716. associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53717. deregDrag = ionic.onGesture('drag', onDrag, $element[0]);
  53718. deregRelease = ionic.onGesture('release', onRelease, $element[0]);
  53719. }
  53720. function onDrag(ev) {
  53721. if (isPrimary && viewTransition) {
  53722. var dragX = getDragX(ev);
  53723. dragPoints.push({
  53724. t: Date.now(),
  53725. x: dragX
  53726. });
  53727. if (dragX >= windowWidth - 15) {
  53728. onRelease(ev);
  53729. } else {
  53730. var step = Math.min(Math.max(getSwipeCompletion(dragX), 0), 1);
  53731. viewTransition.run(step);
  53732. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.run(step);
  53733. }
  53734. }
  53735. }
  53736. function onRelease(ev) {
  53737. if (isPrimary && viewTransition && dragPoints && dragPoints.length > 1) {
  53738. var now = Date.now();
  53739. var releaseX = getDragX(ev);
  53740. var startDrag = dragPoints[dragPoints.length - 1];
  53741. for (var x = dragPoints.length - 2; x >= 0; x--) {
  53742. if (now - startDrag.t > 200) {
  53743. break;
  53744. }
  53745. startDrag = dragPoints[x];
  53746. }
  53747. var isSwipingRight = (releaseX >= dragPoints[dragPoints.length - 2].x);
  53748. var releaseSwipeCompletion = getSwipeCompletion(releaseX);
  53749. var velocity = Math.abs(startDrag.x - releaseX) / (now - startDrag.t);
  53750. // private variables because ui-router has no way to pass custom data using $state.go
  53751. disableRenderStartViewId = backView.viewId;
  53752. disableAnimation = (releaseSwipeCompletion < 0.03 || releaseSwipeCompletion > 0.97);
  53753. if (isSwipingRight && (releaseSwipeCompletion > 0.5 || velocity > 0.1)) {
  53754. // complete view transition on release
  53755. var speed = (velocity > 0.5 || velocity < 0.05 || releaseX > windowWidth - 45) ? 'fast' : 'slow';
  53756. navSwipeAttr(disableAnimation ? '' : speed);
  53757. backView.go();
  53758. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.complete(!disableAnimation, speed);
  53759. } else {
  53760. // cancel view transition on release
  53761. navSwipeAttr(disableAnimation ? '' : 'fast');
  53762. disableRenderStartViewId = null;
  53763. viewTransition.cancel(!disableAnimation);
  53764. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.cancel(!disableAnimation, 'fast', cancelData);
  53765. disableAnimation = null;
  53766. }
  53767. }
  53768. ionic.offGesture(deregDrag, 'drag', onDrag);
  53769. ionic.offGesture(deregRelease, 'release', onRelease);
  53770. windowWidth = viewTransition = dragPoints = null;
  53771. self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(false);
  53772. }
  53773. function getDragX(ev) {
  53774. return ionic.tap.pointerCoord(ev.gesture.srcEvent).x;
  53775. }
  53776. function getSwipeCompletion(dragX) {
  53777. return (dragX - startDragX) / windowWidth;
  53778. }
  53779. deregDragStart = ionic.onGesture('dragstart', onDragStart, $element[0]);
  53780. $scope.$on('$destroy', function() {
  53781. ionic.offGesture(deregDragStart, 'dragstart', onDragStart);
  53782. ionic.offGesture(deregDrag, 'drag', onDrag);
  53783. ionic.offGesture(deregRelease, 'release', onRelease);
  53784. self.element = viewTransition = associatedNavBarCtrl = null;
  53785. });
  53786. };
  53787. function navSwipeAttr(val) {
  53788. ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);
  53789. }
  53790. function onTabsTop(ev, isTabsTop) {
  53791. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53792. associatedNavBarCtrl && associatedNavBarCtrl.hasTabsTop(isTabsTop);
  53793. }
  53794. function onBarSubheader(ev, isBarSubheader) {
  53795. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53796. associatedNavBarCtrl && associatedNavBarCtrl.hasBarSubheader(isBarSubheader);
  53797. }
  53798. function getAssociatedNavBarCtrl() {
  53799. if (navBarDelegate) {
  53800. for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {
  53801. if ($ionicNavBarDelegate._instances[x].$$delegateHandle == navBarDelegate) {
  53802. return $ionicNavBarDelegate._instances[x];
  53803. }
  53804. }
  53805. }
  53806. return $element.inheritedData('$ionNavBarController');
  53807. }
  53808. }]);
  53809. IonicModule
  53810. .controller('$ionicRefresher', [
  53811. '$scope',
  53812. '$attrs',
  53813. '$element',
  53814. '$ionicBind',
  53815. '$timeout',
  53816. function($scope, $attrs, $element, $ionicBind, $timeout) {
  53817. var self = this,
  53818. isDragging = false,
  53819. isOverscrolling = false,
  53820. dragOffset = 0,
  53821. lastOverscroll = 0,
  53822. ptrThreshold = 60,
  53823. activated = false,
  53824. scrollTime = 500,
  53825. startY = null,
  53826. deltaY = null,
  53827. canOverscroll = true,
  53828. scrollParent,
  53829. scrollChild;
  53830. if (!isDefined($attrs.pullingIcon)) {
  53831. $attrs.$set('pullingIcon', 'ion-android-arrow-down');
  53832. }
  53833. $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';
  53834. $scope.showIcon = isDefined($attrs.refreshingIcon);
  53835. $ionicBind($scope, $attrs, {
  53836. pullingIcon: '@',
  53837. pullingText: '@',
  53838. refreshingIcon: '@',
  53839. refreshingText: '@',
  53840. spinner: '@',
  53841. disablePullingRotation: '@',
  53842. $onRefresh: '&onRefresh',
  53843. $onPulling: '&onPulling'
  53844. });
  53845. function handleMousedown(e) {
  53846. e.touches = e.touches || [{
  53847. screenX: e.screenX,
  53848. screenY: e.screenY
  53849. }];
  53850. // Mouse needs this
  53851. startY = Math.floor(e.touches[0].screenY);
  53852. }
  53853. function handleTouchstart(e) {
  53854. e.touches = e.touches || [{
  53855. screenX: e.screenX,
  53856. screenY: e.screenY
  53857. }];
  53858. startY = e.touches[0].screenY;
  53859. }
  53860. function handleTouchend() {
  53861. // reset Y
  53862. startY = null;
  53863. // if this wasn't an overscroll, get out immediately
  53864. if (!canOverscroll && !isDragging) {
  53865. return;
  53866. }
  53867. // the user has overscrolled but went back to native scrolling
  53868. if (!isDragging) {
  53869. dragOffset = 0;
  53870. isOverscrolling = false;
  53871. setScrollLock(false);
  53872. } else {
  53873. isDragging = false;
  53874. dragOffset = 0;
  53875. // the user has scroll far enough to trigger a refresh
  53876. if (lastOverscroll > ptrThreshold) {
  53877. start();
  53878. scrollTo(ptrThreshold, scrollTime);
  53879. // the user has overscrolled but not far enough to trigger a refresh
  53880. } else {
  53881. scrollTo(0, scrollTime, deactivate);
  53882. isOverscrolling = false;
  53883. }
  53884. }
  53885. }
  53886. function handleTouchmove(e) {
  53887. e.touches = e.touches || [{
  53888. screenX: e.screenX,
  53889. screenY: e.screenY
  53890. }];
  53891. // Force mouse events to have had a down event first
  53892. if (!startY && e.type == 'mousemove') {
  53893. return;
  53894. }
  53895. // if multitouch or regular scroll event, get out immediately
  53896. if (!canOverscroll || e.touches.length > 1) {
  53897. return;
  53898. }
  53899. //if this is a new drag, keep track of where we start
  53900. if (startY === null) {
  53901. startY = e.touches[0].screenY;
  53902. }
  53903. deltaY = e.touches[0].screenY - startY;
  53904. // how far have we dragged so far?
  53905. // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch
  53906. // Only do this if we're not on crosswalk
  53907. if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && !ionic.Platform.isCrosswalk() && scrollParent.scrollTop === 0 && deltaY > 0) {
  53908. isDragging = true;
  53909. e.preventDefault();
  53910. }
  53911. // if we've dragged up and back down in to native scroll territory
  53912. if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {
  53913. if (isOverscrolling) {
  53914. isOverscrolling = false;
  53915. setScrollLock(false);
  53916. }
  53917. if (isDragging) {
  53918. nativescroll(scrollParent, deltaY - dragOffset * -1);
  53919. }
  53920. // if we're not at overscroll 0 yet, 0 out
  53921. if (lastOverscroll !== 0) {
  53922. overscroll(0);
  53923. }
  53924. return;
  53925. } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {
  53926. // starting overscroll, but drag started below scrollTop 0, so we need to offset the position
  53927. dragOffset = deltaY;
  53928. }
  53929. // prevent native scroll events while overscrolling
  53930. e.preventDefault();
  53931. // if not overscrolling yet, initiate overscrolling
  53932. if (!isOverscrolling) {
  53933. isOverscrolling = true;
  53934. setScrollLock(true);
  53935. }
  53936. isDragging = true;
  53937. // overscroll according to the user's drag so far
  53938. overscroll((deltaY - dragOffset) / 3);
  53939. // update the icon accordingly
  53940. if (!activated && lastOverscroll > ptrThreshold) {
  53941. activated = true;
  53942. ionic.requestAnimationFrame(activate);
  53943. } else if (activated && lastOverscroll < ptrThreshold) {
  53944. activated = false;
  53945. ionic.requestAnimationFrame(deactivate);
  53946. }
  53947. }
  53948. function handleScroll(e) {
  53949. // canOverscrol is used to greatly simplify the drag handler during normal scrolling
  53950. canOverscroll = (e.target.scrollTop === 0) || isDragging;
  53951. }
  53952. function overscroll(val) {
  53953. scrollChild.style[ionic.CSS.TRANSFORM] = 'translate3d(0px, ' + val + 'px, 0px)';
  53954. lastOverscroll = val;
  53955. }
  53956. function nativescroll(target, newScrollTop) {
  53957. // creates a scroll event that bubbles, can be cancelled, and with its view
  53958. // and detail property initialized to window and 1, respectively
  53959. target.scrollTop = newScrollTop;
  53960. var e = document.createEvent("UIEvents");
  53961. e.initUIEvent("scroll", true, true, window, 1);
  53962. target.dispatchEvent(e);
  53963. }
  53964. function setScrollLock(enabled) {
  53965. // set the scrollbar to be position:fixed in preparation to overscroll
  53966. // or remove it so the app can be natively scrolled
  53967. if (enabled) {
  53968. ionic.requestAnimationFrame(function() {
  53969. scrollChild.classList.add('overscroll');
  53970. show();
  53971. });
  53972. } else {
  53973. ionic.requestAnimationFrame(function() {
  53974. scrollChild.classList.remove('overscroll');
  53975. hide();
  53976. deactivate();
  53977. });
  53978. }
  53979. }
  53980. $scope.$on('scroll.refreshComplete', function() {
  53981. // prevent the complete from firing before the scroll has started
  53982. $timeout(function() {
  53983. ionic.requestAnimationFrame(tail);
  53984. // scroll back to home during tail animation
  53985. scrollTo(0, scrollTime, deactivate);
  53986. // return to native scrolling after tail animation has time to finish
  53987. $timeout(function() {
  53988. if (isOverscrolling) {
  53989. isOverscrolling = false;
  53990. setScrollLock(false);
  53991. }
  53992. }, scrollTime);
  53993. }, scrollTime);
  53994. });
  53995. function scrollTo(Y, duration, callback) {
  53996. // scroll animation loop w/ easing
  53997. // credit https://gist.github.com/dezinezync/5487119
  53998. var start = Date.now(),
  53999. from = lastOverscroll;
  54000. if (from === Y) {
  54001. callback();
  54002. return; /* Prevent scrolling to the Y point if already there */
  54003. }
  54004. // decelerating to zero velocity
  54005. function easeOutCubic(t) {
  54006. return (--t) * t * t + 1;
  54007. }
  54008. // scroll loop
  54009. function scroll() {
  54010. var currentTime = Date.now(),
  54011. time = Math.min(1, ((currentTime - start) / duration)),
  54012. // where .5 would be 50% of time on a linear scale easedT gives a
  54013. // fraction based on the easing method
  54014. easedT = easeOutCubic(time);
  54015. overscroll(Math.floor((easedT * (Y - from)) + from));
  54016. if (time < 1) {
  54017. ionic.requestAnimationFrame(scroll);
  54018. } else {
  54019. if (Y < 5 && Y > -5) {
  54020. isOverscrolling = false;
  54021. setScrollLock(false);
  54022. }
  54023. callback && callback();
  54024. }
  54025. }
  54026. // start scroll loop
  54027. ionic.requestAnimationFrame(scroll);
  54028. }
  54029. var touchStartEvent, touchMoveEvent, touchEndEvent;
  54030. if (window.navigator.pointerEnabled) {
  54031. touchStartEvent = 'pointerdown';
  54032. touchMoveEvent = 'pointermove';
  54033. touchEndEvent = 'pointerup';
  54034. } else if (window.navigator.msPointerEnabled) {
  54035. touchStartEvent = 'MSPointerDown';
  54036. touchMoveEvent = 'MSPointerMove';
  54037. touchEndEvent = 'MSPointerUp';
  54038. } else {
  54039. touchStartEvent = 'touchstart';
  54040. touchMoveEvent = 'touchmove';
  54041. touchEndEvent = 'touchend';
  54042. }
  54043. self.init = function() {
  54044. scrollParent = $element.parent().parent()[0];
  54045. scrollChild = $element.parent()[0];
  54046. if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||
  54047. !scrollChild || !scrollChild.classList.contains('scroll')) {
  54048. throw new Error('Refresher must be immediate child of ion-content or ion-scroll');
  54049. }
  54050. ionic.on(touchStartEvent, handleTouchstart, scrollChild);
  54051. ionic.on(touchMoveEvent, handleTouchmove, scrollChild);
  54052. ionic.on(touchEndEvent, handleTouchend, scrollChild);
  54053. ionic.on('mousedown', handleMousedown, scrollChild);
  54054. ionic.on('mousemove', handleTouchmove, scrollChild);
  54055. ionic.on('mouseup', handleTouchend, scrollChild);
  54056. ionic.on('scroll', handleScroll, scrollParent);
  54057. // cleanup when done
  54058. $scope.$on('$destroy', destroy);
  54059. };
  54060. function destroy() {
  54061. if ( scrollChild ) {
  54062. ionic.off(touchStartEvent, handleTouchstart, scrollChild);
  54063. ionic.off(touchMoveEvent, handleTouchmove, scrollChild);
  54064. ionic.off(touchEndEvent, handleTouchend, scrollChild);
  54065. ionic.off('mousedown', handleMousedown, scrollChild);
  54066. ionic.off('mousemove', handleTouchmove, scrollChild);
  54067. ionic.off('mouseup', handleTouchend, scrollChild);
  54068. }
  54069. if ( scrollParent ) {
  54070. ionic.off('scroll', handleScroll, scrollParent);
  54071. }
  54072. scrollParent = null;
  54073. scrollChild = null;
  54074. }
  54075. // DOM manipulation and broadcast methods shared by JS and Native Scrolling
  54076. // getter used by JS Scrolling
  54077. self.getRefresherDomMethods = function() {
  54078. return {
  54079. activate: activate,
  54080. deactivate: deactivate,
  54081. start: start,
  54082. show: show,
  54083. hide: hide,
  54084. tail: tail
  54085. };
  54086. };
  54087. function activate() {
  54088. $element[0].classList.add('active');
  54089. $scope.$onPulling();
  54090. }
  54091. function deactivate() {
  54092. // give tail 150ms to finish
  54093. $timeout(function() {
  54094. // deactivateCallback
  54095. $element.removeClass('active refreshing refreshing-tail');
  54096. if (activated) activated = false;
  54097. }, 150);
  54098. }
  54099. function start() {
  54100. // startCallback
  54101. $element[0].classList.add('refreshing');
  54102. var q = $scope.$onRefresh();
  54103. if (q && q.then) {
  54104. q['finally'](function() {
  54105. $scope.$broadcast('scroll.refreshComplete');
  54106. });
  54107. }
  54108. }
  54109. function show() {
  54110. // showCallback
  54111. $element[0].classList.remove('invisible');
  54112. }
  54113. function hide() {
  54114. // showCallback
  54115. $element[0].classList.add('invisible');
  54116. }
  54117. function tail() {
  54118. // tailCallback
  54119. $element[0].classList.add('refreshing-tail');
  54120. }
  54121. // for testing
  54122. self.__handleTouchmove = handleTouchmove;
  54123. self.__getScrollChild = function() { return scrollChild; };
  54124. self.__getScrollParent = function() { return scrollParent; };
  54125. }
  54126. ]);
  54127. /**
  54128. * @private
  54129. */
  54130. IonicModule
  54131. .controller('$ionicScroll', [
  54132. '$scope',
  54133. 'scrollViewOptions',
  54134. '$timeout',
  54135. '$window',
  54136. '$location',
  54137. '$document',
  54138. '$ionicScrollDelegate',
  54139. '$ionicHistory',
  54140. function($scope,
  54141. scrollViewOptions,
  54142. $timeout,
  54143. $window,
  54144. $location,
  54145. $document,
  54146. $ionicScrollDelegate,
  54147. $ionicHistory) {
  54148. var self = this;
  54149. // for testing
  54150. self.__timeout = $timeout;
  54151. self._scrollViewOptions = scrollViewOptions; //for testing
  54152. self.isNative = function() {
  54153. return !!scrollViewOptions.nativeScrolling;
  54154. };
  54155. var element = self.element = scrollViewOptions.el;
  54156. var $element = self.$element = jqLite(element);
  54157. var scrollView;
  54158. if (self.isNative()) {
  54159. scrollView = self.scrollView = new ionic.views.ScrollNative(scrollViewOptions);
  54160. } else {
  54161. scrollView = self.scrollView = new ionic.views.Scroll(scrollViewOptions);
  54162. }
  54163. //Attach self to element as a controller so other directives can require this controller
  54164. //through `require: '$ionicScroll'
  54165. //Also attach to parent so that sibling elements can require this
  54166. ($element.parent().length ? $element.parent() : $element)
  54167. .data('$$ionicScrollController', self);
  54168. var deregisterInstance = $ionicScrollDelegate._registerInstance(
  54169. self, scrollViewOptions.delegateHandle, function() {
  54170. return $ionicHistory.isActiveScope($scope);
  54171. }
  54172. );
  54173. if (!isDefined(scrollViewOptions.bouncing)) {
  54174. ionic.Platform.ready(function() {
  54175. if (scrollView && scrollView.options) {
  54176. scrollView.options.bouncing = true;
  54177. if (ionic.Platform.isAndroid()) {
  54178. // No bouncing by default on Android
  54179. scrollView.options.bouncing = false;
  54180. // Faster scroll decel
  54181. scrollView.options.deceleration = 0.95;
  54182. }
  54183. }
  54184. });
  54185. }
  54186. var resize = angular.bind(scrollView, scrollView.resize);
  54187. angular.element($window).on('resize', resize);
  54188. var scrollFunc = function(e) {
  54189. var detail = (e.originalEvent || e).detail || {};
  54190. $scope.$onScroll && $scope.$onScroll({
  54191. event: e,
  54192. scrollTop: detail.scrollTop || 0,
  54193. scrollLeft: detail.scrollLeft || 0
  54194. });
  54195. };
  54196. $element.on('scroll', scrollFunc);
  54197. $scope.$on('$destroy', function() {
  54198. deregisterInstance();
  54199. scrollView && scrollView.__cleanup && scrollView.__cleanup();
  54200. angular.element($window).off('resize', resize);
  54201. if ( $element ) {
  54202. $element.off('scroll', scrollFunc);
  54203. }
  54204. if ( self._scrollViewOptions ) {
  54205. self._scrollViewOptions.el = null;
  54206. }
  54207. if ( scrollViewOptions ) {
  54208. scrollViewOptions.el = null;
  54209. }
  54210. scrollView = self.scrollView = scrollViewOptions = self._scrollViewOptions = element = self.$element = $element = null;
  54211. });
  54212. $timeout(function() {
  54213. scrollView && scrollView.run && scrollView.run();
  54214. });
  54215. self.getScrollView = function() {
  54216. return scrollView;
  54217. };
  54218. self.getScrollPosition = function() {
  54219. return scrollView.getValues();
  54220. };
  54221. self.resize = function() {
  54222. return $timeout(resize, 0, false).then(function() {
  54223. $element && $element.triggerHandler('scroll-resize');
  54224. });
  54225. };
  54226. self.scrollTop = function(shouldAnimate) {
  54227. self.resize().then(function() {
  54228. if (!scrollView) {
  54229. return;
  54230. }
  54231. scrollView.scrollTo(0, 0, !!shouldAnimate);
  54232. });
  54233. };
  54234. self.scrollBottom = function(shouldAnimate) {
  54235. self.resize().then(function() {
  54236. if (!scrollView) {
  54237. return;
  54238. }
  54239. var max = scrollView.getScrollMax();
  54240. scrollView.scrollTo(max.left, max.top, !!shouldAnimate);
  54241. });
  54242. };
  54243. self.scrollTo = function(left, top, shouldAnimate) {
  54244. self.resize().then(function() {
  54245. if (!scrollView) {
  54246. return;
  54247. }
  54248. scrollView.scrollTo(left, top, !!shouldAnimate);
  54249. });
  54250. };
  54251. self.zoomTo = function(zoom, shouldAnimate, originLeft, originTop) {
  54252. self.resize().then(function() {
  54253. if (!scrollView) {
  54254. return;
  54255. }
  54256. scrollView.zoomTo(zoom, !!shouldAnimate, originLeft, originTop);
  54257. });
  54258. };
  54259. self.zoomBy = function(zoom, shouldAnimate, originLeft, originTop) {
  54260. self.resize().then(function() {
  54261. if (!scrollView) {
  54262. return;
  54263. }
  54264. scrollView.zoomBy(zoom, !!shouldAnimate, originLeft, originTop);
  54265. });
  54266. };
  54267. self.scrollBy = function(left, top, shouldAnimate) {
  54268. self.resize().then(function() {
  54269. if (!scrollView) {
  54270. return;
  54271. }
  54272. scrollView.scrollBy(left, top, !!shouldAnimate);
  54273. });
  54274. };
  54275. self.anchorScroll = function(shouldAnimate) {
  54276. self.resize().then(function() {
  54277. if (!scrollView) {
  54278. return;
  54279. }
  54280. var hash = $location.hash();
  54281. var elm = hash && $document[0].getElementById(hash);
  54282. if (!(hash && elm)) {
  54283. scrollView.scrollTo(0, 0, !!shouldAnimate);
  54284. return;
  54285. }
  54286. var curElm = elm;
  54287. var scrollLeft = 0, scrollTop = 0;
  54288. do {
  54289. if (curElm !== null) scrollLeft += curElm.offsetLeft;
  54290. if (curElm !== null) scrollTop += curElm.offsetTop;
  54291. curElm = curElm.offsetParent;
  54292. } while (curElm.attributes != self.element.attributes && curElm.offsetParent);
  54293. scrollView.scrollTo(scrollLeft, scrollTop, !!shouldAnimate);
  54294. });
  54295. };
  54296. self.freezeScroll = scrollView.freeze;
  54297. self.freezeScrollShut = scrollView.freezeShut;
  54298. self.freezeAllScrolls = function(shouldFreeze) {
  54299. for (var i = 0; i < $ionicScrollDelegate._instances.length; i++) {
  54300. $ionicScrollDelegate._instances[i].freezeScroll(shouldFreeze);
  54301. }
  54302. };
  54303. /**
  54304. * @private
  54305. */
  54306. self._setRefresher = function(refresherScope, refresherElement, refresherMethods) {
  54307. self.refresher = refresherElement;
  54308. var refresherHeight = self.refresher.clientHeight || 60;
  54309. scrollView.activatePullToRefresh(
  54310. refresherHeight,
  54311. refresherMethods
  54312. );
  54313. };
  54314. }]);
  54315. IonicModule
  54316. .controller('$ionicSideMenus', [
  54317. '$scope',
  54318. '$attrs',
  54319. '$ionicSideMenuDelegate',
  54320. '$ionicPlatform',
  54321. '$ionicBody',
  54322. '$ionicHistory',
  54323. '$ionicScrollDelegate',
  54324. 'IONIC_BACK_PRIORITY',
  54325. '$rootScope',
  54326. function($scope, $attrs, $ionicSideMenuDelegate, $ionicPlatform, $ionicBody, $ionicHistory, $ionicScrollDelegate, IONIC_BACK_PRIORITY, $rootScope) {
  54327. var self = this;
  54328. var rightShowing, leftShowing, isDragging;
  54329. var startX, lastX, offsetX, isAsideExposed;
  54330. var enableMenuWithBackViews = true;
  54331. self.$scope = $scope;
  54332. self.initialize = function(options) {
  54333. self.left = options.left;
  54334. self.right = options.right;
  54335. self.setContent(options.content);
  54336. self.dragThresholdX = options.dragThresholdX || 10;
  54337. $ionicHistory.registerHistory(self.$scope);
  54338. };
  54339. /**
  54340. * Set the content view controller if not passed in the constructor options.
  54341. *
  54342. * @param {object} content
  54343. */
  54344. self.setContent = function(content) {
  54345. if (content) {
  54346. self.content = content;
  54347. self.content.onDrag = function(e) {
  54348. self._handleDrag(e);
  54349. };
  54350. self.content.endDrag = function(e) {
  54351. self._endDrag(e);
  54352. };
  54353. }
  54354. };
  54355. self.isOpenLeft = function() {
  54356. return self.getOpenAmount() > 0;
  54357. };
  54358. self.isOpenRight = function() {
  54359. return self.getOpenAmount() < 0;
  54360. };
  54361. /**
  54362. * Toggle the left menu to open 100%
  54363. */
  54364. self.toggleLeft = function(shouldOpen) {
  54365. if (isAsideExposed || !self.left.isEnabled) return;
  54366. var openAmount = self.getOpenAmount();
  54367. if (arguments.length === 0) {
  54368. shouldOpen = openAmount <= 0;
  54369. }
  54370. self.content.enableAnimation();
  54371. if (!shouldOpen) {
  54372. self.openPercentage(0);
  54373. $rootScope.$emit('$ionicSideMenuClose', 'left');
  54374. } else {
  54375. self.openPercentage(100);
  54376. $rootScope.$emit('$ionicSideMenuOpen', 'left');
  54377. }
  54378. };
  54379. /**
  54380. * Toggle the right menu to open 100%
  54381. */
  54382. self.toggleRight = function(shouldOpen) {
  54383. if (isAsideExposed || !self.right.isEnabled) return;
  54384. var openAmount = self.getOpenAmount();
  54385. if (arguments.length === 0) {
  54386. shouldOpen = openAmount >= 0;
  54387. }
  54388. self.content.enableAnimation();
  54389. if (!shouldOpen) {
  54390. self.openPercentage(0);
  54391. $rootScope.$emit('$ionicSideMenuClose', 'right');
  54392. } else {
  54393. self.openPercentage(-100);
  54394. $rootScope.$emit('$ionicSideMenuOpen', 'right');
  54395. }
  54396. };
  54397. self.toggle = function(side) {
  54398. if (side == 'right') {
  54399. self.toggleRight();
  54400. } else {
  54401. self.toggleLeft();
  54402. }
  54403. };
  54404. /**
  54405. * Close all menus.
  54406. */
  54407. self.close = function() {
  54408. self.openPercentage(0);
  54409. $rootScope.$emit('$ionicSideMenuClose', 'left');
  54410. $rootScope.$emit('$ionicSideMenuClose', 'right');
  54411. };
  54412. /**
  54413. * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)
  54414. */
  54415. self.getOpenAmount = function() {
  54416. return self.content && self.content.getTranslateX() || 0;
  54417. };
  54418. /**
  54419. * @return {float} The ratio of open amount over menu width. For example, a
  54420. * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative
  54421. * for right menu.
  54422. */
  54423. self.getOpenRatio = function() {
  54424. var amount = self.getOpenAmount();
  54425. if (amount >= 0) {
  54426. return amount / self.left.width;
  54427. }
  54428. return amount / self.right.width;
  54429. };
  54430. self.isOpen = function() {
  54431. return self.getOpenAmount() !== 0;
  54432. };
  54433. /**
  54434. * @return {float} The percentage of open amount over menu width. For example, a
  54435. * menu of width 100 open 50 pixels would be open 50%. Value is negative
  54436. * for right menu.
  54437. */
  54438. self.getOpenPercentage = function() {
  54439. return self.getOpenRatio() * 100;
  54440. };
  54441. /**
  54442. * Open the menu with a given percentage amount.
  54443. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu.
  54444. */
  54445. self.openPercentage = function(percentage) {
  54446. var p = percentage / 100;
  54447. if (self.left && percentage >= 0) {
  54448. self.openAmount(self.left.width * p);
  54449. } else if (self.right && percentage < 0) {
  54450. self.openAmount(self.right.width * p);
  54451. }
  54452. // add the CSS class "menu-open" if the percentage does not
  54453. // equal 0, otherwise remove the class from the body element
  54454. $ionicBody.enableClass((percentage !== 0), 'menu-open');
  54455. self.content.setCanScroll(percentage == 0);
  54456. };
  54457. /*
  54458. function freezeAllScrolls(shouldFreeze) {
  54459. if (shouldFreeze && !self.isScrollFreeze) {
  54460. $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);
  54461. } else if (!shouldFreeze && self.isScrollFreeze) {
  54462. $ionicScrollDelegate.freezeAllScrolls(false);
  54463. }
  54464. self.isScrollFreeze = shouldFreeze;
  54465. }
  54466. */
  54467. /**
  54468. * Open the menu the given pixel amount.
  54469. * @param {float} amount the pixel amount to open the menu. Positive value for left menu,
  54470. * negative value for right menu (only one menu will be visible at a time).
  54471. */
  54472. self.openAmount = function(amount) {
  54473. var maxLeft = self.left && self.left.width || 0;
  54474. var maxRight = self.right && self.right.width || 0;
  54475. // Check if we can move to that side, depending if the left/right panel is enabled
  54476. if (!(self.left && self.left.isEnabled) && amount > 0) {
  54477. self.content.setTranslateX(0);
  54478. return;
  54479. }
  54480. if (!(self.right && self.right.isEnabled) && amount < 0) {
  54481. self.content.setTranslateX(0);
  54482. return;
  54483. }
  54484. if (leftShowing && amount > maxLeft) {
  54485. self.content.setTranslateX(maxLeft);
  54486. return;
  54487. }
  54488. if (rightShowing && amount < -maxRight) {
  54489. self.content.setTranslateX(-maxRight);
  54490. return;
  54491. }
  54492. self.content.setTranslateX(amount);
  54493. if (amount >= 0) {
  54494. leftShowing = true;
  54495. rightShowing = false;
  54496. if (amount > 0) {
  54497. // Push the z-index of the right menu down
  54498. self.right && self.right.pushDown && self.right.pushDown();
  54499. // Bring the z-index of the left menu up
  54500. self.left && self.left.bringUp && self.left.bringUp();
  54501. }
  54502. } else {
  54503. rightShowing = true;
  54504. leftShowing = false;
  54505. // Bring the z-index of the right menu up
  54506. self.right && self.right.bringUp && self.right.bringUp();
  54507. // Push the z-index of the left menu down
  54508. self.left && self.left.pushDown && self.left.pushDown();
  54509. }
  54510. };
  54511. /**
  54512. * Given an event object, find the final resting position of this side
  54513. * menu. For example, if the user "throws" the content to the right and
  54514. * releases the touch, the left menu should snap open (animated, of course).
  54515. *
  54516. * @param {Event} e the gesture event to use for snapping
  54517. */
  54518. self.snapToRest = function(e) {
  54519. // We want to animate at the end of this
  54520. self.content.enableAnimation();
  54521. isDragging = false;
  54522. // Check how much the panel is open after the drag, and
  54523. // what the drag velocity is
  54524. var ratio = self.getOpenRatio();
  54525. if (ratio === 0) {
  54526. // Just to be safe
  54527. self.openPercentage(0);
  54528. return;
  54529. }
  54530. var velocityThreshold = 0.3;
  54531. var velocityX = e.gesture.velocityX;
  54532. var direction = e.gesture.direction;
  54533. // Going right, less than half, too slow (snap back)
  54534. if (ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
  54535. self.openPercentage(0);
  54536. }
  54537. // Going left, more than half, too slow (snap back)
  54538. else if (ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {
  54539. self.openPercentage(100);
  54540. }
  54541. // Going left, less than half, too slow (snap back)
  54542. else if (ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {
  54543. self.openPercentage(0);
  54544. }
  54545. // Going right, more than half, too slow (snap back)
  54546. else if (ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
  54547. self.openPercentage(-100);
  54548. }
  54549. // Going right, more than half, or quickly (snap open)
  54550. else if (direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {
  54551. self.openPercentage(100);
  54552. }
  54553. // Going left, more than half, or quickly (span open)
  54554. else if (direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {
  54555. self.openPercentage(-100);
  54556. }
  54557. // Snap back for safety
  54558. else {
  54559. self.openPercentage(0);
  54560. }
  54561. };
  54562. self.enableMenuWithBackViews = function(val) {
  54563. if (arguments.length) {
  54564. enableMenuWithBackViews = !!val;
  54565. }
  54566. return enableMenuWithBackViews;
  54567. };
  54568. self.isAsideExposed = function() {
  54569. return !!isAsideExposed;
  54570. };
  54571. self.exposeAside = function(shouldExposeAside) {
  54572. if (!(self.left && self.left.isEnabled) && !(self.right && self.right.isEnabled)) return;
  54573. self.close();
  54574. isAsideExposed = shouldExposeAside;
  54575. if ((self.left && self.left.isEnabled) && (self.right && self.right.isEnabled)) {
  54576. self.content.setMarginLeftAndRight(isAsideExposed ? self.left.width : 0, isAsideExposed ? self.right.width : 0);
  54577. } else if (self.left && self.left.isEnabled) {
  54578. // set the left marget width if it should be exposed
  54579. // otherwise set false so there's no left margin
  54580. self.content.setMarginLeft(isAsideExposed ? self.left.width : 0);
  54581. } else if (self.right && self.right.isEnabled) {
  54582. self.content.setMarginRight(isAsideExposed ? self.right.width : 0);
  54583. }
  54584. self.$scope.$emit('$ionicExposeAside', isAsideExposed);
  54585. };
  54586. self.activeAsideResizing = function(isResizing) {
  54587. $ionicBody.enableClass(isResizing, 'aside-resizing');
  54588. };
  54589. // End a drag with the given event
  54590. self._endDrag = function(e) {
  54591. if (isAsideExposed) return;
  54592. if (isDragging) {
  54593. self.snapToRest(e);
  54594. }
  54595. startX = null;
  54596. lastX = null;
  54597. offsetX = null;
  54598. };
  54599. // Handle a drag event
  54600. self._handleDrag = function(e) {
  54601. if (isAsideExposed || !$scope.dragContent) return;
  54602. // If we don't have start coords, grab and store them
  54603. if (!startX) {
  54604. startX = e.gesture.touches[0].pageX;
  54605. lastX = startX;
  54606. } else {
  54607. // Grab the current tap coords
  54608. lastX = e.gesture.touches[0].pageX;
  54609. }
  54610. // Calculate difference from the tap points
  54611. if (!isDragging && Math.abs(lastX - startX) > self.dragThresholdX) {
  54612. // if the difference is greater than threshold, start dragging using the current
  54613. // point as the starting point
  54614. startX = lastX;
  54615. isDragging = true;
  54616. // Initialize dragging
  54617. self.content.disableAnimation();
  54618. offsetX = self.getOpenAmount();
  54619. }
  54620. if (isDragging) {
  54621. self.openAmount(offsetX + (lastX - startX));
  54622. //self.content.setCanScroll(false);
  54623. }
  54624. };
  54625. self.canDragContent = function(canDrag) {
  54626. if (arguments.length) {
  54627. $scope.dragContent = !!canDrag;
  54628. }
  54629. return $scope.dragContent;
  54630. };
  54631. self.edgeThreshold = 25;
  54632. self.edgeThresholdEnabled = false;
  54633. self.edgeDragThreshold = function(value) {
  54634. if (arguments.length) {
  54635. if (isNumber(value) && value > 0) {
  54636. self.edgeThreshold = value;
  54637. self.edgeThresholdEnabled = true;
  54638. } else {
  54639. self.edgeThresholdEnabled = !!value;
  54640. }
  54641. }
  54642. return self.edgeThresholdEnabled;
  54643. };
  54644. self.isDraggableTarget = function(e) {
  54645. //Only restrict edge when sidemenu is closed and restriction is enabled
  54646. var shouldOnlyAllowEdgeDrag = self.edgeThresholdEnabled && !self.isOpen();
  54647. var startX = e.gesture.startEvent && e.gesture.startEvent.center &&
  54648. e.gesture.startEvent.center.pageX;
  54649. var dragIsWithinBounds = !shouldOnlyAllowEdgeDrag ||
  54650. startX <= self.edgeThreshold ||
  54651. startX >= self.content.element.offsetWidth - self.edgeThreshold;
  54652. var backView = $ionicHistory.backView();
  54653. var menuEnabled = enableMenuWithBackViews ? true : !backView;
  54654. if (!menuEnabled) {
  54655. var currentView = $ionicHistory.currentView() || {};
  54656. return (dragIsWithinBounds && (backView.historyId !== currentView.historyId));
  54657. }
  54658. return ($scope.dragContent || self.isOpen()) &&
  54659. dragIsWithinBounds &&
  54660. !e.gesture.srcEvent.defaultPrevented &&
  54661. menuEnabled &&
  54662. !e.target.tagName.match(/input|textarea|select|object|embed/i) &&
  54663. !e.target.isContentEditable &&
  54664. !(e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll') == 'true');
  54665. };
  54666. $scope.sideMenuContentTranslateX = 0;
  54667. var deregisterBackButtonAction = noop;
  54668. var closeSideMenu = angular.bind(self, self.close);
  54669. $scope.$watch(function() {
  54670. return self.getOpenAmount() !== 0;
  54671. }, function(isOpen) {
  54672. deregisterBackButtonAction();
  54673. if (isOpen) {
  54674. deregisterBackButtonAction = $ionicPlatform.registerBackButtonAction(
  54675. closeSideMenu,
  54676. IONIC_BACK_PRIORITY.sideMenu
  54677. );
  54678. }
  54679. });
  54680. var deregisterInstance = $ionicSideMenuDelegate._registerInstance(
  54681. self, $attrs.delegateHandle, function() {
  54682. return $ionicHistory.isActiveScope($scope);
  54683. }
  54684. );
  54685. $scope.$on('$destroy', function() {
  54686. deregisterInstance();
  54687. deregisterBackButtonAction();
  54688. self.$scope = null;
  54689. if (self.content) {
  54690. self.content.setCanScroll(true);
  54691. self.content.element = null;
  54692. self.content = null;
  54693. }
  54694. });
  54695. self.initialize({
  54696. left: {
  54697. width: 275
  54698. },
  54699. right: {
  54700. width: 275
  54701. }
  54702. });
  54703. }]);
  54704. (function(ionic) {
  54705. var TRANSLATE32 = 'translate(32,32)';
  54706. var STROKE_OPACITY = 'stroke-opacity';
  54707. var ROUND = 'round';
  54708. var INDEFINITE = 'indefinite';
  54709. var DURATION = '750ms';
  54710. var NONE = 'none';
  54711. var SHORTCUTS = {
  54712. a: 'animate',
  54713. an: 'attributeName',
  54714. at: 'animateTransform',
  54715. c: 'circle',
  54716. da: 'stroke-dasharray',
  54717. os: 'stroke-dashoffset',
  54718. f: 'fill',
  54719. lc: 'stroke-linecap',
  54720. rc: 'repeatCount',
  54721. sw: 'stroke-width',
  54722. t: 'transform',
  54723. v: 'values'
  54724. };
  54725. var SPIN_ANIMATION = {
  54726. v: '0,32,32;360,32,32',
  54727. an: 'transform',
  54728. type: 'rotate',
  54729. rc: INDEFINITE,
  54730. dur: DURATION
  54731. };
  54732. function createSvgElement(tagName, data, parent, spinnerName) {
  54733. var ele = document.createElement(SHORTCUTS[tagName] || tagName);
  54734. var k, x, y;
  54735. for (k in data) {
  54736. if (angular.isArray(data[k])) {
  54737. for (x = 0; x < data[k].length; x++) {
  54738. if (data[k][x].fn) {
  54739. for (y = 0; y < data[k][x].t; y++) {
  54740. createSvgElement(k, data[k][x].fn(y, spinnerName), ele, spinnerName);
  54741. }
  54742. } else {
  54743. createSvgElement(k, data[k][x], ele, spinnerName);
  54744. }
  54745. }
  54746. } else {
  54747. setSvgAttribute(ele, k, data[k]);
  54748. }
  54749. }
  54750. parent.appendChild(ele);
  54751. }
  54752. function setSvgAttribute(ele, k, v) {
  54753. ele.setAttribute(SHORTCUTS[k] || k, v);
  54754. }
  54755. function animationValues(strValues, i) {
  54756. var values = strValues.split(';');
  54757. var back = values.slice(i);
  54758. var front = values.slice(0, values.length - back.length);
  54759. values = back.concat(front).reverse();
  54760. return values.join(';') + ';' + values[0];
  54761. }
  54762. var IOS_SPINNER = {
  54763. sw: 4,
  54764. lc: ROUND,
  54765. line: [{
  54766. fn: function(i, spinnerName) {
  54767. return {
  54768. y1: spinnerName == 'ios' ? 17 : 12,
  54769. y2: spinnerName == 'ios' ? 29 : 20,
  54770. t: TRANSLATE32 + ' rotate(' + (30 * i + (i < 6 ? 180 : -180)) + ')',
  54771. a: [{
  54772. fn: function() {
  54773. return {
  54774. an: STROKE_OPACITY,
  54775. dur: DURATION,
  54776. v: animationValues('0;.1;.15;.25;.35;.45;.55;.65;.7;.85;1', i),
  54777. rc: INDEFINITE
  54778. };
  54779. },
  54780. t: 1
  54781. }]
  54782. };
  54783. },
  54784. t: 12
  54785. }]
  54786. };
  54787. var spinners = {
  54788. android: {
  54789. c: [{
  54790. sw: 6,
  54791. da: 128,
  54792. os: 82,
  54793. r: 26,
  54794. cx: 32,
  54795. cy: 32,
  54796. f: NONE
  54797. }]
  54798. },
  54799. ios: IOS_SPINNER,
  54800. 'ios-small': IOS_SPINNER,
  54801. bubbles: {
  54802. sw: 0,
  54803. c: [{
  54804. fn: function(i) {
  54805. return {
  54806. cx: 24 * Math.cos(2 * Math.PI * i / 8),
  54807. cy: 24 * Math.sin(2 * Math.PI * i / 8),
  54808. t: TRANSLATE32,
  54809. a: [{
  54810. fn: function() {
  54811. return {
  54812. an: 'r',
  54813. dur: DURATION,
  54814. v: animationValues('1;2;3;4;5;6;7;8', i),
  54815. rc: INDEFINITE
  54816. };
  54817. },
  54818. t: 1
  54819. }]
  54820. };
  54821. },
  54822. t: 8
  54823. }]
  54824. },
  54825. circles: {
  54826. c: [{
  54827. fn: function(i) {
  54828. return {
  54829. r: 5,
  54830. cx: 24 * Math.cos(2 * Math.PI * i / 8),
  54831. cy: 24 * Math.sin(2 * Math.PI * i / 8),
  54832. t: TRANSLATE32,
  54833. sw: 0,
  54834. a: [{
  54835. fn: function() {
  54836. return {
  54837. an: 'fill-opacity',
  54838. dur: DURATION,
  54839. v: animationValues('.3;.3;.3;.4;.7;.85;.9;1', i),
  54840. rc: INDEFINITE
  54841. };
  54842. },
  54843. t: 1
  54844. }]
  54845. };
  54846. },
  54847. t: 8
  54848. }]
  54849. },
  54850. crescent: {
  54851. c: [{
  54852. sw: 4,
  54853. da: 128,
  54854. os: 82,
  54855. r: 26,
  54856. cx: 32,
  54857. cy: 32,
  54858. f: NONE,
  54859. at: [SPIN_ANIMATION]
  54860. }]
  54861. },
  54862. dots: {
  54863. c: [{
  54864. fn: function(i) {
  54865. return {
  54866. cx: 16 + (16 * i),
  54867. cy: 32,
  54868. sw: 0,
  54869. a: [{
  54870. fn: function() {
  54871. return {
  54872. an: 'fill-opacity',
  54873. dur: DURATION,
  54874. v: animationValues('.5;.6;.8;1;.8;.6;.5', i),
  54875. rc: INDEFINITE
  54876. };
  54877. },
  54878. t: 1
  54879. }, {
  54880. fn: function() {
  54881. return {
  54882. an: 'r',
  54883. dur: DURATION,
  54884. v: animationValues('4;5;6;5;4;3;3', i),
  54885. rc: INDEFINITE
  54886. };
  54887. },
  54888. t: 1
  54889. }]
  54890. };
  54891. },
  54892. t: 3
  54893. }]
  54894. },
  54895. lines: {
  54896. sw: 7,
  54897. lc: ROUND,
  54898. line: [{
  54899. fn: function(i) {
  54900. return {
  54901. x1: 10 + (i * 14),
  54902. x2: 10 + (i * 14),
  54903. a: [{
  54904. fn: function() {
  54905. return {
  54906. an: 'y1',
  54907. dur: DURATION,
  54908. v: animationValues('16;18;28;18;16', i),
  54909. rc: INDEFINITE
  54910. };
  54911. },
  54912. t: 1
  54913. }, {
  54914. fn: function() {
  54915. return {
  54916. an: 'y2',
  54917. dur: DURATION,
  54918. v: animationValues('48;44;36;46;48', i),
  54919. rc: INDEFINITE
  54920. };
  54921. },
  54922. t: 1
  54923. }, {
  54924. fn: function() {
  54925. return {
  54926. an: STROKE_OPACITY,
  54927. dur: DURATION,
  54928. v: animationValues('1;.8;.5;.4;1', i),
  54929. rc: INDEFINITE
  54930. };
  54931. },
  54932. t: 1
  54933. }]
  54934. };
  54935. },
  54936. t: 4
  54937. }]
  54938. },
  54939. ripple: {
  54940. f: NONE,
  54941. 'fill-rule': 'evenodd',
  54942. sw: 3,
  54943. circle: [{
  54944. fn: function(i) {
  54945. return {
  54946. cx: 32,
  54947. cy: 32,
  54948. a: [{
  54949. fn: function() {
  54950. return {
  54951. an: 'r',
  54952. begin: (i * -1) + 's',
  54953. dur: '2s',
  54954. v: '0;24',
  54955. keyTimes: '0;1',
  54956. keySplines: '0.1,0.2,0.3,1',
  54957. calcMode: 'spline',
  54958. rc: INDEFINITE
  54959. };
  54960. },
  54961. t: 1
  54962. }, {
  54963. fn: function() {
  54964. return {
  54965. an: STROKE_OPACITY,
  54966. begin: (i * -1) + 's',
  54967. dur: '2s',
  54968. v: '.2;1;.2;0',
  54969. rc: INDEFINITE
  54970. };
  54971. },
  54972. t: 1
  54973. }]
  54974. };
  54975. },
  54976. t: 2
  54977. }]
  54978. },
  54979. spiral: {
  54980. defs: [{
  54981. linearGradient: [{
  54982. id: 'sGD',
  54983. gradientUnits: 'userSpaceOnUse',
  54984. x1: 55, y1: 46, x2: 2, y2: 46,
  54985. stop: [{
  54986. offset: 0.1,
  54987. class: 'stop1'
  54988. }, {
  54989. offset: 1,
  54990. class: 'stop2'
  54991. }]
  54992. }]
  54993. }],
  54994. g: [{
  54995. sw: 4,
  54996. lc: ROUND,
  54997. f: NONE,
  54998. path: [{
  54999. stroke: 'url(#sGD)',
  55000. d: 'M4,32 c0,15,12,28,28,28c8,0,16-4,21-9'
  55001. }, {
  55002. d: 'M60,32 C60,16,47.464,4,32,4S4,16,4,32'
  55003. }],
  55004. at: [SPIN_ANIMATION]
  55005. }]
  55006. }
  55007. };
  55008. var animations = {
  55009. android: function(ele) {
  55010. // Note that this is called as a function, not a constructor.
  55011. var self = {};
  55012. this.stop = false;
  55013. var rIndex = 0;
  55014. var rotateCircle = 0;
  55015. var startTime;
  55016. var svgEle = ele.querySelector('g');
  55017. var circleEle = ele.querySelector('circle');
  55018. function run() {
  55019. if (self.stop) return;
  55020. var v = easeInOutCubic(Date.now() - startTime, 650);
  55021. var scaleX = 1;
  55022. var translateX = 0;
  55023. var dasharray = (188 - (58 * v));
  55024. var dashoffset = (182 - (182 * v));
  55025. if (rIndex % 2) {
  55026. scaleX = -1;
  55027. translateX = -64;
  55028. dasharray = (128 - (-58 * v));
  55029. dashoffset = (182 * v);
  55030. }
  55031. var rotateLine = [0, -101, -90, -11, -180, 79, -270, -191][rIndex];
  55032. setSvgAttribute(circleEle, 'da', Math.max(Math.min(dasharray, 188), 128));
  55033. setSvgAttribute(circleEle, 'os', Math.max(Math.min(dashoffset, 182), 0));
  55034. setSvgAttribute(circleEle, 't', 'scale(' + scaleX + ',1) translate(' + translateX + ',0) rotate(' + rotateLine + ',32,32)');
  55035. rotateCircle += 4.1;
  55036. if (rotateCircle > 359) rotateCircle = 0;
  55037. setSvgAttribute(svgEle, 't', 'rotate(' + rotateCircle + ',32,32)');
  55038. if (v >= 1) {
  55039. rIndex++;
  55040. if (rIndex > 7) rIndex = 0;
  55041. startTime = Date.now();
  55042. }
  55043. ionic.requestAnimationFrame(run);
  55044. }
  55045. return function() {
  55046. startTime = Date.now();
  55047. run();
  55048. return self;
  55049. };
  55050. }
  55051. };
  55052. function easeInOutCubic(t, c) {
  55053. t /= c / 2;
  55054. if (t < 1) return 1 / 2 * t * t * t;
  55055. t -= 2;
  55056. return 1 / 2 * (t * t * t + 2);
  55057. }
  55058. IonicModule
  55059. .controller('$ionicSpinner', [
  55060. '$element',
  55061. '$attrs',
  55062. '$ionicConfig',
  55063. function($element, $attrs, $ionicConfig) {
  55064. var spinnerName, anim;
  55065. this.init = function() {
  55066. spinnerName = $attrs.icon || $ionicConfig.spinner.icon();
  55067. var container = document.createElement('div');
  55068. createSvgElement('svg', {
  55069. viewBox: '0 0 64 64',
  55070. g: [spinners[spinnerName]]
  55071. }, container, spinnerName);
  55072. // Specifically for animations to work,
  55073. // Android 4.3 and below requires the element to be
  55074. // added as an html string, rather than dynmically
  55075. // building up the svg element and appending it.
  55076. $element.html(container.innerHTML);
  55077. this.start();
  55078. return spinnerName;
  55079. };
  55080. this.start = function() {
  55081. animations[spinnerName] && (anim = animations[spinnerName]($element[0])());
  55082. };
  55083. this.stop = function() {
  55084. animations[spinnerName] && (anim.stop = true);
  55085. };
  55086. }]);
  55087. })(ionic);
  55088. IonicModule
  55089. .controller('$ionicTab', [
  55090. '$scope',
  55091. '$ionicHistory',
  55092. '$attrs',
  55093. '$location',
  55094. '$state',
  55095. function($scope, $ionicHistory, $attrs, $location, $state) {
  55096. this.$scope = $scope;
  55097. //All of these exposed for testing
  55098. this.hrefMatchesState = function() {
  55099. return $attrs.href && $location.path().indexOf(
  55100. $attrs.href.replace(/^#/, '').replace(/\/$/, '')
  55101. ) === 0;
  55102. };
  55103. this.srefMatchesState = function() {
  55104. return $attrs.uiSref && $state.includes($attrs.uiSref.split('(')[0]);
  55105. };
  55106. this.navNameMatchesState = function() {
  55107. return this.navViewName && $ionicHistory.isCurrentStateNavView(this.navViewName);
  55108. };
  55109. this.tabMatchesState = function() {
  55110. return this.hrefMatchesState() || this.srefMatchesState() || this.navNameMatchesState();
  55111. };
  55112. }]);
  55113. IonicModule
  55114. .controller('$ionicTabs', [
  55115. '$scope',
  55116. '$element',
  55117. '$ionicHistory',
  55118. function($scope, $element, $ionicHistory) {
  55119. var self = this;
  55120. var selectedTab = null;
  55121. var previousSelectedTab = null;
  55122. var selectedTabIndex;
  55123. var isVisible = true;
  55124. self.tabs = [];
  55125. self.selectedIndex = function() {
  55126. return self.tabs.indexOf(selectedTab);
  55127. };
  55128. self.selectedTab = function() {
  55129. return selectedTab;
  55130. };
  55131. self.previousSelectedTab = function() {
  55132. return previousSelectedTab;
  55133. };
  55134. self.add = function(tab) {
  55135. $ionicHistory.registerHistory(tab);
  55136. self.tabs.push(tab);
  55137. };
  55138. self.remove = function(tab) {
  55139. var tabIndex = self.tabs.indexOf(tab);
  55140. if (tabIndex === -1) {
  55141. return;
  55142. }
  55143. //Use a field like '$tabSelected' so developers won't accidentally set it in controllers etc
  55144. if (tab.$tabSelected) {
  55145. self.deselect(tab);
  55146. //Try to select a new tab if we're removing a tab
  55147. if (self.tabs.length === 1) {
  55148. //Do nothing if there are no other tabs to select
  55149. } else {
  55150. //Select previous tab if it's the last tab, else select next tab
  55151. var newTabIndex = tabIndex === self.tabs.length - 1 ? tabIndex - 1 : tabIndex + 1;
  55152. self.select(self.tabs[newTabIndex]);
  55153. }
  55154. }
  55155. self.tabs.splice(tabIndex, 1);
  55156. };
  55157. self.deselect = function(tab) {
  55158. if (tab.$tabSelected) {
  55159. previousSelectedTab = selectedTab;
  55160. selectedTab = selectedTabIndex = null;
  55161. tab.$tabSelected = false;
  55162. (tab.onDeselect || noop)();
  55163. tab.$broadcast && tab.$broadcast('$ionicHistory.deselect');
  55164. }
  55165. };
  55166. self.select = function(tab, shouldEmitEvent) {
  55167. var tabIndex;
  55168. if (isNumber(tab)) {
  55169. tabIndex = tab;
  55170. if (tabIndex >= self.tabs.length) return;
  55171. tab = self.tabs[tabIndex];
  55172. } else {
  55173. tabIndex = self.tabs.indexOf(tab);
  55174. }
  55175. if (arguments.length === 1) {
  55176. shouldEmitEvent = !!(tab.navViewName || tab.uiSref);
  55177. }
  55178. if (selectedTab && selectedTab.$historyId == tab.$historyId) {
  55179. if (shouldEmitEvent) {
  55180. $ionicHistory.goToHistoryRoot(tab.$historyId);
  55181. }
  55182. } else if (selectedTabIndex !== tabIndex) {
  55183. forEach(self.tabs, function(tab) {
  55184. self.deselect(tab);
  55185. });
  55186. selectedTab = tab;
  55187. selectedTabIndex = tabIndex;
  55188. if (self.$scope && self.$scope.$parent) {
  55189. self.$scope.$parent.$activeHistoryId = tab.$historyId;
  55190. }
  55191. //Use a funny name like $tabSelected so the developer doesn't overwrite the var in a child scope
  55192. tab.$tabSelected = true;
  55193. (tab.onSelect || noop)();
  55194. if (shouldEmitEvent) {
  55195. $scope.$emit('$ionicHistory.change', {
  55196. type: 'tab',
  55197. tabIndex: tabIndex,
  55198. historyId: tab.$historyId,
  55199. navViewName: tab.navViewName,
  55200. hasNavView: !!tab.navViewName,
  55201. title: tab.title,
  55202. url: tab.href,
  55203. uiSref: tab.uiSref
  55204. });
  55205. }
  55206. $scope.$broadcast("tabSelected", { selectedTab: tab, selectedTabIndex: tabIndex});
  55207. }
  55208. };
  55209. self.hasActiveScope = function() {
  55210. for (var x = 0; x < self.tabs.length; x++) {
  55211. if ($ionicHistory.isActiveScope(self.tabs[x])) {
  55212. return true;
  55213. }
  55214. }
  55215. return false;
  55216. };
  55217. self.showBar = function(show) {
  55218. if (arguments.length) {
  55219. if (show) {
  55220. $element.removeClass('tabs-item-hide');
  55221. } else {
  55222. $element.addClass('tabs-item-hide');
  55223. }
  55224. isVisible = !!show;
  55225. }
  55226. return isVisible;
  55227. };
  55228. }]);
  55229. IonicModule
  55230. .controller('$ionicView', [
  55231. '$scope',
  55232. '$element',
  55233. '$attrs',
  55234. '$compile',
  55235. '$rootScope',
  55236. function($scope, $element, $attrs, $compile, $rootScope) {
  55237. var self = this;
  55238. var navElementHtml = {};
  55239. var navViewCtrl;
  55240. var navBarDelegateHandle;
  55241. var hasViewHeaderBar;
  55242. var deregisters = [];
  55243. var viewTitle;
  55244. var deregIonNavBarInit = $scope.$on('ionNavBar.init', function(ev, delegateHandle) {
  55245. // this view has its own ion-nav-bar, remember the navBarDelegateHandle for this view
  55246. ev.stopPropagation();
  55247. navBarDelegateHandle = delegateHandle;
  55248. });
  55249. self.init = function() {
  55250. deregIonNavBarInit();
  55251. var modalCtrl = $element.inheritedData('$ionModalController');
  55252. navViewCtrl = $element.inheritedData('$ionNavViewController');
  55253. // don't bother if inside a modal or there's no parent navView
  55254. if (!navViewCtrl || modalCtrl) return;
  55255. // add listeners for when this view changes
  55256. $scope.$on('$ionicView.beforeEnter', self.beforeEnter);
  55257. $scope.$on('$ionicView.afterEnter', afterEnter);
  55258. $scope.$on('$ionicView.beforeLeave', deregisterFns);
  55259. };
  55260. self.beforeEnter = function(ev, transData) {
  55261. // this event was emitted, starting at intial ion-view, then bubbles up
  55262. // only the first ion-view should do something with it, parent ion-views should ignore
  55263. if (transData && !transData.viewNotified) {
  55264. transData.viewNotified = true;
  55265. if (!$rootScope.$$phase) $scope.$digest();
  55266. viewTitle = isDefined($attrs.viewTitle) ? $attrs.viewTitle : $attrs.title;
  55267. var navBarItems = {};
  55268. for (var n in navElementHtml) {
  55269. navBarItems[n] = generateNavBarItem(navElementHtml[n]);
  55270. }
  55271. navViewCtrl.beforeEnter(extend(transData, {
  55272. title: viewTitle,
  55273. showBack: !attrTrue('hideBackButton'),
  55274. navBarItems: navBarItems,
  55275. navBarDelegate: navBarDelegateHandle || null,
  55276. showNavBar: !attrTrue('hideNavBar'),
  55277. hasHeaderBar: !!hasViewHeaderBar
  55278. }));
  55279. // make sure any existing observers are cleaned up
  55280. deregisterFns();
  55281. }
  55282. };
  55283. function afterEnter() {
  55284. // only listen for title updates after it has entered
  55285. // but also deregister the observe before it leaves
  55286. var viewTitleAttr = isDefined($attrs.viewTitle) && 'viewTitle' || isDefined($attrs.title) && 'title';
  55287. if (viewTitleAttr) {
  55288. titleUpdate($attrs[viewTitleAttr]);
  55289. deregisters.push($attrs.$observe(viewTitleAttr, titleUpdate));
  55290. }
  55291. if (isDefined($attrs.hideBackButton)) {
  55292. deregisters.push($scope.$watch($attrs.hideBackButton, function(val) {
  55293. navViewCtrl.showBackButton(!val);
  55294. }));
  55295. }
  55296. if (isDefined($attrs.hideNavBar)) {
  55297. deregisters.push($scope.$watch($attrs.hideNavBar, function(val) {
  55298. navViewCtrl.showBar(!val);
  55299. }));
  55300. }
  55301. }
  55302. function titleUpdate(newTitle) {
  55303. if (isDefined(newTitle) && newTitle !== viewTitle) {
  55304. viewTitle = newTitle;
  55305. navViewCtrl.title(viewTitle);
  55306. }
  55307. }
  55308. function deregisterFns() {
  55309. // remove all existing $attrs.$observe's
  55310. for (var x = 0; x < deregisters.length; x++) {
  55311. deregisters[x]();
  55312. }
  55313. deregisters = [];
  55314. }
  55315. function generateNavBarItem(html) {
  55316. if (html) {
  55317. // every time a view enters we need to recreate its view buttons if they exist
  55318. return $compile(html)($scope.$new());
  55319. }
  55320. }
  55321. function attrTrue(key) {
  55322. return !!$scope.$eval($attrs[key]);
  55323. }
  55324. self.navElement = function(type, html) {
  55325. navElementHtml[type] = html;
  55326. };
  55327. }]);
  55328. /*
  55329. * We don't document the ionActionSheet directive, we instead document
  55330. * the $ionicActionSheet service
  55331. */
  55332. IonicModule
  55333. .directive('ionActionSheet', ['$document', function($document) {
  55334. return {
  55335. restrict: 'E',
  55336. scope: true,
  55337. replace: true,
  55338. link: function($scope, $element) {
  55339. var keyUp = function(e) {
  55340. if (e.which == 27) {
  55341. $scope.cancel();
  55342. $scope.$apply();
  55343. }
  55344. };
  55345. var backdropClick = function(e) {
  55346. if (e.target == $element[0]) {
  55347. $scope.cancel();
  55348. $scope.$apply();
  55349. }
  55350. };
  55351. $scope.$on('$destroy', function() {
  55352. $element.remove();
  55353. $document.unbind('keyup', keyUp);
  55354. });
  55355. $document.bind('keyup', keyUp);
  55356. $element.bind('click', backdropClick);
  55357. },
  55358. template: '<div class="action-sheet-backdrop">' +
  55359. '<div class="action-sheet-wrapper">' +
  55360. '<div class="action-sheet" ng-class="{\'action-sheet-has-icons\': $actionSheetHasIcon}">' +
  55361. '<div class="action-sheet-group action-sheet-options">' +
  55362. '<div class="action-sheet-title" ng-if="titleText" ng-bind-html="titleText"></div>' +
  55363. '<button class="button action-sheet-option" ng-click="buttonClicked($index)" ng-class="b.className" ng-repeat="b in buttons" ng-bind-html="b.text"></button>' +
  55364. '<button class="button destructive action-sheet-destructive" ng-if="destructiveText" ng-click="destructiveButtonClicked()" ng-bind-html="destructiveText"></button>' +
  55365. '</div>' +
  55366. '<div class="action-sheet-group action-sheet-cancel" ng-if="cancelText">' +
  55367. '<button class="button" ng-click="cancel()" ng-bind-html="cancelText"></button>' +
  55368. '</div>' +
  55369. '</div>' +
  55370. '</div>' +
  55371. '</div>'
  55372. };
  55373. }]);
  55374. /**
  55375. * @ngdoc directive
  55376. * @name ionCheckbox
  55377. * @module ionic
  55378. * @restrict E
  55379. * @codepen hqcju
  55380. * @description
  55381. * The checkbox is no different than the HTML checkbox input, except it's styled differently.
  55382. *
  55383. * The checkbox behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]).
  55384. *
  55385. * @usage
  55386. * ```html
  55387. * <ion-checkbox ng-model="isChecked">Checkbox Label</ion-checkbox>
  55388. * ```
  55389. */
  55390. IonicModule
  55391. .directive('ionCheckbox', ['$ionicConfig', function($ionicConfig) {
  55392. return {
  55393. restrict: 'E',
  55394. replace: true,
  55395. require: '?ngModel',
  55396. transclude: true,
  55397. template:
  55398. '<label class="item item-checkbox">' +
  55399. '<div class="checkbox checkbox-input-hidden disable-pointer-events">' +
  55400. '<input type="checkbox">' +
  55401. '<i class="checkbox-icon"></i>' +
  55402. '</div>' +
  55403. '<div class="item-content disable-pointer-events" ng-transclude></div>' +
  55404. '</label>',
  55405. compile: function(element, attr) {
  55406. var input = element.find('input');
  55407. forEach({
  55408. 'name': attr.name,
  55409. 'ng-value': attr.ngValue,
  55410. 'ng-model': attr.ngModel,
  55411. 'ng-checked': attr.ngChecked,
  55412. 'ng-disabled': attr.ngDisabled,
  55413. 'ng-true-value': attr.ngTrueValue,
  55414. 'ng-false-value': attr.ngFalseValue,
  55415. 'ng-change': attr.ngChange,
  55416. 'ng-required': attr.ngRequired,
  55417. 'required': attr.required
  55418. }, function(value, name) {
  55419. if (isDefined(value)) {
  55420. input.attr(name, value);
  55421. }
  55422. });
  55423. var checkboxWrapper = element[0].querySelector('.checkbox');
  55424. checkboxWrapper.classList.add('checkbox-' + $ionicConfig.form.checkbox());
  55425. }
  55426. };
  55427. }]);
  55428. /**
  55429. * @ngdoc directive
  55430. * @restrict A
  55431. * @name collectionRepeat
  55432. * @module ionic
  55433. * @codepen 7ec1ec58f2489ab8f359fa1a0fe89c15
  55434. * @description
  55435. * `collection-repeat` allows an app to show huge lists of items much more performantly than
  55436. * `ng-repeat`.
  55437. *
  55438. * It renders into the DOM only as many items as are currently visible.
  55439. *
  55440. * This means that on a phone screen that can fit eight items, only the eight items matching
  55441. * the current scroll position will be rendered.
  55442. *
  55443. * **The Basics**:
  55444. *
  55445. * - The data given to collection-repeat must be an array.
  55446. * - If the `item-height` and `item-width` attributes are not supplied, it will be assumed that
  55447. * every item in the list has the same dimensions as the first item.
  55448. * - Don't use angular one-time binding (`::`) with collection-repeat. The scope of each item is
  55449. * assigned new data and re-digested as you scroll. Bindings need to update, and one-time bindings
  55450. * won't.
  55451. *
  55452. * **Performance Tips**:
  55453. *
  55454. * - The iOS webview has a performance bottleneck when switching out `<img src>` attributes.
  55455. * To increase performance of images on iOS, cache your images in advance and,
  55456. * if possible, lower the number of unique images. We're working on [a solution](https://github.com/driftyco/ionic/issues/3194).
  55457. *
  55458. * @usage
  55459. * #### Basic Item List ([codepen](http://codepen.io/ionic/pen/0c2c35a34a8b18ad4d793fef0b081693))
  55460. * ```html
  55461. * <ion-content>
  55462. * <ion-item collection-repeat="item in items">
  55463. * {% raw %}{{item}}{% endraw %}
  55464. * </ion-item>
  55465. * </ion-content>
  55466. * ```
  55467. *
  55468. * #### Grid of Images ([codepen](http://codepen.io/ionic/pen/5515d4efd9d66f780e96787387f41664))
  55469. * ```html
  55470. * <ion-content>
  55471. * <img collection-repeat="photo in photos"
  55472. * item-width="33%"
  55473. * item-height="200px"
  55474. * ng-src="{% raw %}{{photo.url}}{% endraw %}">
  55475. * </ion-content>
  55476. * ```
  55477. *
  55478. * #### Horizontal Scroller, Dynamic Item Width ([codepen](http://codepen.io/ionic/pen/67cc56b349124a349acb57a0740e030e))
  55479. * ```html
  55480. * <ion-content>
  55481. * <h2>Available Kittens:</h2>
  55482. * <ion-scroll direction="x" class="available-scroller">
  55483. * <div class="photo" collection-repeat="photo in main.photos"
  55484. * item-height="250" item-width="photo.width + 30">
  55485. * <img ng-src="{% raw %}{{photo.src}}{% endraw %}">
  55486. * </div>
  55487. * </ion-scroll>
  55488. * </ion-content>
  55489. * ```
  55490. *
  55491. * @param {expression} collection-repeat The expression indicating how to enumerate a collection,
  55492. * of the format `variable in expression` – where variable is the user defined loop variable
  55493. * and `expression` is a scope expression giving the collection to enumerate.
  55494. * For example: `album in artist.albums` or `album in artist.albums | orderBy:'name'`.
  55495. * @param {expression=} item-width The width of the repeated element. The expression must return
  55496. * a number (pixels) or a percentage. Defaults to the width of the first item in the list.
  55497. * (previously named collection-item-width)
  55498. * @param {expression=} item-height The height of the repeated element. The expression must return
  55499. * a number (pixels) or a percentage. Defaults to the height of the first item in the list.
  55500. * (previously named collection-item-height)
  55501. * @param {number=} item-render-buffer The number of items to load before and after the visible
  55502. * items in the list. Default 3. Tip: set this higher if you have lots of images to preload, but
  55503. * don't set it too high or you'll see performance loss.
  55504. * @param {boolean=} force-refresh-images Force images to refresh as you scroll. This fixes a problem
  55505. * where, when an element is interchanged as scrolling, its image will still have the old src
  55506. * while the new src loads. Setting this to true comes with a small performance loss.
  55507. */
  55508. IonicModule
  55509. .directive('collectionRepeat', CollectionRepeatDirective)
  55510. .factory('$ionicCollectionManager', RepeatManagerFactory);
  55511. var ONE_PX_TRANSPARENT_IMG_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
  55512. var WIDTH_HEIGHT_REGEX = /height:.*?px;\s*width:.*?px/;
  55513. var DEFAULT_RENDER_BUFFER = 3;
  55514. CollectionRepeatDirective.$inject = ['$ionicCollectionManager', '$parse', '$window', '$$rAF', '$rootScope', '$timeout'];
  55515. function CollectionRepeatDirective($ionicCollectionManager, $parse, $window, $$rAF, $rootScope, $timeout) {
  55516. return {
  55517. restrict: 'A',
  55518. priority: 1000,
  55519. transclude: 'element',
  55520. $$tlb: true,
  55521. require: '^^$ionicScroll',
  55522. link: postLink
  55523. };
  55524. function postLink(scope, element, attr, scrollCtrl, transclude) {
  55525. var scrollView = scrollCtrl.scrollView;
  55526. var node = element[0];
  55527. var containerNode = angular.element('<div class="collection-repeat-container">')[0];
  55528. node.parentNode.replaceChild(containerNode, node);
  55529. if (scrollView.options.scrollingX && scrollView.options.scrollingY) {
  55530. throw new Error("collection-repeat expected a parent x or y scrollView, not " +
  55531. "an xy scrollView.");
  55532. }
  55533. var repeatExpr = attr.collectionRepeat;
  55534. var match = repeatExpr.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  55535. if (!match) {
  55536. throw new Error("collection-repeat expected expression in form of '_item_ in " +
  55537. "_collection_[ track by _id_]' but got '" + attr.collectionRepeat + "'.");
  55538. }
  55539. var keyExpr = match[1];
  55540. var listExpr = match[2];
  55541. var listGetter = $parse(listExpr);
  55542. var heightData = {};
  55543. var widthData = {};
  55544. var computedStyleDimensions = {};
  55545. var data = [];
  55546. var repeatManager;
  55547. // attr.collectionBufferSize is deprecated
  55548. var renderBufferExpr = attr.itemRenderBuffer || attr.collectionBufferSize;
  55549. var renderBuffer = angular.isDefined(renderBufferExpr) ?
  55550. parseInt(renderBufferExpr) :
  55551. DEFAULT_RENDER_BUFFER;
  55552. // attr.collectionItemHeight is deprecated
  55553. var heightExpr = attr.itemHeight || attr.collectionItemHeight;
  55554. // attr.collectionItemWidth is deprecated
  55555. var widthExpr = attr.itemWidth || attr.collectionItemWidth;
  55556. var afterItemsContainer = initAfterItemsContainer();
  55557. var changeValidator = makeChangeValidator();
  55558. initDimensions();
  55559. // Dimensions are refreshed on resize or data change.
  55560. scrollCtrl.$element.on('scroll-resize', refreshDimensions);
  55561. angular.element($window).on('resize', onResize);
  55562. var unlistenToExposeAside = $rootScope.$on('$ionicExposeAside', ionic.animationFrameThrottle(function() {
  55563. scrollCtrl.scrollView.resize();
  55564. onResize();
  55565. }));
  55566. $timeout(refreshDimensions, 0, false);
  55567. function onResize() {
  55568. if (changeValidator.resizeRequiresRefresh(scrollView.__clientWidth, scrollView.__clientHeight)) {
  55569. refreshDimensions();
  55570. }
  55571. }
  55572. scope.$watchCollection(listGetter, function(newValue) {
  55573. data = newValue || (newValue = []);
  55574. if (!angular.isArray(newValue)) {
  55575. throw new Error("collection-repeat expected an array for '" + listExpr + "', " +
  55576. "but got a " + typeof value);
  55577. }
  55578. // Wait for this digest to end before refreshing everything.
  55579. scope.$$postDigest(function() {
  55580. getRepeatManager().setData(data);
  55581. if (changeValidator.dataChangeRequiresRefresh(data)) refreshDimensions();
  55582. });
  55583. });
  55584. scope.$on('$destroy', function() {
  55585. angular.element($window).off('resize', onResize);
  55586. unlistenToExposeAside();
  55587. scrollCtrl.$element && scrollCtrl.$element.off('scroll-resize', refreshDimensions);
  55588. computedStyleNode && computedStyleNode.parentNode &&
  55589. computedStyleNode.parentNode.removeChild(computedStyleNode);
  55590. computedStyleScope && computedStyleScope.$destroy();
  55591. computedStyleScope = computedStyleNode = null;
  55592. repeatManager && repeatManager.destroy();
  55593. repeatManager = null;
  55594. });
  55595. function makeChangeValidator() {
  55596. var self;
  55597. return (self = {
  55598. dataLength: 0,
  55599. width: 0,
  55600. height: 0,
  55601. // A resize triggers a refresh only if we have data, the scrollView has size,
  55602. // and the size has changed.
  55603. resizeRequiresRefresh: function(newWidth, newHeight) {
  55604. var requiresRefresh = self.dataLength && newWidth && newHeight &&
  55605. (newWidth !== self.width || newHeight !== self.height);
  55606. self.width = newWidth;
  55607. self.height = newHeight;
  55608. return !!requiresRefresh;
  55609. },
  55610. // A change in data only triggers a refresh if the data has length, or if the data's
  55611. // length is less than before.
  55612. dataChangeRequiresRefresh: function(newData) {
  55613. var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;
  55614. self.dataLength = newData.length;
  55615. return !!requiresRefresh;
  55616. }
  55617. });
  55618. }
  55619. function getRepeatManager() {
  55620. return repeatManager || (repeatManager = new $ionicCollectionManager({
  55621. afterItemsNode: afterItemsContainer[0],
  55622. containerNode: containerNode,
  55623. heightData: heightData,
  55624. widthData: widthData,
  55625. forceRefreshImages: !!(isDefined(attr.forceRefreshImages) && attr.forceRefreshImages !== 'false'),
  55626. keyExpression: keyExpr,
  55627. renderBuffer: renderBuffer,
  55628. scope: scope,
  55629. scrollView: scrollCtrl.scrollView,
  55630. transclude: transclude
  55631. }));
  55632. }
  55633. function initAfterItemsContainer() {
  55634. var container = angular.element(
  55635. scrollView.__content.querySelector('.collection-repeat-after-container')
  55636. );
  55637. // Put everything in the view after the repeater into a container.
  55638. if (!container.length) {
  55639. var elementIsAfterRepeater = false;
  55640. var afterNodes = [].filter.call(scrollView.__content.childNodes, function(node) {
  55641. if (ionic.DomUtil.contains(node, containerNode)) {
  55642. elementIsAfterRepeater = true;
  55643. return false;
  55644. }
  55645. return elementIsAfterRepeater;
  55646. });
  55647. container = angular.element('<span class="collection-repeat-after-container">');
  55648. if (scrollView.options.scrollingX) {
  55649. container.addClass('horizontal');
  55650. }
  55651. container.append(afterNodes);
  55652. scrollView.__content.appendChild(container[0]);
  55653. }
  55654. return container;
  55655. }
  55656. function initDimensions() {
  55657. //Height and width have four 'modes':
  55658. //1) Computed Mode
  55659. // - Nothing is supplied, so we getComputedStyle() on one element in the list and use
  55660. // that width and height value for the width and height of every item. This is re-computed
  55661. // every resize.
  55662. //2) Constant Mode, Static Integer
  55663. // - The user provides a constant number for width or height, in pixels. We parse it,
  55664. // store it on the `value` field, and it never changes
  55665. //3) Constant Mode, Percent
  55666. // - The user provides a percent string for width or height. The getter for percent is
  55667. // stored on the `getValue()` field, and is re-evaluated once every resize. The result
  55668. // is stored on the `value` field.
  55669. //4) Dynamic Mode
  55670. // - The user provides a dynamic expression for the width or height. This is re-evaluated
  55671. // for every item, stored on the `.getValue()` field.
  55672. if (heightExpr) {
  55673. parseDimensionAttr(heightExpr, heightData);
  55674. } else {
  55675. heightData.computed = true;
  55676. }
  55677. if (widthExpr) {
  55678. parseDimensionAttr(widthExpr, widthData);
  55679. } else {
  55680. widthData.computed = true;
  55681. }
  55682. }
  55683. function refreshDimensions() {
  55684. var hasData = data.length > 0;
  55685. if (hasData && (heightData.computed || widthData.computed)) {
  55686. computeStyleDimensions();
  55687. }
  55688. if (hasData && heightData.computed) {
  55689. heightData.value = computedStyleDimensions.height;
  55690. if (!heightData.value) {
  55691. throw new Error('collection-repeat tried to compute the height of repeated elements "' +
  55692. repeatExpr + '", but was unable to. Please provide the "item-height" attribute. ' +
  55693. 'http://ionicframework.com/docs/api/directive/collectionRepeat/');
  55694. }
  55695. } else if (!heightData.dynamic && heightData.getValue) {
  55696. // If it's a constant with a getter (eg percent), we just refresh .value after resize
  55697. heightData.value = heightData.getValue();
  55698. }
  55699. if (hasData && widthData.computed) {
  55700. widthData.value = computedStyleDimensions.width;
  55701. if (!widthData.value) {
  55702. throw new Error('collection-repeat tried to compute the width of repeated elements "' +
  55703. repeatExpr + '", but was unable to. Please provide the "item-width" attribute. ' +
  55704. 'http://ionicframework.com/docs/api/directive/collectionRepeat/');
  55705. }
  55706. } else if (!widthData.dynamic && widthData.getValue) {
  55707. // If it's a constant with a getter (eg percent), we just refresh .value after resize
  55708. widthData.value = widthData.getValue();
  55709. }
  55710. // Dynamic dimensions aren't updated on resize. Since they're already dynamic anyway,
  55711. // .getValue() will be used.
  55712. getRepeatManager().refreshLayout();
  55713. }
  55714. function parseDimensionAttr(attrValue, dimensionData) {
  55715. if (!attrValue) return;
  55716. var parsedValue;
  55717. // Try to just parse the plain attr value
  55718. try {
  55719. parsedValue = $parse(attrValue);
  55720. } catch (e) {
  55721. // If the parse fails and the value has `px` or `%` in it, surround the attr in
  55722. // quotes, to attempt to let the user provide a simple `attr="100%"` or `attr="100px"`
  55723. if (attrValue.trim().match(/\d+(px|%)$/)) {
  55724. attrValue = '"' + attrValue + '"';
  55725. }
  55726. parsedValue = $parse(attrValue);
  55727. }
  55728. var constantAttrValue = attrValue.replace(/(\'|\"|px|%)/g, '').trim();
  55729. var isConstant = constantAttrValue.length && !/([a-zA-Z]|\$|:|\?)/.test(constantAttrValue);
  55730. dimensionData.attrValue = attrValue;
  55731. // If it's a constant, it's either a percent or just a constant pixel number.
  55732. if (isConstant) {
  55733. // For percents, store the percent getter on .getValue()
  55734. if (attrValue.indexOf('%') > -1) {
  55735. var decimalValue = parseFloat(parsedValue()) / 100;
  55736. dimensionData.getValue = dimensionData === heightData ?
  55737. function() { return Math.floor(decimalValue * scrollView.__clientHeight); } :
  55738. function() { return Math.floor(decimalValue * scrollView.__clientWidth); };
  55739. } else {
  55740. // For static constants, just store the static constant.
  55741. dimensionData.value = parseInt(parsedValue());
  55742. }
  55743. } else {
  55744. dimensionData.dynamic = true;
  55745. dimensionData.getValue = dimensionData === heightData ?
  55746. function heightGetter(scope, locals) {
  55747. var result = parsedValue(scope, locals);
  55748. if (result.charAt && result.charAt(result.length - 1) === '%') {
  55749. return Math.floor(parseFloat(result) / 100 * scrollView.__clientHeight);
  55750. }
  55751. return parseInt(result);
  55752. } :
  55753. function widthGetter(scope, locals) {
  55754. var result = parsedValue(scope, locals);
  55755. if (result.charAt && result.charAt(result.length - 1) === '%') {
  55756. return Math.floor(parseFloat(result) / 100 * scrollView.__clientWidth);
  55757. }
  55758. return parseInt(result);
  55759. };
  55760. }
  55761. }
  55762. var computedStyleNode;
  55763. var computedStyleScope;
  55764. function computeStyleDimensions() {
  55765. if (!computedStyleNode) {
  55766. transclude(computedStyleScope = scope.$new(), function(clone) {
  55767. clone[0].removeAttribute('collection-repeat'); // remove absolute position styling
  55768. computedStyleNode = clone[0];
  55769. });
  55770. }
  55771. computedStyleScope[keyExpr] = (listGetter(scope) || [])[0];
  55772. if (!$rootScope.$$phase) computedStyleScope.$digest();
  55773. containerNode.appendChild(computedStyleNode);
  55774. var style = $window.getComputedStyle(computedStyleNode);
  55775. computedStyleDimensions.width = parseInt(style.width);
  55776. computedStyleDimensions.height = parseInt(style.height);
  55777. containerNode.removeChild(computedStyleNode);
  55778. }
  55779. }
  55780. }
  55781. RepeatManagerFactory.$inject = ['$rootScope', '$window', '$$rAF'];
  55782. function RepeatManagerFactory($rootScope, $window, $$rAF) {
  55783. var EMPTY_DIMENSION = { primaryPos: 0, secondaryPos: 0, primarySize: 0, secondarySize: 0, rowPrimarySize: 0 };
  55784. return function RepeatController(options) {
  55785. var afterItemsNode = options.afterItemsNode;
  55786. var containerNode = options.containerNode;
  55787. var forceRefreshImages = options.forceRefreshImages;
  55788. var heightData = options.heightData;
  55789. var widthData = options.widthData;
  55790. var keyExpression = options.keyExpression;
  55791. var renderBuffer = options.renderBuffer;
  55792. var scope = options.scope;
  55793. var scrollView = options.scrollView;
  55794. var transclude = options.transclude;
  55795. var data = [];
  55796. var getterLocals = {};
  55797. var heightFn = heightData.getValue || function() { return heightData.value; };
  55798. var heightGetter = function(index, value) {
  55799. getterLocals[keyExpression] = value;
  55800. getterLocals.$index = index;
  55801. return heightFn(scope, getterLocals);
  55802. };
  55803. var widthFn = widthData.getValue || function() { return widthData.value; };
  55804. var widthGetter = function(index, value) {
  55805. getterLocals[keyExpression] = value;
  55806. getterLocals.$index = index;
  55807. return widthFn(scope, getterLocals);
  55808. };
  55809. var isVertical = !!scrollView.options.scrollingY;
  55810. // We say it's a grid view if we're either dynamic or not 100% width
  55811. var isGridView = isVertical ?
  55812. (widthData.dynamic || widthData.value !== scrollView.__clientWidth) :
  55813. (heightData.dynamic || heightData.value !== scrollView.__clientHeight);
  55814. var isStaticView = !heightData.dynamic && !widthData.dynamic;
  55815. var PRIMARY = 'PRIMARY';
  55816. var SECONDARY = 'SECONDARY';
  55817. var TRANSLATE_TEMPLATE_STR = isVertical ?
  55818. 'translate3d(SECONDARYpx,PRIMARYpx,0)' :
  55819. 'translate3d(PRIMARYpx,SECONDARYpx,0)';
  55820. var WIDTH_HEIGHT_TEMPLATE_STR = isVertical ?
  55821. 'height: PRIMARYpx; width: SECONDARYpx;' :
  55822. 'height: SECONDARYpx; width: PRIMARYpx;';
  55823. var estimatedHeight;
  55824. var estimatedWidth;
  55825. var repeaterBeforeSize = 0;
  55826. var repeaterAfterSize = 0;
  55827. var renderStartIndex = -1;
  55828. var renderEndIndex = -1;
  55829. var renderAfterBoundary = -1;
  55830. var renderBeforeBoundary = -1;
  55831. var itemsPool = [];
  55832. var itemsLeaving = [];
  55833. var itemsEntering = [];
  55834. var itemsShownMap = {};
  55835. var nextItemId = 0;
  55836. var scrollViewSetDimensions = isVertical ?
  55837. function() { scrollView.setDimensions(null, null, null, view.getContentSize(), true); } :
  55838. function() { scrollView.setDimensions(null, null, view.getContentSize(), null, true); };
  55839. // view is a mix of list/grid methods + static/dynamic methods.
  55840. // See bottom for implementations. Available methods:
  55841. //
  55842. // getEstimatedPrimaryPos(i), getEstimatedSecondaryPos(i), getEstimatedIndex(scrollTop),
  55843. // calculateDimensions(toIndex), getDimensions(index),
  55844. // updateRenderRange(scrollTop, scrollValueEnd), onRefreshLayout(), onRefreshData()
  55845. var view = isVertical ? new VerticalViewType() : new HorizontalViewType();
  55846. (isGridView ? GridViewType : ListViewType).call(view);
  55847. (isStaticView ? StaticViewType : DynamicViewType).call(view);
  55848. var contentSizeStr = isVertical ? 'getContentHeight' : 'getContentWidth';
  55849. var originalGetContentSize = scrollView.options[contentSizeStr];
  55850. scrollView.options[contentSizeStr] = angular.bind(view, view.getContentSize);
  55851. scrollView.__$callback = scrollView.__callback;
  55852. scrollView.__callback = function(transformLeft, transformTop, zoom, wasResize) {
  55853. var scrollValue = view.getScrollValue();
  55854. if (renderStartIndex === -1 ||
  55855. scrollValue + view.scrollPrimarySize > renderAfterBoundary ||
  55856. scrollValue < renderBeforeBoundary) {
  55857. render();
  55858. }
  55859. scrollView.__$callback(transformLeft, transformTop, zoom, wasResize);
  55860. };
  55861. var isLayoutReady = false;
  55862. var isDataReady = false;
  55863. this.refreshLayout = function() {
  55864. if (data.length) {
  55865. estimatedHeight = heightGetter(0, data[0]);
  55866. estimatedWidth = widthGetter(0, data[0]);
  55867. } else {
  55868. // If we don't have any data in our array, just guess.
  55869. estimatedHeight = 100;
  55870. estimatedWidth = 100;
  55871. }
  55872. // Get the size of every element AFTER the repeater. We have to get the margin before and
  55873. // after the first/last element to fix a browser bug with getComputedStyle() not counting
  55874. // the first/last child's margins into height.
  55875. var style = getComputedStyle(afterItemsNode) || {};
  55876. var firstStyle = afterItemsNode.firstElementChild && getComputedStyle(afterItemsNode.firstElementChild) || {};
  55877. var lastStyle = afterItemsNode.lastElementChild && getComputedStyle(afterItemsNode.lastElementChild) || {};
  55878. repeaterAfterSize = (parseInt(style[isVertical ? 'height' : 'width']) || 0) +
  55879. (firstStyle && parseInt(firstStyle[isVertical ? 'marginTop' : 'marginLeft']) || 0) +
  55880. (lastStyle && parseInt(lastStyle[isVertical ? 'marginBottom' : 'marginRight']) || 0);
  55881. // Get the offsetTop of the repeater.
  55882. repeaterBeforeSize = 0;
  55883. var current = containerNode;
  55884. do {
  55885. repeaterBeforeSize += current[isVertical ? 'offsetTop' : 'offsetLeft'];
  55886. } while ( ionic.DomUtil.contains(scrollView.__content, current = current.offsetParent) );
  55887. var containerPrevNode = containerNode.previousElementSibling;
  55888. var beforeStyle = containerPrevNode ? $window.getComputedStyle(containerPrevNode) : {};
  55889. var beforeMargin = parseInt(beforeStyle[isVertical ? 'marginBottom' : 'marginRight'] || 0);
  55890. // Because we position the collection container with position: relative, it doesn't take
  55891. // into account where to position itself relative to the previous element's marginBottom.
  55892. // To compensate, we translate the container up by the previous element's margin.
  55893. containerNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  55894. .replace(PRIMARY, -beforeMargin)
  55895. .replace(SECONDARY, 0);
  55896. repeaterBeforeSize -= beforeMargin;
  55897. if (!scrollView.__clientHeight || !scrollView.__clientWidth) {
  55898. scrollView.__clientWidth = scrollView.__container.clientWidth;
  55899. scrollView.__clientHeight = scrollView.__container.clientHeight;
  55900. }
  55901. (view.onRefreshLayout || angular.noop)();
  55902. view.refreshDirection();
  55903. scrollViewSetDimensions();
  55904. // Create the pool of items for reuse, setting the size to (estimatedItemsOnScreen) * 2,
  55905. // plus the size of the renderBuffer.
  55906. if (!isLayoutReady) {
  55907. var poolSize = Math.max(20, renderBuffer * 3);
  55908. for (var i = 0; i < poolSize; i++) {
  55909. itemsPool.push(new RepeatItem());
  55910. }
  55911. }
  55912. isLayoutReady = true;
  55913. if (isLayoutReady && isDataReady) {
  55914. // If the resize or latest data change caused the scrollValue to
  55915. // now be out of bounds, resize the scrollView.
  55916. if (scrollView.__scrollLeft > scrollView.__maxScrollLeft ||
  55917. scrollView.__scrollTop > scrollView.__maxScrollTop) {
  55918. scrollView.resize();
  55919. }
  55920. forceRerender(true);
  55921. }
  55922. };
  55923. this.setData = function(newData) {
  55924. data = newData;
  55925. (view.onRefreshData || angular.noop)();
  55926. isDataReady = true;
  55927. };
  55928. this.destroy = function() {
  55929. render.destroyed = true;
  55930. itemsPool.forEach(function(item) {
  55931. item.scope.$destroy();
  55932. item.scope = item.element = item.node = item.images = null;
  55933. });
  55934. itemsPool.length = itemsEntering.length = itemsLeaving.length = 0;
  55935. itemsShownMap = {};
  55936. //Restore the scrollView's normal behavior and resize it to normal size.
  55937. scrollView.options[contentSizeStr] = originalGetContentSize;
  55938. scrollView.__callback = scrollView.__$callback;
  55939. scrollView.resize();
  55940. (view.onDestroy || angular.noop)();
  55941. };
  55942. function forceRerender() {
  55943. return render(true);
  55944. }
  55945. function render(forceRerender) {
  55946. if (render.destroyed) return;
  55947. var i;
  55948. var ii;
  55949. var item;
  55950. var dim;
  55951. var scope;
  55952. var scrollValue = view.getScrollValue();
  55953. var scrollValueEnd = scrollValue + view.scrollPrimarySize;
  55954. view.updateRenderRange(scrollValue, scrollValueEnd);
  55955. renderStartIndex = Math.max(0, renderStartIndex - renderBuffer);
  55956. renderEndIndex = Math.min(data.length - 1, renderEndIndex + renderBuffer);
  55957. for (i in itemsShownMap) {
  55958. if (i < renderStartIndex || i > renderEndIndex) {
  55959. item = itemsShownMap[i];
  55960. delete itemsShownMap[i];
  55961. itemsLeaving.push(item);
  55962. item.isShown = false;
  55963. }
  55964. }
  55965. // Render indicies that aren't shown yet
  55966. //
  55967. // NOTE(ajoslin): this may sound crazy, but calling any other functions during this render
  55968. // loop will often push the render time over the edge from less than one frame to over
  55969. // one frame, causing visible jank.
  55970. // DON'T call any other functions inside this loop unless it's vital.
  55971. for (i = renderStartIndex; i <= renderEndIndex; i++) {
  55972. // We only go forward with render if the index is in data, the item isn't already shown,
  55973. // or forceRerender is on.
  55974. if (i >= data.length || (itemsShownMap[i] && !forceRerender)) continue;
  55975. item = itemsShownMap[i] || (itemsShownMap[i] = itemsLeaving.length ? itemsLeaving.pop() :
  55976. itemsPool.length ? itemsPool.shift() :
  55977. new RepeatItem());
  55978. itemsEntering.push(item);
  55979. item.isShown = true;
  55980. scope = item.scope;
  55981. scope.$index = i;
  55982. scope[keyExpression] = data[i];
  55983. scope.$first = (i === 0);
  55984. scope.$last = (i === (data.length - 1));
  55985. scope.$middle = !(scope.$first || scope.$last);
  55986. scope.$odd = !(scope.$even = (i & 1) === 0);
  55987. if (scope.$$disconnected) ionic.Utils.reconnectScope(item.scope);
  55988. dim = view.getDimensions(i);
  55989. if (item.secondaryPos !== dim.secondaryPos || item.primaryPos !== dim.primaryPos) {
  55990. item.node.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  55991. .replace(PRIMARY, (item.primaryPos = dim.primaryPos))
  55992. .replace(SECONDARY, (item.secondaryPos = dim.secondaryPos));
  55993. }
  55994. if (item.secondarySize !== dim.secondarySize || item.primarySize !== dim.primarySize) {
  55995. item.node.style.cssText = item.node.style.cssText
  55996. .replace(WIDTH_HEIGHT_REGEX, WIDTH_HEIGHT_TEMPLATE_STR
  55997. //TODO fix item.primarySize + 1 hack
  55998. .replace(PRIMARY, (item.primarySize = dim.primarySize) + 1)
  55999. .replace(SECONDARY, (item.secondarySize = dim.secondarySize))
  56000. );
  56001. }
  56002. }
  56003. // If we reach the end of the list, render the afterItemsNode - this contains all the
  56004. // elements the developer placed after the collection-repeat
  56005. if (renderEndIndex === data.length - 1) {
  56006. dim = view.getDimensions(data.length - 1) || EMPTY_DIMENSION;
  56007. afterItemsNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  56008. .replace(PRIMARY, dim.primaryPos + dim.primarySize)
  56009. .replace(SECONDARY, 0);
  56010. }
  56011. while (itemsLeaving.length) {
  56012. item = itemsLeaving.pop();
  56013. item.scope.$broadcast('$collectionRepeatLeave');
  56014. ionic.Utils.disconnectScope(item.scope);
  56015. itemsPool.push(item);
  56016. item.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';
  56017. item.primaryPos = item.secondaryPos = null;
  56018. }
  56019. if (forceRefreshImages) {
  56020. for (i = 0, ii = itemsEntering.length; i < ii && (item = itemsEntering[i]); i++) {
  56021. if (!item.images) continue;
  56022. for (var j = 0, jj = item.images.length, img; j < jj && (img = item.images[j]); j++) {
  56023. var src = img.src;
  56024. img.src = ONE_PX_TRANSPARENT_IMG_SRC;
  56025. img.src = src;
  56026. }
  56027. }
  56028. }
  56029. if (forceRerender) {
  56030. var rootScopePhase = $rootScope.$$phase;
  56031. while (itemsEntering.length) {
  56032. item = itemsEntering.pop();
  56033. if (!rootScopePhase) item.scope.$digest();
  56034. }
  56035. } else {
  56036. digestEnteringItems();
  56037. }
  56038. }
  56039. function digestEnteringItems() {
  56040. var item;
  56041. if (digestEnteringItems.running) return;
  56042. digestEnteringItems.running = true;
  56043. $$rAF(function process() {
  56044. var rootScopePhase = $rootScope.$$phase;
  56045. while (itemsEntering.length) {
  56046. item = itemsEntering.pop();
  56047. if (item.isShown) {
  56048. if (!rootScopePhase) item.scope.$digest();
  56049. }
  56050. }
  56051. digestEnteringItems.running = false;
  56052. });
  56053. }
  56054. function RepeatItem() {
  56055. var self = this;
  56056. this.scope = scope.$new();
  56057. this.id = 'item' + (nextItemId++);
  56058. transclude(this.scope, function(clone) {
  56059. self.element = clone;
  56060. self.element.data('$$collectionRepeatItem', self);
  56061. // TODO destroy
  56062. self.node = clone[0];
  56063. // Batch style setting to lower repaints
  56064. self.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';
  56065. self.node.style.cssText += ' height: 0px; width: 0px;';
  56066. ionic.Utils.disconnectScope(self.scope);
  56067. containerNode.appendChild(self.node);
  56068. self.images = clone[0].getElementsByTagName('img');
  56069. });
  56070. }
  56071. function VerticalViewType() {
  56072. this.getItemPrimarySize = heightGetter;
  56073. this.getItemSecondarySize = widthGetter;
  56074. this.getScrollValue = function() {
  56075. return Math.max(0, Math.min(scrollView.__scrollTop - repeaterBeforeSize,
  56076. scrollView.__maxScrollTop - repeaterBeforeSize - repeaterAfterSize));
  56077. };
  56078. this.refreshDirection = function() {
  56079. this.scrollPrimarySize = scrollView.__clientHeight;
  56080. this.scrollSecondarySize = scrollView.__clientWidth;
  56081. this.estimatedPrimarySize = estimatedHeight;
  56082. this.estimatedSecondarySize = estimatedWidth;
  56083. this.estimatedItemsAcross = isGridView &&
  56084. Math.floor(scrollView.__clientWidth / estimatedWidth) ||
  56085. 1;
  56086. };
  56087. }
  56088. function HorizontalViewType() {
  56089. this.getItemPrimarySize = widthGetter;
  56090. this.getItemSecondarySize = heightGetter;
  56091. this.getScrollValue = function() {
  56092. return Math.max(0, Math.min(scrollView.__scrollLeft - repeaterBeforeSize,
  56093. scrollView.__maxScrollLeft - repeaterBeforeSize - repeaterAfterSize));
  56094. };
  56095. this.refreshDirection = function() {
  56096. this.scrollPrimarySize = scrollView.__clientWidth;
  56097. this.scrollSecondarySize = scrollView.__clientHeight;
  56098. this.estimatedPrimarySize = estimatedWidth;
  56099. this.estimatedSecondarySize = estimatedHeight;
  56100. this.estimatedItemsAcross = isGridView &&
  56101. Math.floor(scrollView.__clientHeight / estimatedHeight) ||
  56102. 1;
  56103. };
  56104. }
  56105. function GridViewType() {
  56106. this.getEstimatedSecondaryPos = function(index) {
  56107. return (index % this.estimatedItemsAcross) * this.estimatedSecondarySize;
  56108. };
  56109. this.getEstimatedPrimaryPos = function(index) {
  56110. return Math.floor(index / this.estimatedItemsAcross) * this.estimatedPrimarySize;
  56111. };
  56112. this.getEstimatedIndex = function(scrollValue) {
  56113. return Math.floor(scrollValue / this.estimatedPrimarySize) *
  56114. this.estimatedItemsAcross;
  56115. };
  56116. }
  56117. function ListViewType() {
  56118. this.getEstimatedSecondaryPos = function() {
  56119. return 0;
  56120. };
  56121. this.getEstimatedPrimaryPos = function(index) {
  56122. return index * this.estimatedPrimarySize;
  56123. };
  56124. this.getEstimatedIndex = function(scrollValue) {
  56125. return Math.floor((scrollValue) / this.estimatedPrimarySize);
  56126. };
  56127. }
  56128. function StaticViewType() {
  56129. this.getContentSize = function() {
  56130. return this.getEstimatedPrimaryPos(data.length - 1) + this.estimatedPrimarySize +
  56131. repeaterBeforeSize + repeaterAfterSize;
  56132. };
  56133. // static view always returns the same object for getDimensions, to avoid memory allocation
  56134. // while scrolling. This could be dangerous if this was a public function, but it's not.
  56135. // Only we use it.
  56136. var dim = {};
  56137. this.getDimensions = function(index) {
  56138. dim.primaryPos = this.getEstimatedPrimaryPos(index);
  56139. dim.secondaryPos = this.getEstimatedSecondaryPos(index);
  56140. dim.primarySize = this.estimatedPrimarySize;
  56141. dim.secondarySize = this.estimatedSecondarySize;
  56142. return dim;
  56143. };
  56144. this.updateRenderRange = function(scrollValue, scrollValueEnd) {
  56145. renderStartIndex = Math.max(0, this.getEstimatedIndex(scrollValue));
  56146. // Make sure the renderEndIndex takes into account all the items on the row
  56147. renderEndIndex = Math.min(data.length - 1,
  56148. this.getEstimatedIndex(scrollValueEnd) + this.estimatedItemsAcross - 1);
  56149. renderBeforeBoundary = Math.max(0,
  56150. this.getEstimatedPrimaryPos(renderStartIndex));
  56151. renderAfterBoundary = this.getEstimatedPrimaryPos(renderEndIndex) +
  56152. this.estimatedPrimarySize;
  56153. };
  56154. }
  56155. function DynamicViewType() {
  56156. var self = this;
  56157. var debouncedScrollViewSetDimensions = ionic.debounce(scrollViewSetDimensions, 25, true);
  56158. var calculateDimensions = isGridView ? calculateDimensionsGrid : calculateDimensionsList;
  56159. var dimensionsIndex;
  56160. var dimensions = [];
  56161. // Get the dimensions at index. {width, height, left, top}.
  56162. // We start with no dimensions calculated, then any time dimensions are asked for at an
  56163. // index we calculate dimensions up to there.
  56164. function calculateDimensionsList(toIndex) {
  56165. var i, prevDimension, dim;
  56166. for (i = Math.max(0, dimensionsIndex); i <= toIndex && (dim = dimensions[i]); i++) {
  56167. prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;
  56168. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56169. dim.secondarySize = self.scrollSecondarySize;
  56170. dim.primaryPos = prevDimension.primaryPos + prevDimension.primarySize;
  56171. dim.secondaryPos = 0;
  56172. }
  56173. }
  56174. function calculateDimensionsGrid(toIndex) {
  56175. var i, prevDimension, dim;
  56176. for (i = Math.max(dimensionsIndex, 0); i <= toIndex && (dim = dimensions[i]); i++) {
  56177. prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;
  56178. dim.secondarySize = Math.min(
  56179. self.getItemSecondarySize(i, data[i]),
  56180. self.scrollSecondarySize
  56181. );
  56182. dim.secondaryPos = prevDimension.secondaryPos + prevDimension.secondarySize;
  56183. if (i === 0 || dim.secondaryPos + dim.secondarySize > self.scrollSecondarySize) {
  56184. dim.secondaryPos = 0;
  56185. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56186. dim.primaryPos = prevDimension.primaryPos + prevDimension.rowPrimarySize;
  56187. dim.rowStartIndex = i;
  56188. dim.rowPrimarySize = dim.primarySize;
  56189. } else {
  56190. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56191. dim.primaryPos = prevDimension.primaryPos;
  56192. dim.rowStartIndex = prevDimension.rowStartIndex;
  56193. dimensions[dim.rowStartIndex].rowPrimarySize = dim.rowPrimarySize = Math.max(
  56194. dimensions[dim.rowStartIndex].rowPrimarySize,
  56195. dim.primarySize
  56196. );
  56197. dim.rowPrimarySize = Math.max(dim.primarySize, dim.rowPrimarySize);
  56198. }
  56199. }
  56200. }
  56201. this.getContentSize = function() {
  56202. var dim = dimensions[dimensionsIndex] || EMPTY_DIMENSION;
  56203. return ((dim.primaryPos + dim.primarySize) || 0) +
  56204. this.getEstimatedPrimaryPos(data.length - dimensionsIndex - 1) +
  56205. repeaterBeforeSize + repeaterAfterSize;
  56206. };
  56207. this.onDestroy = function() {
  56208. dimensions.length = 0;
  56209. };
  56210. this.onRefreshData = function() {
  56211. var i;
  56212. var ii;
  56213. // Make sure dimensions has as many items as data.length.
  56214. // This is to be sure we don't have to allocate objects while scrolling.
  56215. for (i = dimensions.length, ii = data.length; i < ii; i++) {
  56216. dimensions.push({});
  56217. }
  56218. dimensionsIndex = -1;
  56219. };
  56220. this.onRefreshLayout = function() {
  56221. dimensionsIndex = -1;
  56222. };
  56223. this.getDimensions = function(index) {
  56224. index = Math.min(index, data.length - 1);
  56225. if (dimensionsIndex < index) {
  56226. // Once we start asking for dimensions near the end of the list, go ahead and calculate
  56227. // everything. This is to make sure when the user gets to the end of the list, the
  56228. // scroll height of the list is 100% accurate (not estimated anymore).
  56229. if (index > data.length * 0.9) {
  56230. calculateDimensions(data.length - 1);
  56231. dimensionsIndex = data.length - 1;
  56232. scrollViewSetDimensions();
  56233. } else {
  56234. calculateDimensions(index);
  56235. dimensionsIndex = index;
  56236. debouncedScrollViewSetDimensions();
  56237. }
  56238. }
  56239. return dimensions[index];
  56240. };
  56241. var oldRenderStartIndex = -1;
  56242. var oldScrollValue = -1;
  56243. this.updateRenderRange = function(scrollValue, scrollValueEnd) {
  56244. var i;
  56245. var len;
  56246. var dim;
  56247. // Calculate more dimensions than we estimate we'll need, to be sure.
  56248. this.getDimensions( this.getEstimatedIndex(scrollValueEnd) * 2 );
  56249. // -- Calculate renderStartIndex
  56250. // base case: start at 0
  56251. if (oldRenderStartIndex === -1 || scrollValue === 0) {
  56252. i = 0;
  56253. // scrolling down
  56254. } else if (scrollValue >= oldScrollValue) {
  56255. for (i = oldRenderStartIndex, len = data.length; i < len; i++) {
  56256. if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize >= scrollValue) {
  56257. break;
  56258. }
  56259. }
  56260. // scrolling up
  56261. } else {
  56262. for (i = oldRenderStartIndex; i >= 0; i--) {
  56263. if ((dim = this.getDimensions(i)) && dim.primaryPos <= scrollValue) {
  56264. // when grid view, make sure the render starts at the beginning of a row.
  56265. i = isGridView ? dim.rowStartIndex : i;
  56266. break;
  56267. }
  56268. }
  56269. }
  56270. renderStartIndex = Math.min(Math.max(0, i), data.length - 1);
  56271. renderBeforeBoundary = renderStartIndex !== -1 ? this.getDimensions(renderStartIndex).primaryPos : -1;
  56272. // -- Calculate renderEndIndex
  56273. var lastRowDim;
  56274. for (i = renderStartIndex + 1, len = data.length; i < len; i++) {
  56275. if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize > scrollValueEnd) {
  56276. // Go all the way to the end of the row if we're in a grid
  56277. if (isGridView) {
  56278. lastRowDim = dim;
  56279. while (i < len - 1 &&
  56280. (dim = this.getDimensions(i + 1)).primaryPos === lastRowDim.primaryPos) {
  56281. i++;
  56282. }
  56283. }
  56284. break;
  56285. }
  56286. }
  56287. renderEndIndex = Math.min(i, data.length - 1);
  56288. renderAfterBoundary = renderEndIndex !== -1 ?
  56289. ((dim = this.getDimensions(renderEndIndex)).primaryPos + (dim.rowPrimarySize || dim.primarySize)) :
  56290. -1;
  56291. oldScrollValue = scrollValue;
  56292. oldRenderStartIndex = renderStartIndex;
  56293. };
  56294. }
  56295. };
  56296. }
  56297. /**
  56298. * @ngdoc directive
  56299. * @name ionContent
  56300. * @module ionic
  56301. * @delegate ionic.service:$ionicScrollDelegate
  56302. * @restrict E
  56303. *
  56304. * @description
  56305. * The ionContent directive provides an easy to use content area that can be configured
  56306. * to use Ionic's custom Scroll View, or the built in overflow scrolling of the browser.
  56307. *
  56308. * While we recommend using the custom Scroll features in Ionic in most cases, sometimes
  56309. * (for performance reasons) only the browser's native overflow scrolling will suffice,
  56310. * and so we've made it easy to toggle between the Ionic scroll implementation and
  56311. * overflow scrolling.
  56312. *
  56313. * You can implement pull-to-refresh with the {@link ionic.directive:ionRefresher}
  56314. * directive, and infinite scrolling with the {@link ionic.directive:ionInfiniteScroll}
  56315. * directive.
  56316. *
  56317. * If there is any dynamic content inside the ion-content, be sure to call `.resize()` with {@link ionic.service:$ionicScrollDelegate}
  56318. * after the content has been added.
  56319. *
  56320. * Be aware that this directive gets its own child scope. If you do not understand why this
  56321. * is important, you can read [https://docs.angularjs.org/guide/scope](https://docs.angularjs.org/guide/scope).
  56322. *
  56323. * @param {string=} delegate-handle The handle used to identify this scrollView
  56324. * with {@link ionic.service:$ionicScrollDelegate}.
  56325. * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.
  56326. * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.
  56327. * @param {boolean=} padding Whether to add padding to the content.
  56328. * Defaults to true on iOS, false on Android.
  56329. * @param {boolean=} scroll Whether to allow scrolling of content. Defaults to true.
  56330. * @param {boolean=} overflow-scroll Whether to use overflow-scrolling instead of
  56331. * Ionic scroll. See {@link ionic.provider:$ionicConfigProvider} to set this as the global default.
  56332. * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.
  56333. * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.
  56334. * @param {string=} start-x Initial horizontal scroll position. Default 0.
  56335. * @param {string=} start-y Initial vertical scroll position. Default 0.
  56336. * @param {expression=} on-scroll Expression to evaluate when the content is scrolled.
  56337. * @param {expression=} on-scroll-complete Expression to evaluate when a scroll action completes. Has access to 'scrollLeft' and 'scrollTop' locals.
  56338. * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges
  56339. * of the content. Defaults to true on iOS, false on Android.
  56340. * @param {number=} scroll-event-interval Number of milliseconds between each firing of the 'on-scroll' expression. Default 10.
  56341. */
  56342. IonicModule
  56343. .directive('ionContent', [
  56344. '$timeout',
  56345. '$controller',
  56346. '$ionicBind',
  56347. '$ionicConfig',
  56348. function($timeout, $controller, $ionicBind, $ionicConfig) {
  56349. return {
  56350. restrict: 'E',
  56351. require: '^?ionNavView',
  56352. scope: true,
  56353. priority: 800,
  56354. compile: function(element, attr) {
  56355. var innerElement;
  56356. var scrollCtrl;
  56357. element.addClass('scroll-content ionic-scroll');
  56358. if (attr.scroll != 'false') {
  56359. //We cannot use normal transclude here because it breaks element.data()
  56360. //inheritance on compile
  56361. innerElement = jqLite('<div class="scroll"></div>');
  56362. innerElement.append(element.contents());
  56363. element.append(innerElement);
  56364. } else {
  56365. element.addClass('scroll-content-false');
  56366. }
  56367. var nativeScrolling = attr.overflowScroll !== "false" && (attr.overflowScroll === "true" || !$ionicConfig.scrolling.jsScrolling());
  56368. // collection-repeat requires JS scrolling
  56369. if (nativeScrolling) {
  56370. nativeScrolling = !element[0].querySelector('[collection-repeat]');
  56371. }
  56372. return { pre: prelink };
  56373. function prelink($scope, $element, $attr) {
  56374. var parentScope = $scope.$parent;
  56375. $scope.$watch(function() {
  56376. return (parentScope.$hasHeader ? ' has-header' : '') +
  56377. (parentScope.$hasSubheader ? ' has-subheader' : '') +
  56378. (parentScope.$hasFooter ? ' has-footer' : '') +
  56379. (parentScope.$hasSubfooter ? ' has-subfooter' : '') +
  56380. (parentScope.$hasTabs ? ' has-tabs' : '') +
  56381. (parentScope.$hasTabsTop ? ' has-tabs-top' : '');
  56382. }, function(className, oldClassName) {
  56383. $element.removeClass(oldClassName);
  56384. $element.addClass(className);
  56385. });
  56386. //Only this ionContent should use these variables from parent scopes
  56387. $scope.$hasHeader = $scope.$hasSubheader =
  56388. $scope.$hasFooter = $scope.$hasSubfooter =
  56389. $scope.$hasTabs = $scope.$hasTabsTop =
  56390. false;
  56391. $ionicBind($scope, $attr, {
  56392. $onScroll: '&onScroll',
  56393. $onScrollComplete: '&onScrollComplete',
  56394. hasBouncing: '@',
  56395. padding: '@',
  56396. direction: '@',
  56397. scrollbarX: '@',
  56398. scrollbarY: '@',
  56399. startX: '@',
  56400. startY: '@',
  56401. scrollEventInterval: '@'
  56402. });
  56403. $scope.direction = $scope.direction || 'y';
  56404. if (isDefined($attr.padding)) {
  56405. $scope.$watch($attr.padding, function(newVal) {
  56406. (innerElement || $element).toggleClass('padding', !!newVal);
  56407. });
  56408. }
  56409. if ($attr.scroll === "false") {
  56410. //do nothing
  56411. } else {
  56412. var scrollViewOptions = {};
  56413. // determined in compile phase above
  56414. if (nativeScrolling) {
  56415. // use native scrolling
  56416. $element.addClass('overflow-scroll');
  56417. scrollViewOptions = {
  56418. el: $element[0],
  56419. delegateHandle: attr.delegateHandle,
  56420. startX: $scope.$eval($scope.startX) || 0,
  56421. startY: $scope.$eval($scope.startY) || 0,
  56422. nativeScrolling: true
  56423. };
  56424. } else {
  56425. // Use JS scrolling
  56426. scrollViewOptions = {
  56427. el: $element[0],
  56428. delegateHandle: attr.delegateHandle,
  56429. locking: (attr.locking || 'true') === 'true',
  56430. bouncing: $scope.$eval($scope.hasBouncing),
  56431. startX: $scope.$eval($scope.startX) || 0,
  56432. startY: $scope.$eval($scope.startY) || 0,
  56433. scrollbarX: $scope.$eval($scope.scrollbarX) !== false,
  56434. scrollbarY: $scope.$eval($scope.scrollbarY) !== false,
  56435. scrollingX: $scope.direction.indexOf('x') >= 0,
  56436. scrollingY: $scope.direction.indexOf('y') >= 0,
  56437. scrollEventInterval: parseInt($scope.scrollEventInterval, 10) || 10,
  56438. scrollingComplete: onScrollComplete
  56439. };
  56440. }
  56441. // init scroll controller with appropriate options
  56442. scrollCtrl = $controller('$ionicScroll', {
  56443. $scope: $scope,
  56444. scrollViewOptions: scrollViewOptions
  56445. });
  56446. $scope.scrollCtrl = scrollCtrl;
  56447. $scope.$on('$destroy', function() {
  56448. if (scrollViewOptions) {
  56449. scrollViewOptions.scrollingComplete = noop;
  56450. delete scrollViewOptions.el;
  56451. }
  56452. innerElement = null;
  56453. $element = null;
  56454. attr.$$element = null;
  56455. });
  56456. }
  56457. function onScrollComplete() {
  56458. $scope.$onScrollComplete({
  56459. scrollTop: scrollCtrl.scrollView.__scrollTop,
  56460. scrollLeft: scrollCtrl.scrollView.__scrollLeft
  56461. });
  56462. }
  56463. }
  56464. }
  56465. };
  56466. }]);
  56467. /**
  56468. * @ngdoc directive
  56469. * @name exposeAsideWhen
  56470. * @module ionic
  56471. * @restrict A
  56472. * @parent ionic.directive:ionSideMenus
  56473. *
  56474. * @description
  56475. * It is common for a tablet application to hide a menu when in portrait mode, but to show the
  56476. * same menu on the left side when the tablet is in landscape mode. The `exposeAsideWhen` attribute
  56477. * directive can be used to accomplish a similar interface.
  56478. *
  56479. * By default, side menus are hidden underneath its side menu content, and can be opened by either
  56480. * swiping the content left or right, or toggling a button to show the side menu. However, by adding the
  56481. * `exposeAsideWhen` attribute directive to an {@link ionic.directive:ionSideMenu} element directive,
  56482. * a side menu can be given instructions on "when" the menu should be exposed (always viewable). For
  56483. * example, the `expose-aside-when="large"` attribute will keep the side menu hidden when the viewport's
  56484. * width is less than `768px`, but when the viewport's width is `768px` or greater, the menu will then
  56485. * always be shown and can no longer be opened or closed like it could when it was hidden for smaller
  56486. * viewports.
  56487. *
  56488. * Using `large` as the attribute's value is a shortcut value to `(min-width:768px)` since it is
  56489. * the most common use-case. However, for added flexibility, any valid media query could be added
  56490. * as the value, such as `(min-width:600px)` or even multiple queries such as
  56491. * `(min-width:750px) and (max-width:1200px)`.
  56492. * @usage
  56493. * ```html
  56494. * <ion-side-menus>
  56495. * <!-- Center content -->
  56496. * <ion-side-menu-content>
  56497. * </ion-side-menu-content>
  56498. *
  56499. * <!-- Left menu -->
  56500. * <ion-side-menu expose-aside-when="large">
  56501. * </ion-side-menu>
  56502. * </ion-side-menus>
  56503. * ```
  56504. * For a complete side menu example, see the
  56505. * {@link ionic.directive:ionSideMenus} documentation.
  56506. */
  56507. IonicModule.directive('exposeAsideWhen', ['$window', function($window) {
  56508. return {
  56509. restrict: 'A',
  56510. require: '^ionSideMenus',
  56511. link: function($scope, $element, $attr, sideMenuCtrl) {
  56512. var prevInnerWidth = $window.innerWidth;
  56513. var prevInnerHeight = $window.innerHeight;
  56514. ionic.on('resize', function() {
  56515. if (prevInnerWidth === $window.innerWidth && prevInnerHeight === $window.innerHeight) {
  56516. return;
  56517. }
  56518. prevInnerWidth = $window.innerWidth;
  56519. prevInnerHeight = $window.innerHeight;
  56520. onResize();
  56521. }, $window);
  56522. function checkAsideExpose() {
  56523. var mq = $attr.exposeAsideWhen == 'large' ? '(min-width:768px)' : $attr.exposeAsideWhen;
  56524. sideMenuCtrl.exposeAside($window.matchMedia(mq).matches);
  56525. sideMenuCtrl.activeAsideResizing(false);
  56526. }
  56527. function onResize() {
  56528. sideMenuCtrl.activeAsideResizing(true);
  56529. debouncedCheck();
  56530. }
  56531. var debouncedCheck = ionic.debounce(function() {
  56532. $scope.$apply(checkAsideExpose);
  56533. }, 300, false);
  56534. $scope.$evalAsync(checkAsideExpose);
  56535. }
  56536. };
  56537. }]);
  56538. var GESTURE_DIRECTIVES = 'onHold onTap onDoubleTap onTouch onRelease onDragStart onDrag onDragEnd onDragUp onDragRight onDragDown onDragLeft onSwipe onSwipeUp onSwipeRight onSwipeDown onSwipeLeft'.split(' ');
  56539. GESTURE_DIRECTIVES.forEach(function(name) {
  56540. IonicModule.directive(name, gestureDirective(name));
  56541. });
  56542. /**
  56543. * @ngdoc directive
  56544. * @name onHold
  56545. * @module ionic
  56546. * @restrict A
  56547. *
  56548. * @description
  56549. * Touch stays at the same location for 500ms. Similar to long touch events available for AngularJS and jQuery.
  56550. *
  56551. * @usage
  56552. * ```html
  56553. * <button on-hold="onHold()" class="button">Test</button>
  56554. * ```
  56555. */
  56556. /**
  56557. * @ngdoc directive
  56558. * @name onTap
  56559. * @module ionic
  56560. * @restrict A
  56561. *
  56562. * @description
  56563. * Quick touch at a location. If the duration of the touch goes
  56564. * longer than 250ms it is no longer a tap gesture.
  56565. *
  56566. * @usage
  56567. * ```html
  56568. * <button on-tap="onTap()" class="button">Test</button>
  56569. * ```
  56570. */
  56571. /**
  56572. * @ngdoc directive
  56573. * @name onDoubleTap
  56574. * @module ionic
  56575. * @restrict A
  56576. *
  56577. * @description
  56578. * Double tap touch at a location.
  56579. *
  56580. * @usage
  56581. * ```html
  56582. * <button on-double-tap="onDoubleTap()" class="button">Test</button>
  56583. * ```
  56584. */
  56585. /**
  56586. * @ngdoc directive
  56587. * @name onTouch
  56588. * @module ionic
  56589. * @restrict A
  56590. *
  56591. * @description
  56592. * Called immediately when the user first begins a touch. This
  56593. * gesture does not wait for a touchend/mouseup.
  56594. *
  56595. * @usage
  56596. * ```html
  56597. * <button on-touch="onTouch()" class="button">Test</button>
  56598. * ```
  56599. */
  56600. /**
  56601. * @ngdoc directive
  56602. * @name onRelease
  56603. * @module ionic
  56604. * @restrict A
  56605. *
  56606. * @description
  56607. * Called when the user ends a touch.
  56608. *
  56609. * @usage
  56610. * ```html
  56611. * <button on-release="onRelease()" class="button">Test</button>
  56612. * ```
  56613. */
  56614. /**
  56615. * @ngdoc directive
  56616. * @name onDragStart
  56617. * @module ionic
  56618. * @restrict A
  56619. *
  56620. * @description
  56621. * Called when a drag gesture has started.
  56622. *
  56623. * @usage
  56624. * ```html
  56625. * <button on-drag-start="onDragStart()" class="button">Test</button>
  56626. * ```
  56627. */
  56628. /**
  56629. * @ngdoc directive
  56630. * @name onDrag
  56631. * @module ionic
  56632. * @restrict A
  56633. *
  56634. * @description
  56635. * Move with one touch around on the page. Blocking the scrolling when
  56636. * moving left and right is a good practice. When all the drag events are
  56637. * blocking you disable scrolling on that area.
  56638. *
  56639. * @usage
  56640. * ```html
  56641. * <button on-drag="onDrag()" class="button">Test</button>
  56642. * ```
  56643. */
  56644. /**
  56645. * @ngdoc directive
  56646. * @name onDragEnd
  56647. * @module ionic
  56648. * @restrict A
  56649. *
  56650. * @description
  56651. * Called when a drag gesture has ended.
  56652. *
  56653. * @usage
  56654. * ```html
  56655. * <button on-drag-end="onDragEnd()" class="button">Test</button>
  56656. * ```
  56657. */
  56658. /**
  56659. * @ngdoc directive
  56660. * @name onDragUp
  56661. * @module ionic
  56662. * @restrict A
  56663. *
  56664. * @description
  56665. * Called when the element is dragged up.
  56666. *
  56667. * @usage
  56668. * ```html
  56669. * <button on-drag-up="onDragUp()" class="button">Test</button>
  56670. * ```
  56671. */
  56672. /**
  56673. * @ngdoc directive
  56674. * @name onDragRight
  56675. * @module ionic
  56676. * @restrict A
  56677. *
  56678. * @description
  56679. * Called when the element is dragged to the right.
  56680. *
  56681. * @usage
  56682. * ```html
  56683. * <button on-drag-right="onDragRight()" class="button">Test</button>
  56684. * ```
  56685. */
  56686. /**
  56687. * @ngdoc directive
  56688. * @name onDragDown
  56689. * @module ionic
  56690. * @restrict A
  56691. *
  56692. * @description
  56693. * Called when the element is dragged down.
  56694. *
  56695. * @usage
  56696. * ```html
  56697. * <button on-drag-down="onDragDown()" class="button">Test</button>
  56698. * ```
  56699. */
  56700. /**
  56701. * @ngdoc directive
  56702. * @name onDragLeft
  56703. * @module ionic
  56704. * @restrict A
  56705. *
  56706. * @description
  56707. * Called when the element is dragged to the left.
  56708. *
  56709. * @usage
  56710. * ```html
  56711. * <button on-drag-left="onDragLeft()" class="button">Test</button>
  56712. * ```
  56713. */
  56714. /**
  56715. * @ngdoc directive
  56716. * @name onSwipe
  56717. * @module ionic
  56718. * @restrict A
  56719. *
  56720. * @description
  56721. * Called when a moving touch has a high velocity in any direction.
  56722. *
  56723. * @usage
  56724. * ```html
  56725. * <button on-swipe="onSwipe()" class="button">Test</button>
  56726. * ```
  56727. */
  56728. /**
  56729. * @ngdoc directive
  56730. * @name onSwipeUp
  56731. * @module ionic
  56732. * @restrict A
  56733. *
  56734. * @description
  56735. * Called when a moving touch has a high velocity moving up.
  56736. *
  56737. * @usage
  56738. * ```html
  56739. * <button on-swipe-up="onSwipeUp()" class="button">Test</button>
  56740. * ```
  56741. */
  56742. /**
  56743. * @ngdoc directive
  56744. * @name onSwipeRight
  56745. * @module ionic
  56746. * @restrict A
  56747. *
  56748. * @description
  56749. * Called when a moving touch has a high velocity moving to the right.
  56750. *
  56751. * @usage
  56752. * ```html
  56753. * <button on-swipe-right="onSwipeRight()" class="button">Test</button>
  56754. * ```
  56755. */
  56756. /**
  56757. * @ngdoc directive
  56758. * @name onSwipeDown
  56759. * @module ionic
  56760. * @restrict A
  56761. *
  56762. * @description
  56763. * Called when a moving touch has a high velocity moving down.
  56764. *
  56765. * @usage
  56766. * ```html
  56767. * <button on-swipe-down="onSwipeDown()" class="button">Test</button>
  56768. * ```
  56769. */
  56770. /**
  56771. * @ngdoc directive
  56772. * @name onSwipeLeft
  56773. * @module ionic
  56774. * @restrict A
  56775. *
  56776. * @description
  56777. * Called when a moving touch has a high velocity moving to the left.
  56778. *
  56779. * @usage
  56780. * ```html
  56781. * <button on-swipe-left="onSwipeLeft()" class="button">Test</button>
  56782. * ```
  56783. */
  56784. function gestureDirective(directiveName) {
  56785. return ['$ionicGesture', '$parse', function($ionicGesture, $parse) {
  56786. var eventType = directiveName.substr(2).toLowerCase();
  56787. return function(scope, element, attr) {
  56788. var fn = $parse( attr[directiveName] );
  56789. var listener = function(ev) {
  56790. scope.$apply(function() {
  56791. fn(scope, {
  56792. $event: ev
  56793. });
  56794. });
  56795. };
  56796. var gesture = $ionicGesture.on(eventType, listener, element);
  56797. scope.$on('$destroy', function() {
  56798. $ionicGesture.off(gesture, eventType, listener);
  56799. });
  56800. };
  56801. }];
  56802. }
  56803. IonicModule
  56804. //.directive('ionHeaderBar', tapScrollToTopDirective())
  56805. /**
  56806. * @ngdoc directive
  56807. * @name ionHeaderBar
  56808. * @module ionic
  56809. * @restrict E
  56810. *
  56811. * @description
  56812. * Adds a fixed header bar above some content.
  56813. *
  56814. * Can also be a subheader (lower down) if the 'bar-subheader' class is applied.
  56815. * See [the header CSS docs](/docs/components/#subheader).
  56816. *
  56817. * @param {string=} align-title How to align the title. By default the title
  56818. * will be aligned the same as how the platform aligns its titles (iOS centers
  56819. * titles, Android aligns them left).
  56820. * Available: 'left', 'right', or 'center'. Defaults to the same as the platform.
  56821. * @param {boolean=} no-tap-scroll By default, the header bar will scroll the
  56822. * content to the top when tapped. Set no-tap-scroll to true to disable this
  56823. * behavior.
  56824. * Available: true or false. Defaults to false.
  56825. *
  56826. * @usage
  56827. * ```html
  56828. * <ion-header-bar align-title="left" class="bar-positive">
  56829. * <div class="buttons">
  56830. * <button class="button" ng-click="doSomething()">Left Button</button>
  56831. * </div>
  56832. * <h1 class="title">Title!</h1>
  56833. * <div class="buttons">
  56834. * <button class="button">Right Button</button>
  56835. * </div>
  56836. * </ion-header-bar>
  56837. * <ion-content class="has-header">
  56838. * Some content!
  56839. * </ion-content>
  56840. * ```
  56841. */
  56842. .directive('ionHeaderBar', headerFooterBarDirective(true))
  56843. /**
  56844. * @ngdoc directive
  56845. * @name ionFooterBar
  56846. * @module ionic
  56847. * @restrict E
  56848. *
  56849. * @description
  56850. * Adds a fixed footer bar below some content.
  56851. *
  56852. * Can also be a subfooter (higher up) if the 'bar-subfooter' class is applied.
  56853. * See [the footer CSS docs](/docs/components/#footer).
  56854. *
  56855. * Note: If you use ionFooterBar in combination with ng-if, the surrounding content
  56856. * will not align correctly. This will be fixed soon.
  56857. *
  56858. * @param {string=} align-title Where to align the title.
  56859. * Available: 'left', 'right', or 'center'. Defaults to 'center'.
  56860. *
  56861. * @usage
  56862. * ```html
  56863. * <ion-content class="has-footer">
  56864. * Some content!
  56865. * </ion-content>
  56866. * <ion-footer-bar align-title="left" class="bar-assertive">
  56867. * <div class="buttons">
  56868. * <button class="button">Left Button</button>
  56869. * </div>
  56870. * <h1 class="title">Title!</h1>
  56871. * <div class="buttons" ng-click="doSomething()">
  56872. * <button class="button">Right Button</button>
  56873. * </div>
  56874. * </ion-footer-bar>
  56875. * ```
  56876. */
  56877. .directive('ionFooterBar', headerFooterBarDirective(false));
  56878. function tapScrollToTopDirective() { //eslint-disable-line no-unused-vars
  56879. return ['$ionicScrollDelegate', function($ionicScrollDelegate) {
  56880. return {
  56881. restrict: 'E',
  56882. link: function($scope, $element, $attr) {
  56883. if ($attr.noTapScroll == 'true') {
  56884. return;
  56885. }
  56886. ionic.on('tap', onTap, $element[0]);
  56887. $scope.$on('$destroy', function() {
  56888. ionic.off('tap', onTap, $element[0]);
  56889. });
  56890. function onTap(e) {
  56891. var depth = 3;
  56892. var current = e.target;
  56893. //Don't scroll to top in certain cases
  56894. while (depth-- && current) {
  56895. if (current.classList.contains('button') ||
  56896. current.tagName.match(/input|textarea|select/i) ||
  56897. current.isContentEditable) {
  56898. return;
  56899. }
  56900. current = current.parentNode;
  56901. }
  56902. var touch = e.gesture && e.gesture.touches[0] || e.detail.touches[0];
  56903. var bounds = $element[0].getBoundingClientRect();
  56904. if (ionic.DomUtil.rectContains(
  56905. touch.pageX, touch.pageY,
  56906. bounds.left, bounds.top - 20,
  56907. bounds.left + bounds.width, bounds.top + bounds.height
  56908. )) {
  56909. $ionicScrollDelegate.scrollTop(true);
  56910. }
  56911. }
  56912. }
  56913. };
  56914. }];
  56915. }
  56916. function headerFooterBarDirective(isHeader) {
  56917. return ['$document', '$timeout', function($document, $timeout) {
  56918. return {
  56919. restrict: 'E',
  56920. controller: '$ionicHeaderBar',
  56921. compile: function(tElement) {
  56922. tElement.addClass(isHeader ? 'bar bar-header' : 'bar bar-footer');
  56923. // top style tabs? if so, remove bottom border for seamless display
  56924. $timeout(function() {
  56925. if (isHeader && $document[0].getElementsByClassName('tabs-top').length) tElement.addClass('has-tabs-top');
  56926. });
  56927. return { pre: prelink };
  56928. function prelink($scope, $element, $attr, ctrl) {
  56929. if (isHeader) {
  56930. $scope.$watch(function() { return $element[0].className; }, function(value) {
  56931. var isShown = value.indexOf('ng-hide') === -1;
  56932. var isSubheader = value.indexOf('bar-subheader') !== -1;
  56933. $scope.$hasHeader = isShown && !isSubheader;
  56934. $scope.$hasSubheader = isShown && isSubheader;
  56935. $scope.$emit('$ionicSubheader', $scope.$hasSubheader);
  56936. });
  56937. $scope.$on('$destroy', function() {
  56938. delete $scope.$hasHeader;
  56939. delete $scope.$hasSubheader;
  56940. });
  56941. ctrl.align();
  56942. $scope.$on('$ionicHeader.align', function() {
  56943. ionic.requestAnimationFrame(function() {
  56944. ctrl.align();
  56945. });
  56946. });
  56947. } else {
  56948. $scope.$watch(function() { return $element[0].className; }, function(value) {
  56949. var isShown = value.indexOf('ng-hide') === -1;
  56950. var isSubfooter = value.indexOf('bar-subfooter') !== -1;
  56951. $scope.$hasFooter = isShown && !isSubfooter;
  56952. $scope.$hasSubfooter = isShown && isSubfooter;
  56953. });
  56954. $scope.$on('$destroy', function() {
  56955. delete $scope.$hasFooter;
  56956. delete $scope.$hasSubfooter;
  56957. });
  56958. $scope.$watch('$hasTabs', function(val) {
  56959. $element.toggleClass('has-tabs', !!val);
  56960. });
  56961. ctrl.align();
  56962. $scope.$on('$ionicFooter.align', function() {
  56963. ionic.requestAnimationFrame(function() {
  56964. ctrl.align();
  56965. });
  56966. });
  56967. }
  56968. }
  56969. }
  56970. };
  56971. }];
  56972. }
  56973. /**
  56974. * @ngdoc directive
  56975. * @name ionInfiniteScroll
  56976. * @module ionic
  56977. * @parent ionic.directive:ionContent, ionic.directive:ionScroll
  56978. * @restrict E
  56979. *
  56980. * @description
  56981. * The ionInfiniteScroll directive allows you to call a function whenever
  56982. * the user gets to the bottom of the page or near the bottom of the page.
  56983. *
  56984. * The expression you pass in for `on-infinite` is called when the user scrolls
  56985. * greater than `distance` away from the bottom of the content. Once `on-infinite`
  56986. * is done loading new data, it should broadcast the `scroll.infiniteScrollComplete`
  56987. * event from your controller (see below example).
  56988. *
  56989. * @param {expression} on-infinite What to call when the scroller reaches the
  56990. * bottom.
  56991. * @param {string=} distance The distance from the bottom that the scroll must
  56992. * reach to trigger the on-infinite expression. Default: 1%.
  56993. * @param {string=} spinner The {@link ionic.directive:ionSpinner} to show while loading. The SVG
  56994. * {@link ionic.directive:ionSpinner} is now the default, replacing rotating font icons.
  56995. * @param {string=} icon The icon to show while loading. Default: 'ion-load-d'. This is depreicated
  56996. * in favor of the SVG {@link ionic.directive:ionSpinner}.
  56997. * @param {boolean=} immediate-check Whether to check the infinite scroll bounds immediately on load.
  56998. *
  56999. * @usage
  57000. * ```html
  57001. * <ion-content ng-controller="MyController">
  57002. * <ion-list>
  57003. * ....
  57004. * ....
  57005. * </ion-list>
  57006. *
  57007. * <ion-infinite-scroll
  57008. * on-infinite="loadMore()"
  57009. * distance="1%">
  57010. * </ion-infinite-scroll>
  57011. * </ion-content>
  57012. * ```
  57013. * ```js
  57014. * function MyController($scope, $http) {
  57015. * $scope.items = [];
  57016. * $scope.loadMore = function() {
  57017. * $http.get('/more-items').success(function(items) {
  57018. * useItems(items);
  57019. * $scope.$broadcast('scroll.infiniteScrollComplete');
  57020. * });
  57021. * };
  57022. *
  57023. * $scope.$on('$stateChangeSuccess', function() {
  57024. * $scope.loadMore();
  57025. * });
  57026. * }
  57027. * ```
  57028. *
  57029. * An easy to way to stop infinite scroll once there is no more data to load
  57030. * is to use angular's `ng-if` directive:
  57031. *
  57032. * ```html
  57033. * <ion-infinite-scroll
  57034. * ng-if="moreDataCanBeLoaded()"
  57035. * icon="ion-loading-c"
  57036. * on-infinite="loadMoreData()">
  57037. * </ion-infinite-scroll>
  57038. * ```
  57039. */
  57040. IonicModule
  57041. .directive('ionInfiniteScroll', ['$timeout', function($timeout) {
  57042. return {
  57043. restrict: 'E',
  57044. require: ['?^$ionicScroll', 'ionInfiniteScroll'],
  57045. template: function($element, $attrs) {
  57046. if ($attrs.icon) return '<i class="icon {{icon()}} icon-refreshing {{scrollingType}}"></i>';
  57047. return '<ion-spinner icon="{{spinner()}}"></ion-spinner>';
  57048. },
  57049. scope: true,
  57050. controller: '$ionInfiniteScroll',
  57051. link: function($scope, $element, $attrs, ctrls) {
  57052. var infiniteScrollCtrl = ctrls[1];
  57053. var scrollCtrl = infiniteScrollCtrl.scrollCtrl = ctrls[0];
  57054. var jsScrolling = infiniteScrollCtrl.jsScrolling = !scrollCtrl.isNative();
  57055. // if this view is not beneath a scrollCtrl, it can't be injected, proceed w/ native scrolling
  57056. if (jsScrolling) {
  57057. infiniteScrollCtrl.scrollView = scrollCtrl.scrollView;
  57058. $scope.scrollingType = 'js-scrolling';
  57059. //bind to JS scroll events
  57060. scrollCtrl.$element.on('scroll', infiniteScrollCtrl.checkBounds);
  57061. } else {
  57062. // grabbing the scrollable element, to determine dimensions, and current scroll pos
  57063. var scrollEl = ionic.DomUtil.getParentOrSelfWithClass($element[0].parentNode, 'overflow-scroll');
  57064. infiniteScrollCtrl.scrollEl = scrollEl;
  57065. // if there's no scroll controller, and no overflow scroll div, infinite scroll wont work
  57066. if (!scrollEl) {
  57067. throw 'Infinite scroll must be used inside a scrollable div';
  57068. }
  57069. //bind to native scroll events
  57070. infiniteScrollCtrl.scrollEl.addEventListener('scroll', infiniteScrollCtrl.checkBounds);
  57071. }
  57072. // Optionally check bounds on start after scrollView is fully rendered
  57073. var doImmediateCheck = isDefined($attrs.immediateCheck) ? $scope.$eval($attrs.immediateCheck) : true;
  57074. if (doImmediateCheck) {
  57075. $timeout(function() { infiniteScrollCtrl.checkBounds(); });
  57076. }
  57077. }
  57078. };
  57079. }]);
  57080. /**
  57081. * @ngdoc directive
  57082. * @name ionInput
  57083. * @parent ionic.directive:ionList
  57084. * @module ionic
  57085. * @restrict E
  57086. * Creates a text input group that can easily be focused
  57087. *
  57088. * @usage
  57089. *
  57090. * ```html
  57091. * <ion-list>
  57092. * <ion-input>
  57093. * <input type="text" placeholder="First Name">
  57094. * </ion-input>
  57095. *
  57096. * <ion-input>
  57097. * <ion-label>Username</ion-label>
  57098. * <input type="text">
  57099. * </ion-input>
  57100. * </ion-list>
  57101. * ```
  57102. */
  57103. var labelIds = -1;
  57104. IonicModule
  57105. .directive('ionInput', [function() {
  57106. return {
  57107. restrict: 'E',
  57108. controller: ['$scope', '$element', function($scope, $element) {
  57109. this.$scope = $scope;
  57110. this.$element = $element;
  57111. this.setInputAriaLabeledBy = function(id) {
  57112. var inputs = $element[0].querySelectorAll('input,textarea');
  57113. inputs.length && inputs[0].setAttribute('aria-labelledby', id);
  57114. };
  57115. this.focus = function() {
  57116. var inputs = $element[0].querySelectorAll('input,textarea');
  57117. inputs.length && inputs[0].focus();
  57118. };
  57119. }]
  57120. };
  57121. }]);
  57122. /**
  57123. * @ngdoc directive
  57124. * @name ionLabel
  57125. * @parent ionic.directive:ionList
  57126. * @module ionic
  57127. * @restrict E
  57128. *
  57129. * New in Ionic 1.2. It is strongly recommended that you use `<ion-label>` in place
  57130. * of any `<label>` elements for maximum cross-browser support and performance.
  57131. *
  57132. * Creates a label for a form input.
  57133. *
  57134. * @usage
  57135. *
  57136. * ```html
  57137. * <ion-list>
  57138. * <ion-input>
  57139. * <ion-label>Username</ion-label>
  57140. * <input type="text">
  57141. * </ion-input>
  57142. * </ion-list>
  57143. * ```
  57144. */
  57145. IonicModule
  57146. .directive('ionLabel', [function() {
  57147. return {
  57148. restrict: 'E',
  57149. require: '?^ionInput',
  57150. compile: function() {
  57151. return function link($scope, $element, $attrs, ionInputCtrl) {
  57152. var element = $element[0];
  57153. $element.addClass('input-label');
  57154. $element.attr('aria-label', $element.text());
  57155. var id = element.id || '_label-' + ++labelIds;
  57156. if (!element.id) {
  57157. $element.attr('id', id);
  57158. }
  57159. if (ionInputCtrl) {
  57160. ionInputCtrl.setInputAriaLabeledBy(id);
  57161. $element.on('click', function() {
  57162. ionInputCtrl.focus();
  57163. });
  57164. }
  57165. };
  57166. }
  57167. };
  57168. }]);
  57169. /**
  57170. * Input label adds accessibility to <span class="input-label">.
  57171. */
  57172. IonicModule
  57173. .directive('inputLabel', [function() {
  57174. return {
  57175. restrict: 'C',
  57176. require: '?^ionInput',
  57177. compile: function() {
  57178. return function link($scope, $element, $attrs, ionInputCtrl) {
  57179. var element = $element[0];
  57180. $element.attr('aria-label', $element.text());
  57181. var id = element.id || '_label-' + ++labelIds;
  57182. if (!element.id) {
  57183. $element.attr('id', id);
  57184. }
  57185. if (ionInputCtrl) {
  57186. ionInputCtrl.setInputAriaLabeledBy(id);
  57187. }
  57188. };
  57189. }
  57190. };
  57191. }]);
  57192. /**
  57193. * @ngdoc directive
  57194. * @name ionItem
  57195. * @parent ionic.directive:ionList
  57196. * @module ionic
  57197. * @restrict E
  57198. * Creates a list-item that can easily be swiped,
  57199. * deleted, reordered, edited, and more.
  57200. *
  57201. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57202. *
  57203. * Can be assigned any item class name. See the
  57204. * [list CSS documentation](/docs/components/#list).
  57205. *
  57206. * @usage
  57207. *
  57208. * ```html
  57209. * <ion-list>
  57210. * <ion-item>Hello!</ion-item>
  57211. * <ion-item href="#/detail">
  57212. * Link to detail page
  57213. * </ion-item>
  57214. * </ion-list>
  57215. * ```
  57216. */
  57217. IonicModule
  57218. .directive('ionItem', ['$$rAF', function($$rAF) {
  57219. return {
  57220. restrict: 'E',
  57221. controller: ['$scope', '$element', function($scope, $element) {
  57222. this.$scope = $scope;
  57223. this.$element = $element;
  57224. }],
  57225. scope: true,
  57226. compile: function($element, $attrs) {
  57227. var isAnchor = isDefined($attrs.href) ||
  57228. isDefined($attrs.ngHref) ||
  57229. isDefined($attrs.uiSref);
  57230. var isComplexItem = isAnchor ||
  57231. //Lame way of testing, but we have to know at compile what to do with the element
  57232. /ion-(delete|option|reorder)-button/i.test($element.html());
  57233. if (isComplexItem) {
  57234. var innerElement = jqLite(isAnchor ? '<a></a>' : '<div></div>');
  57235. innerElement.addClass('item-content');
  57236. if (isDefined($attrs.href) || isDefined($attrs.ngHref)) {
  57237. innerElement.attr('ng-href', '{{$href()}}');
  57238. if (isDefined($attrs.target)) {
  57239. innerElement.attr('target', '{{$target()}}');
  57240. }
  57241. }
  57242. innerElement.append($element.contents());
  57243. $element.addClass('item item-complex')
  57244. .append(innerElement);
  57245. } else {
  57246. $element.addClass('item');
  57247. }
  57248. return function link($scope, $element, $attrs) {
  57249. $scope.$href = function() {
  57250. return $attrs.href || $attrs.ngHref;
  57251. };
  57252. $scope.$target = function() {
  57253. return $attrs.target;
  57254. };
  57255. var content = $element[0].querySelector('.item-content');
  57256. if (content) {
  57257. $scope.$on('$collectionRepeatLeave', function() {
  57258. if (content && content.$$ionicOptionsOpen) {
  57259. content.style[ionic.CSS.TRANSFORM] = '';
  57260. content.style[ionic.CSS.TRANSITION] = 'none';
  57261. $$rAF(function() {
  57262. content.style[ionic.CSS.TRANSITION] = '';
  57263. });
  57264. content.$$ionicOptionsOpen = false;
  57265. }
  57266. });
  57267. }
  57268. };
  57269. }
  57270. };
  57271. }]);
  57272. var ITEM_TPL_DELETE_BUTTON =
  57273. '<div class="item-left-edit item-delete enable-pointer-events">' +
  57274. '</div>';
  57275. /**
  57276. * @ngdoc directive
  57277. * @name ionDeleteButton
  57278. * @parent ionic.directive:ionItem
  57279. * @module ionic
  57280. * @restrict E
  57281. * Creates a delete button inside a list item, that is visible when the
  57282. * {@link ionic.directive:ionList ionList parent's} `show-delete` evaluates to true or
  57283. * `$ionicListDelegate.showDelete(true)` is called.
  57284. *
  57285. * Takes any ionicon as a class.
  57286. *
  57287. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57288. *
  57289. * @usage
  57290. *
  57291. * ```html
  57292. * <ion-list show-delete="shouldShowDelete">
  57293. * <ion-item>
  57294. * <ion-delete-button class="ion-minus-circled"></ion-delete-button>
  57295. * Hello, list item!
  57296. * </ion-item>
  57297. * </ion-list>
  57298. * <ion-toggle ng-model="shouldShowDelete">
  57299. * Show Delete?
  57300. * </ion-toggle>
  57301. * ```
  57302. */
  57303. IonicModule
  57304. .directive('ionDeleteButton', function() {
  57305. function stopPropagation(ev) {
  57306. ev.stopPropagation();
  57307. }
  57308. return {
  57309. restrict: 'E',
  57310. require: ['^^ionItem', '^?ionList'],
  57311. //Run before anything else, so we can move it before other directives process
  57312. //its location (eg ngIf relies on the location of the directive in the dom)
  57313. priority: Number.MAX_VALUE,
  57314. compile: function($element, $attr) {
  57315. //Add the classes we need during the compile phase, so that they stay
  57316. //even if something else like ngIf removes the element and re-addss it
  57317. $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);
  57318. return function($scope, $element, $attr, ctrls) {
  57319. var itemCtrl = ctrls[0];
  57320. var listCtrl = ctrls[1];
  57321. var container = jqLite(ITEM_TPL_DELETE_BUTTON);
  57322. container.append($element);
  57323. itemCtrl.$element.append(container).addClass('item-left-editable');
  57324. //Don't bubble click up to main .item
  57325. $element.on('click', stopPropagation);
  57326. init();
  57327. $scope.$on('$ionic.reconnectScope', init);
  57328. function init() {
  57329. listCtrl = listCtrl || $element.controller('ionList');
  57330. if (listCtrl && listCtrl.showDelete()) {
  57331. container.addClass('visible active');
  57332. }
  57333. }
  57334. };
  57335. }
  57336. };
  57337. });
  57338. IonicModule
  57339. .directive('itemFloatingLabel', function() {
  57340. return {
  57341. restrict: 'C',
  57342. link: function(scope, element) {
  57343. var el = element[0];
  57344. var input = el.querySelector('input, textarea');
  57345. var inputLabel = el.querySelector('.input-label');
  57346. if (!input || !inputLabel) return;
  57347. var onInput = function() {
  57348. if (input.value) {
  57349. inputLabel.classList.add('has-input');
  57350. } else {
  57351. inputLabel.classList.remove('has-input');
  57352. }
  57353. };
  57354. input.addEventListener('input', onInput);
  57355. var ngModelCtrl = jqLite(input).controller('ngModel');
  57356. if (ngModelCtrl) {
  57357. ngModelCtrl.$render = function() {
  57358. input.value = ngModelCtrl.$viewValue || '';
  57359. onInput();
  57360. };
  57361. }
  57362. scope.$on('$destroy', function() {
  57363. input.removeEventListener('input', onInput);
  57364. });
  57365. }
  57366. };
  57367. });
  57368. var ITEM_TPL_OPTION_BUTTONS =
  57369. '<div class="item-options invisible">' +
  57370. '</div>';
  57371. /**
  57372. * @ngdoc directive
  57373. * @name ionOptionButton
  57374. * @parent ionic.directive:ionItem
  57375. * @module ionic
  57376. * @restrict E
  57377. * @description
  57378. * Creates an option button inside a list item, that is visible when the item is swiped
  57379. * to the left by the user. Swiped open option buttons can be hidden with
  57380. * {@link ionic.service:$ionicListDelegate#closeOptionButtons $ionicListDelegate.closeOptionButtons}.
  57381. *
  57382. * Can be assigned any button class.
  57383. *
  57384. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57385. *
  57386. * @usage
  57387. *
  57388. * ```html
  57389. * <ion-list>
  57390. * <ion-item>
  57391. * I love kittens!
  57392. * <ion-option-button class="button-positive">Share</ion-option-button>
  57393. * <ion-option-button class="button-assertive">Edit</ion-option-button>
  57394. * </ion-item>
  57395. * </ion-list>
  57396. * ```
  57397. */
  57398. IonicModule.directive('ionOptionButton', [function() {
  57399. function stopPropagation(e) {
  57400. e.stopPropagation();
  57401. }
  57402. return {
  57403. restrict: 'E',
  57404. require: '^ionItem',
  57405. priority: Number.MAX_VALUE,
  57406. compile: function($element, $attr) {
  57407. $attr.$set('class', ($attr['class'] || '') + ' button', true);
  57408. return function($scope, $element, $attr, itemCtrl) {
  57409. if (!itemCtrl.optionsContainer) {
  57410. itemCtrl.optionsContainer = jqLite(ITEM_TPL_OPTION_BUTTONS);
  57411. itemCtrl.$element.append(itemCtrl.optionsContainer);
  57412. }
  57413. itemCtrl.optionsContainer.append($element);
  57414. itemCtrl.$element.addClass('item-right-editable');
  57415. //Don't bubble click up to main .item
  57416. $element.on('click', stopPropagation);
  57417. };
  57418. }
  57419. };
  57420. }]);
  57421. var ITEM_TPL_REORDER_BUTTON =
  57422. '<div data-prevent-scroll="true" class="item-right-edit item-reorder enable-pointer-events">' +
  57423. '</div>';
  57424. /**
  57425. * @ngdoc directive
  57426. * @name ionReorderButton
  57427. * @parent ionic.directive:ionItem
  57428. * @module ionic
  57429. * @restrict E
  57430. * Creates a reorder button inside a list item, that is visible when the
  57431. * {@link ionic.directive:ionList ionList parent's} `show-reorder` evaluates to true or
  57432. * `$ionicListDelegate.showReorder(true)` is called.
  57433. *
  57434. * Can be dragged to reorder items in the list. Takes any ionicon class.
  57435. *
  57436. * Note: Reordering works best when used with `ng-repeat`. Be sure that all `ion-item` children of an `ion-list` are part of the same `ng-repeat` expression.
  57437. *
  57438. * When an item reorder is complete, the expression given in the `on-reorder` attribute is called. The `on-reorder` expression is given two locals that can be used: `$fromIndex` and `$toIndex`. See below for an example.
  57439. *
  57440. * Look at {@link ionic.directive:ionList} for more examples.
  57441. *
  57442. * @usage
  57443. *
  57444. * ```html
  57445. * <ion-list ng-controller="MyCtrl" show-reorder="true">
  57446. * <ion-item ng-repeat="item in items">
  57447. * Item {{item}}
  57448. * <ion-reorder-button class="ion-navicon"
  57449. * on-reorder="moveItem(item, $fromIndex, $toIndex)">
  57450. * </ion-reorder-button>
  57451. * </ion-item>
  57452. * </ion-list>
  57453. * ```
  57454. * ```js
  57455. * function MyCtrl($scope) {
  57456. * $scope.items = [1, 2, 3, 4];
  57457. * $scope.moveItem = function(item, fromIndex, toIndex) {
  57458. * //Move the item in the array
  57459. * $scope.items.splice(fromIndex, 1);
  57460. * $scope.items.splice(toIndex, 0, item);
  57461. * };
  57462. * }
  57463. * ```
  57464. *
  57465. * @param {expression=} on-reorder Expression to call when an item is reordered.
  57466. * Parameters given: $fromIndex, $toIndex.
  57467. */
  57468. IonicModule
  57469. .directive('ionReorderButton', ['$parse', function($parse) {
  57470. return {
  57471. restrict: 'E',
  57472. require: ['^ionItem', '^?ionList'],
  57473. priority: Number.MAX_VALUE,
  57474. compile: function($element, $attr) {
  57475. $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);
  57476. $element[0].setAttribute('data-prevent-scroll', true);
  57477. return function($scope, $element, $attr, ctrls) {
  57478. var itemCtrl = ctrls[0];
  57479. var listCtrl = ctrls[1];
  57480. var onReorderFn = $parse($attr.onReorder);
  57481. $scope.$onReorder = function(oldIndex, newIndex) {
  57482. onReorderFn($scope, {
  57483. $fromIndex: oldIndex,
  57484. $toIndex: newIndex
  57485. });
  57486. };
  57487. // prevent clicks from bubbling up to the item
  57488. if (!$attr.ngClick && !$attr.onClick && !$attr.onclick) {
  57489. $element[0].onclick = function(e) {
  57490. e.stopPropagation();
  57491. return false;
  57492. };
  57493. }
  57494. var container = jqLite(ITEM_TPL_REORDER_BUTTON);
  57495. container.append($element);
  57496. itemCtrl.$element.append(container).addClass('item-right-editable');
  57497. if (listCtrl && listCtrl.showReorder()) {
  57498. container.addClass('visible active');
  57499. }
  57500. };
  57501. }
  57502. };
  57503. }]);
  57504. /**
  57505. * @ngdoc directive
  57506. * @name keyboardAttach
  57507. * @module ionic
  57508. * @restrict A
  57509. *
  57510. * @description
  57511. * keyboard-attach is an attribute directive which will cause an element to float above
  57512. * the keyboard when the keyboard shows. Currently only supports the
  57513. * [ion-footer-bar]({{ page.versionHref }}/api/directive/ionFooterBar/) directive.
  57514. *
  57515. * ### Notes
  57516. * - This directive requires the
  57517. * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard).
  57518. * - On Android not in fullscreen mode, i.e. you have
  57519. * `<preference name="Fullscreen" value="false" />` or no preference in your `config.xml` file,
  57520. * this directive is unnecessary since it is the default behavior.
  57521. * - On iOS, if there is an input in your footer, you will need to set
  57522. * `cordova.plugins.Keyboard.disableScroll(true)`.
  57523. *
  57524. * @usage
  57525. *
  57526. * ```html
  57527. * <ion-footer-bar align-title="left" keyboard-attach class="bar-assertive">
  57528. * <h1 class="title">Title!</h1>
  57529. * </ion-footer-bar>
  57530. * ```
  57531. */
  57532. IonicModule
  57533. .directive('keyboardAttach', function() {
  57534. return function(scope, element) {
  57535. ionic.on('native.keyboardshow', onShow, window);
  57536. ionic.on('native.keyboardhide', onHide, window);
  57537. //deprecated
  57538. ionic.on('native.showkeyboard', onShow, window);
  57539. ionic.on('native.hidekeyboard', onHide, window);
  57540. var scrollCtrl;
  57541. function onShow(e) {
  57542. if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {
  57543. return;
  57544. }
  57545. //for testing
  57546. var keyboardHeight = e.keyboardHeight || (e.detail && e.detail.keyboardHeight);
  57547. element.css('bottom', keyboardHeight + "px");
  57548. scrollCtrl = element.controller('$ionicScroll');
  57549. if (scrollCtrl) {
  57550. scrollCtrl.scrollView.__container.style.bottom = keyboardHeight + keyboardAttachGetClientHeight(element[0]) + "px";
  57551. }
  57552. }
  57553. function onHide() {
  57554. if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {
  57555. return;
  57556. }
  57557. element.css('bottom', '');
  57558. if (scrollCtrl) {
  57559. scrollCtrl.scrollView.__container.style.bottom = '';
  57560. }
  57561. }
  57562. scope.$on('$destroy', function() {
  57563. ionic.off('native.keyboardshow', onShow, window);
  57564. ionic.off('native.keyboardhide', onHide, window);
  57565. //deprecated
  57566. ionic.off('native.showkeyboard', onShow, window);
  57567. ionic.off('native.hidekeyboard', onHide, window);
  57568. });
  57569. };
  57570. });
  57571. function keyboardAttachGetClientHeight(element) {
  57572. return element.clientHeight;
  57573. }
  57574. /**
  57575. * @ngdoc directive
  57576. * @name ionList
  57577. * @module ionic
  57578. * @delegate ionic.service:$ionicListDelegate
  57579. * @codepen JsHjf
  57580. * @restrict E
  57581. * @description
  57582. * The List is a widely used interface element in almost any mobile app, and can include
  57583. * content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.
  57584. *
  57585. * Both the list, which contains items, and the list items themselves can be any HTML
  57586. * element. The containing element requires the `list` class and each list item requires
  57587. * the `item` class.
  57588. *
  57589. * However, using the ionList and ionItem directives make it easy to support various
  57590. * interaction modes such as swipe to edit, drag to reorder, and removing items.
  57591. *
  57592. * Related: {@link ionic.directive:ionItem}, {@link ionic.directive:ionOptionButton}
  57593. * {@link ionic.directive:ionReorderButton}, {@link ionic.directive:ionDeleteButton}, [`list CSS documentation`](/docs/components/#list).
  57594. *
  57595. * @usage
  57596. *
  57597. * Basic Usage:
  57598. *
  57599. * ```html
  57600. * <ion-list>
  57601. * <ion-item ng-repeat="item in items">
  57602. * {% raw %}Hello, {{item}}!{% endraw %}
  57603. * </ion-item>
  57604. * </ion-list>
  57605. * ```
  57606. *
  57607. * Advanced Usage: Thumbnails, Delete buttons, Reordering, Swiping
  57608. *
  57609. * ```html
  57610. * <ion-list ng-controller="MyCtrl"
  57611. * show-delete="shouldShowDelete"
  57612. * show-reorder="shouldShowReorder"
  57613. * can-swipe="listCanSwipe">
  57614. * <ion-item ng-repeat="item in items"
  57615. * class="item-thumbnail-left">
  57616. *
  57617. * {% raw %}<img ng-src="{{item.img}}">
  57618. * <h2>{{item.title}}</h2>
  57619. * <p>{{item.description}}</p>{% endraw %}
  57620. * <ion-option-button class="button-positive"
  57621. * ng-click="share(item)">
  57622. * Share
  57623. * </ion-option-button>
  57624. * <ion-option-button class="button-info"
  57625. * ng-click="edit(item)">
  57626. * Edit
  57627. * </ion-option-button>
  57628. * <ion-delete-button class="ion-minus-circled"
  57629. * ng-click="items.splice($index, 1)">
  57630. * </ion-delete-button>
  57631. * <ion-reorder-button class="ion-navicon"
  57632. * on-reorder="reorderItem(item, $fromIndex, $toIndex)">
  57633. * </ion-reorder-button>
  57634. *
  57635. * </ion-item>
  57636. * </ion-list>
  57637. * ```
  57638. *
  57639. *```javascript
  57640. * app.controller('MyCtrl', function($scope) {
  57641. * $scope.shouldShowDelete = false;
  57642. * $scope.shouldShowReorder = false;
  57643. * $scope.listCanSwipe = true
  57644. * });
  57645. *```
  57646. *
  57647. * @param {string=} delegate-handle The handle used to identify this list with
  57648. * {@link ionic.service:$ionicListDelegate}.
  57649. * @param type {string=} The type of list to use (list-inset or card)
  57650. * @param show-delete {boolean=} Whether the delete buttons for the items in the list are
  57651. * currently shown or hidden.
  57652. * @param show-reorder {boolean=} Whether the reorder buttons for the items in the list are
  57653. * currently shown or hidden.
  57654. * @param can-swipe {boolean=} Whether the items in the list are allowed to be swiped to reveal
  57655. * option buttons. Default: true.
  57656. */
  57657. IonicModule
  57658. .directive('ionList', [
  57659. '$timeout',
  57660. function($timeout) {
  57661. return {
  57662. restrict: 'E',
  57663. require: ['ionList', '^?$ionicScroll'],
  57664. controller: '$ionicList',
  57665. compile: function($element, $attr) {
  57666. var listEl = jqLite('<div class="list">')
  57667. .append($element.contents())
  57668. .addClass($attr.type);
  57669. $element.append(listEl);
  57670. return function($scope, $element, $attrs, ctrls) {
  57671. var listCtrl = ctrls[0];
  57672. var scrollCtrl = ctrls[1];
  57673. // Wait for child elements to render...
  57674. $timeout(init);
  57675. function init() {
  57676. var listView = listCtrl.listView = new ionic.views.ListView({
  57677. el: $element[0],
  57678. listEl: $element.children()[0],
  57679. scrollEl: scrollCtrl && scrollCtrl.element,
  57680. scrollView: scrollCtrl && scrollCtrl.scrollView,
  57681. onReorder: function(el, oldIndex, newIndex) {
  57682. var itemScope = jqLite(el).scope();
  57683. if (itemScope && itemScope.$onReorder) {
  57684. // Make sure onReorder is called in apply cycle,
  57685. // but also make sure it has no conflicts by doing
  57686. // $evalAsync
  57687. $timeout(function() {
  57688. itemScope.$onReorder(oldIndex, newIndex);
  57689. });
  57690. }
  57691. },
  57692. canSwipe: function() {
  57693. return listCtrl.canSwipeItems();
  57694. }
  57695. });
  57696. $scope.$on('$destroy', function() {
  57697. if (listView) {
  57698. listView.deregister && listView.deregister();
  57699. listView = null;
  57700. }
  57701. });
  57702. if (isDefined($attr.canSwipe)) {
  57703. $scope.$watch('!!(' + $attr.canSwipe + ')', function(value) {
  57704. listCtrl.canSwipeItems(value);
  57705. });
  57706. }
  57707. if (isDefined($attr.showDelete)) {
  57708. $scope.$watch('!!(' + $attr.showDelete + ')', function(value) {
  57709. listCtrl.showDelete(value);
  57710. });
  57711. }
  57712. if (isDefined($attr.showReorder)) {
  57713. $scope.$watch('!!(' + $attr.showReorder + ')', function(value) {
  57714. listCtrl.showReorder(value);
  57715. });
  57716. }
  57717. $scope.$watch(function() {
  57718. return listCtrl.showDelete();
  57719. }, function(isShown, wasShown) {
  57720. //Only use isShown=false if it was already shown
  57721. if (!isShown && !wasShown) { return; }
  57722. if (isShown) listCtrl.closeOptionButtons();
  57723. listCtrl.canSwipeItems(!isShown);
  57724. $element.children().toggleClass('list-left-editing', isShown);
  57725. $element.toggleClass('disable-pointer-events', isShown);
  57726. var deleteButton = jqLite($element[0].getElementsByClassName('item-delete'));
  57727. setButtonShown(deleteButton, listCtrl.showDelete);
  57728. });
  57729. $scope.$watch(function() {
  57730. return listCtrl.showReorder();
  57731. }, function(isShown, wasShown) {
  57732. //Only use isShown=false if it was already shown
  57733. if (!isShown && !wasShown) { return; }
  57734. if (isShown) listCtrl.closeOptionButtons();
  57735. listCtrl.canSwipeItems(!isShown);
  57736. $element.children().toggleClass('list-right-editing', isShown);
  57737. $element.toggleClass('disable-pointer-events', isShown);
  57738. var reorderButton = jqLite($element[0].getElementsByClassName('item-reorder'));
  57739. setButtonShown(reorderButton, listCtrl.showReorder);
  57740. });
  57741. function setButtonShown(el, shown) {
  57742. shown() && el.addClass('visible') || el.removeClass('active');
  57743. ionic.requestAnimationFrame(function() {
  57744. shown() && el.addClass('active') || el.removeClass('visible');
  57745. });
  57746. }
  57747. }
  57748. };
  57749. }
  57750. };
  57751. }]);
  57752. /**
  57753. * @ngdoc directive
  57754. * @name menuClose
  57755. * @module ionic
  57756. * @restrict AC
  57757. *
  57758. * @description
  57759. * `menu-close` is an attribute directive that closes a currently opened side menu.
  57760. * Note that by default, navigation transitions will not animate between views when
  57761. * the menu is open. Additionally, this directive will reset the entering view's
  57762. * history stack, making the new page the root of the history stack. This is done
  57763. * to replicate the user experience seen in most side menu implementations, which is
  57764. * to not show the back button at the root of the stack and show only the
  57765. * menu button. We recommend that you also use the `enable-menu-with-back-views="false"`
  57766. * {@link ionic.directive:ionSideMenus} attribute when using the menuClose directive.
  57767. *
  57768. * @usage
  57769. * Below is an example of a link within a side menu. Tapping this link would
  57770. * automatically close the currently opened menu.
  57771. *
  57772. * ```html
  57773. * <a menu-close href="#/home" class="item">Home</a>
  57774. * ```
  57775. *
  57776. * Note that if your destination state uses a resolve and that resolve asynchronously
  57777. * takes longer than a standard transition (300ms), you'll need to set the
  57778. * `nextViewOptions` manually as your resolve completes.
  57779. *
  57780. * ```js
  57781. * $ionicHistory.nextViewOptions({
  57782. * historyRoot: true,
  57783. * disableAnimate: true,
  57784. * expire: 300
  57785. * });
  57786. * ```
  57787. */
  57788. IonicModule
  57789. .directive('menuClose', ['$ionicHistory', '$timeout', function($ionicHistory, $timeout) {
  57790. return {
  57791. restrict: 'AC',
  57792. link: function($scope, $element) {
  57793. $element.bind('click', function() {
  57794. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57795. if (sideMenuCtrl) {
  57796. $ionicHistory.nextViewOptions({
  57797. historyRoot: true,
  57798. disableAnimate: true,
  57799. expire: 300
  57800. });
  57801. // if no transition in 300ms, reset nextViewOptions
  57802. // the expire should take care of it, but will be cancelled in some
  57803. // cases. This directive is an exception to the rules of history.js
  57804. $timeout( function() {
  57805. $ionicHistory.nextViewOptions({
  57806. historyRoot: false,
  57807. disableAnimate: false
  57808. });
  57809. }, 300);
  57810. sideMenuCtrl.close();
  57811. }
  57812. });
  57813. }
  57814. };
  57815. }]);
  57816. /**
  57817. * @ngdoc directive
  57818. * @name menuToggle
  57819. * @module ionic
  57820. * @restrict AC
  57821. *
  57822. * @description
  57823. * Toggle a side menu on the given side.
  57824. *
  57825. * @usage
  57826. * Below is an example of a link within a nav bar. Tapping this button
  57827. * would open the given side menu, and tapping it again would close it.
  57828. *
  57829. * ```html
  57830. * <ion-nav-bar>
  57831. * <ion-nav-buttons side="left">
  57832. * <!-- Toggle left side menu -->
  57833. * <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  57834. * </ion-nav-buttons>
  57835. * <ion-nav-buttons side="right">
  57836. * <!-- Toggle right side menu -->
  57837. * <button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
  57838. * </ion-nav-buttons>
  57839. * </ion-nav-bar>
  57840. * ```
  57841. *
  57842. * ### Button Hidden On Child Views
  57843. * By default, the menu toggle button will only appear on a root
  57844. * level side-menu page. Navigating in to child views will hide the menu-
  57845. * toggle button. They can be made visible on child pages by setting the
  57846. * enable-menu-with-back-views attribute of the {@link ionic.directive:ionSideMenus}
  57847. * directive to true.
  57848. *
  57849. * ```html
  57850. * <ion-side-menus enable-menu-with-back-views="true">
  57851. * ```
  57852. */
  57853. IonicModule
  57854. .directive('menuToggle', function() {
  57855. return {
  57856. restrict: 'AC',
  57857. link: function($scope, $element, $attr) {
  57858. $scope.$on('$ionicView.beforeEnter', function(ev, viewData) {
  57859. if (viewData.enableBack) {
  57860. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57861. if (!sideMenuCtrl.enableMenuWithBackViews()) {
  57862. $element.addClass('hide');
  57863. }
  57864. } else {
  57865. $element.removeClass('hide');
  57866. }
  57867. });
  57868. $element.bind('click', function() {
  57869. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57870. sideMenuCtrl && sideMenuCtrl.toggle($attr.menuToggle);
  57871. });
  57872. }
  57873. };
  57874. });
  57875. /*
  57876. * We don't document the ionModal directive, we instead document
  57877. * the $ionicModal service
  57878. */
  57879. IonicModule
  57880. .directive('ionModal', [function() {
  57881. return {
  57882. restrict: 'E',
  57883. transclude: true,
  57884. replace: true,
  57885. controller: [function() {}],
  57886. template: '<div class="modal-backdrop">' +
  57887. '<div class="modal-backdrop-bg"></div>' +
  57888. '<div class="modal-wrapper" ng-transclude></div>' +
  57889. '</div>'
  57890. };
  57891. }]);
  57892. IonicModule
  57893. .directive('ionModalView', function() {
  57894. return {
  57895. restrict: 'E',
  57896. compile: function(element) {
  57897. element.addClass('modal');
  57898. }
  57899. };
  57900. });
  57901. /**
  57902. * @ngdoc directive
  57903. * @name ionNavBackButton
  57904. * @module ionic
  57905. * @restrict E
  57906. * @parent ionNavBar
  57907. * @description
  57908. * Creates a back button inside an {@link ionic.directive:ionNavBar}.
  57909. *
  57910. * The back button will appear when the user is able to go back in the current navigation stack. By
  57911. * default, the markup of the back button is automatically built using platform-appropriate defaults
  57912. * (iOS back button icon on iOS and Android icon on Android).
  57913. *
  57914. * Additionally, the button is automatically set to `$ionicGoBack()` on click/tap. By default, the
  57915. * app will navigate back one view when the back button is clicked. More advanced behavior is also
  57916. * possible, as outlined below.
  57917. *
  57918. * @usage
  57919. *
  57920. * Recommended markup for default settings:
  57921. *
  57922. * ```html
  57923. * <ion-nav-bar>
  57924. * <ion-nav-back-button>
  57925. * </ion-nav-back-button>
  57926. * </ion-nav-bar>
  57927. * ```
  57928. *
  57929. * With custom inner markup, and automatically adds a default click action:
  57930. *
  57931. * ```html
  57932. * <ion-nav-bar>
  57933. * <ion-nav-back-button class="button-clear">
  57934. * <i class="ion-arrow-left-c"></i> Back
  57935. * </ion-nav-back-button>
  57936. * </ion-nav-bar>
  57937. * ```
  57938. *
  57939. * With custom inner markup and custom click action, using {@link ionic.service:$ionicHistory}:
  57940. *
  57941. * ```html
  57942. * <ion-nav-bar ng-controller="MyCtrl">
  57943. * <ion-nav-back-button class="button-clear"
  57944. * ng-click="myGoBack()">
  57945. * <i class="ion-arrow-left-c"></i> Back
  57946. * </ion-nav-back-button>
  57947. * </ion-nav-bar>
  57948. * ```
  57949. * ```js
  57950. * function MyCtrl($scope, $ionicHistory) {
  57951. * $scope.myGoBack = function() {
  57952. * $ionicHistory.goBack();
  57953. * };
  57954. * }
  57955. * ```
  57956. */
  57957. IonicModule
  57958. .directive('ionNavBackButton', ['$ionicConfig', '$document', function($ionicConfig, $document) {
  57959. return {
  57960. restrict: 'E',
  57961. require: '^ionNavBar',
  57962. compile: function(tElement, tAttrs) {
  57963. // clone the back button, but as a <div>
  57964. var buttonEle = $document[0].createElement('button');
  57965. for (var n in tAttrs.$attr) {
  57966. buttonEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);
  57967. }
  57968. if (!tAttrs.ngClick) {
  57969. buttonEle.setAttribute('ng-click', '$ionicGoBack()');
  57970. }
  57971. buttonEle.className = 'button back-button hide buttons ' + (tElement.attr('class') || '');
  57972. buttonEle.innerHTML = tElement.html() || '';
  57973. var childNode;
  57974. var hasIcon = hasIconClass(tElement[0]);
  57975. var hasInnerText;
  57976. var hasButtonText;
  57977. var hasPreviousTitle;
  57978. for (var x = 0; x < tElement[0].childNodes.length; x++) {
  57979. childNode = tElement[0].childNodes[x];
  57980. if (childNode.nodeType === 1) {
  57981. if (hasIconClass(childNode)) {
  57982. hasIcon = true;
  57983. } else if (childNode.classList.contains('default-title')) {
  57984. hasButtonText = true;
  57985. } else if (childNode.classList.contains('previous-title')) {
  57986. hasPreviousTitle = true;
  57987. }
  57988. } else if (!hasInnerText && childNode.nodeType === 3) {
  57989. hasInnerText = !!childNode.nodeValue.trim();
  57990. }
  57991. }
  57992. function hasIconClass(ele) {
  57993. return /ion-|icon/.test(ele.className);
  57994. }
  57995. var defaultIcon = $ionicConfig.backButton.icon();
  57996. if (!hasIcon && defaultIcon && defaultIcon !== 'none') {
  57997. buttonEle.innerHTML = '<i class="icon ' + defaultIcon + '"></i> ' + buttonEle.innerHTML;
  57998. buttonEle.className += ' button-clear';
  57999. }
  58000. if (!hasInnerText) {
  58001. var buttonTextEle = $document[0].createElement('span');
  58002. buttonTextEle.className = 'back-text';
  58003. if (!hasButtonText && $ionicConfig.backButton.text()) {
  58004. buttonTextEle.innerHTML += '<span class="default-title">' + $ionicConfig.backButton.text() + '</span>';
  58005. }
  58006. if (!hasPreviousTitle && $ionicConfig.backButton.previousTitleText()) {
  58007. buttonTextEle.innerHTML += '<span class="previous-title"></span>';
  58008. }
  58009. buttonEle.appendChild(buttonTextEle);
  58010. }
  58011. tElement.attr('class', 'hide');
  58012. tElement.empty();
  58013. return {
  58014. pre: function($scope, $element, $attr, navBarCtrl) {
  58015. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58016. navBarCtrl.navElement('backButton', buttonEle.outerHTML);
  58017. buttonEle = null;
  58018. }
  58019. };
  58020. }
  58021. };
  58022. }]);
  58023. /**
  58024. * @ngdoc directive
  58025. * @name ionNavBar
  58026. * @module ionic
  58027. * @delegate ionic.service:$ionicNavBarDelegate
  58028. * @restrict E
  58029. *
  58030. * @description
  58031. * If we have an {@link ionic.directive:ionNavView} directive, we can also create an
  58032. * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.
  58033. *
  58034. * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.
  58035. *
  58036. * We can add buttons depending on the currently visible view using
  58037. * {@link ionic.directive:ionNavButtons}.
  58038. *
  58039. * Note that the ion-nav-bar element will only work correctly if your content has an
  58040. * ionView around it.
  58041. *
  58042. * @usage
  58043. *
  58044. * ```html
  58045. * <body ng-app="starter">
  58046. * <!-- The nav bar that will be updated as we navigate -->
  58047. * <ion-nav-bar class="bar-positive">
  58048. * </ion-nav-bar>
  58049. *
  58050. * <!-- where the initial view template will be rendered -->
  58051. * <ion-nav-view>
  58052. * <ion-view>
  58053. * <ion-content>Hello!</ion-content>
  58054. * </ion-view>
  58055. * </ion-nav-view>
  58056. * </body>
  58057. * ```
  58058. *
  58059. * @param {string=} delegate-handle The handle used to identify this navBar
  58060. * with {@link ionic.service:$ionicNavBarDelegate}.
  58061. * @param align-title {string=} Where to align the title of the navbar.
  58062. * Available: 'left', 'right', 'center'. Defaults to 'center'.
  58063. * @param {boolean=} no-tap-scroll By default, the navbar will scroll the content
  58064. * to the top when tapped. Set no-tap-scroll to true to disable this behavior.
  58065. *
  58066. * </table><br/>
  58067. */
  58068. IonicModule
  58069. .directive('ionNavBar', function() {
  58070. return {
  58071. restrict: 'E',
  58072. controller: '$ionicNavBar',
  58073. scope: true,
  58074. link: function($scope, $element, $attr, ctrl) {
  58075. ctrl.init();
  58076. }
  58077. };
  58078. });
  58079. /**
  58080. * @ngdoc directive
  58081. * @name ionNavButtons
  58082. * @module ionic
  58083. * @restrict E
  58084. * @parent ionNavView
  58085. *
  58086. * @description
  58087. * Use nav buttons to set the buttons on your {@link ionic.directive:ionNavBar}
  58088. * from within an {@link ionic.directive:ionView}. This gives each
  58089. * view template the ability to specify which buttons should show in the nav bar,
  58090. * overriding any default buttons already placed in the nav bar.
  58091. *
  58092. * Any buttons you declare will be positioned on the navbar's corresponding side. Primary
  58093. * buttons generally map to the left side of the header, and secondary buttons are
  58094. * generally on the right side. However, their exact locations are platform-specific.
  58095. * For example, in iOS, the primary buttons are on the far left of the header, and
  58096. * secondary buttons are on the far right, with the header title centered between them.
  58097. * For Android, however, both groups of buttons are on the far right of the header,
  58098. * with the header title aligned left.
  58099. *
  58100. * We recommend always using `primary` and `secondary`, so the buttons correctly map
  58101. * to the side familiar to users of each platform. However, in cases where buttons should
  58102. * always be on an exact side, both `left` and `right` sides are still available. For
  58103. * example, a toggle button for a left side menu should be on the left side; in this case,
  58104. * we'd recommend using `side="left"`, so it's always on the left, no matter the platform.
  58105. *
  58106. * ***Note*** that `ion-nav-buttons` must be immediate descendants of the `ion-view` or
  58107. * `ion-nav-bar` element (basically, don't wrap it in another div).
  58108. *
  58109. * @usage
  58110. * ```html
  58111. * <ion-nav-bar>
  58112. * </ion-nav-bar>
  58113. * <ion-nav-view>
  58114. * <ion-view>
  58115. * <ion-nav-buttons side="primary">
  58116. * <button class="button" ng-click="doSomething()">
  58117. * I'm a button on the primary of the navbar!
  58118. * </button>
  58119. * </ion-nav-buttons>
  58120. * <ion-content>
  58121. * Some super content here!
  58122. * </ion-content>
  58123. * </ion-view>
  58124. * </ion-nav-view>
  58125. * ```
  58126. *
  58127. * @param {string} side The side to place the buttons in the
  58128. * {@link ionic.directive:ionNavBar}. Available sides: `primary`, `secondary`, `left`, and `right`.
  58129. */
  58130. IonicModule
  58131. .directive('ionNavButtons', ['$document', function($document) {
  58132. return {
  58133. require: '^ionNavBar',
  58134. restrict: 'E',
  58135. compile: function(tElement, tAttrs) {
  58136. var side = 'left';
  58137. if (/^primary|secondary|right$/i.test(tAttrs.side || '')) {
  58138. side = tAttrs.side.toLowerCase();
  58139. }
  58140. var spanEle = $document[0].createElement('span');
  58141. spanEle.className = side + '-buttons';
  58142. spanEle.innerHTML = tElement.html();
  58143. var navElementType = side + 'Buttons';
  58144. tElement.attr('class', 'hide');
  58145. tElement.empty();
  58146. return {
  58147. pre: function($scope, $element, $attrs, navBarCtrl) {
  58148. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58149. var parentViewCtrl = $element.parent().data('$ionViewController');
  58150. if (parentViewCtrl) {
  58151. // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view
  58152. parentViewCtrl.navElement(navElementType, spanEle.outerHTML);
  58153. } else {
  58154. // these are buttons for all views that do not have their own ion-nav-buttons
  58155. navBarCtrl.navElement(navElementType, spanEle.outerHTML);
  58156. }
  58157. spanEle = null;
  58158. }
  58159. };
  58160. }
  58161. };
  58162. }]);
  58163. /**
  58164. * @ngdoc directive
  58165. * @name navDirection
  58166. * @module ionic
  58167. * @restrict A
  58168. *
  58169. * @description
  58170. * The direction which the nav view transition should animate. Available options
  58171. * are: `forward`, `back`, `enter`, `exit`, `swap`.
  58172. *
  58173. * @usage
  58174. *
  58175. * ```html
  58176. * <a nav-direction="forward" href="#/home">Home</a>
  58177. * ```
  58178. */
  58179. IonicModule
  58180. .directive('navDirection', ['$ionicViewSwitcher', function($ionicViewSwitcher) {
  58181. return {
  58182. restrict: 'A',
  58183. priority: 1000,
  58184. link: function($scope, $element, $attr) {
  58185. $element.bind('click', function() {
  58186. $ionicViewSwitcher.nextDirection($attr.navDirection);
  58187. });
  58188. }
  58189. };
  58190. }]);
  58191. /**
  58192. * @ngdoc directive
  58193. * @name ionNavTitle
  58194. * @module ionic
  58195. * @restrict E
  58196. * @parent ionNavView
  58197. *
  58198. * @description
  58199. *
  58200. * The nav title directive replaces an {@link ionic.directive:ionNavBar} title text with
  58201. * custom HTML from within an {@link ionic.directive:ionView} template. This gives each
  58202. * view the ability to specify its own custom title element, such as an image or any HTML,
  58203. * rather than being text-only. Alternatively, text-only titles can be updated using the
  58204. * `view-title` {@link ionic.directive:ionView} attribute.
  58205. *
  58206. * Note that `ion-nav-title` must be an immediate descendant of the `ion-view` or
  58207. * `ion-nav-bar` element (basically don't wrap it in another div).
  58208. *
  58209. * @usage
  58210. * ```html
  58211. * <ion-nav-bar>
  58212. * </ion-nav-bar>
  58213. * <ion-nav-view>
  58214. * <ion-view>
  58215. * <ion-nav-title>
  58216. * <img src="logo.svg">
  58217. * </ion-nav-title>
  58218. * <ion-content>
  58219. * Some super content here!
  58220. * </ion-content>
  58221. * </ion-view>
  58222. * </ion-nav-view>
  58223. * ```
  58224. *
  58225. */
  58226. IonicModule
  58227. .directive('ionNavTitle', ['$document', function($document) {
  58228. return {
  58229. require: '^ionNavBar',
  58230. restrict: 'E',
  58231. compile: function(tElement, tAttrs) {
  58232. var navElementType = 'title';
  58233. var spanEle = $document[0].createElement('span');
  58234. for (var n in tAttrs.$attr) {
  58235. spanEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);
  58236. }
  58237. spanEle.classList.add('nav-bar-title');
  58238. spanEle.innerHTML = tElement.html();
  58239. tElement.attr('class', 'hide');
  58240. tElement.empty();
  58241. return {
  58242. pre: function($scope, $element, $attrs, navBarCtrl) {
  58243. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58244. var parentViewCtrl = $element.parent().data('$ionViewController');
  58245. if (parentViewCtrl) {
  58246. // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view
  58247. parentViewCtrl.navElement(navElementType, spanEle.outerHTML);
  58248. } else {
  58249. // these are buttons for all views that do not have their own ion-nav-buttons
  58250. navBarCtrl.navElement(navElementType, spanEle.outerHTML);
  58251. }
  58252. spanEle = null;
  58253. }
  58254. };
  58255. }
  58256. };
  58257. }]);
  58258. /**
  58259. * @ngdoc directive
  58260. * @name navTransition
  58261. * @module ionic
  58262. * @restrict A
  58263. *
  58264. * @description
  58265. * The transition type which the nav view transition should use when it animates.
  58266. * Current, options are `ios`, `android`, and `none`. More options coming soon.
  58267. *
  58268. * @usage
  58269. *
  58270. * ```html
  58271. * <a nav-transition="none" href="#/home">Home</a>
  58272. * ```
  58273. */
  58274. IonicModule
  58275. .directive('navTransition', ['$ionicViewSwitcher', function($ionicViewSwitcher) {
  58276. return {
  58277. restrict: 'A',
  58278. priority: 1000,
  58279. link: function($scope, $element, $attr) {
  58280. $element.bind('click', function() {
  58281. $ionicViewSwitcher.nextTransition($attr.navTransition);
  58282. });
  58283. }
  58284. };
  58285. }]);
  58286. /**
  58287. * @ngdoc directive
  58288. * @name ionNavView
  58289. * @module ionic
  58290. * @restrict E
  58291. * @codepen odqCz
  58292. *
  58293. * @description
  58294. * As a user navigates throughout your app, Ionic is able to keep track of their
  58295. * navigation history. By knowing their history, transitions between views
  58296. * correctly enter and exit using the platform's transition style. An additional
  58297. * benefit to Ionic's navigation system is its ability to manage multiple
  58298. * histories. For example, each tab can have it's own navigation history stack.
  58299. *
  58300. * Ionic uses the AngularUI Router module so app interfaces can be organized
  58301. * into various "states". Like Angular's core $route service, URLs can be used
  58302. * to control the views. However, the AngularUI Router provides a more powerful
  58303. * state manager in that states are bound to named, nested, and parallel views,
  58304. * allowing more than one template to be rendered on the same page.
  58305. * Additionally, each state is not required to be bound to a URL, and data can
  58306. * be pushed to each state which allows much flexibility.
  58307. *
  58308. * The ionNavView directive is used to render templates in your application. Each template
  58309. * is part of a state. States are usually mapped to a url, and are defined programatically
  58310. * using angular-ui-router (see [their docs](https://github.com/angular-ui/ui-router/wiki),
  58311. * and remember to replace ui-view with ion-nav-view in examples).
  58312. *
  58313. * @usage
  58314. * In this example, we will create a navigation view that contains our different states for the app.
  58315. *
  58316. * To do this, in our markup we use ionNavView top level directive. To display a header bar we use
  58317. * the {@link ionic.directive:ionNavBar} directive that updates as we navigate through the
  58318. * navigation stack.
  58319. *
  58320. * Next, we need to setup our states that will be rendered.
  58321. *
  58322. * ```js
  58323. * var app = angular.module('myApp', ['ionic']);
  58324. * app.config(function($stateProvider) {
  58325. * $stateProvider
  58326. * .state('index', {
  58327. * url: '/',
  58328. * templateUrl: 'home.html'
  58329. * })
  58330. * .state('music', {
  58331. * url: '/music',
  58332. * templateUrl: 'music.html'
  58333. * });
  58334. * });
  58335. * ```
  58336. * Then on app start, $stateProvider will look at the url, see if it matches the index state,
  58337. * and then try to load home.html into the `<ion-nav-view>`.
  58338. *
  58339. * Pages are loaded by the URLs given. One simple way to create templates in Angular is to put
  58340. * them directly into your HTML file and use the `<script type="text/ng-template">` syntax.
  58341. * So here is one way to put home.html into our app:
  58342. *
  58343. * ```html
  58344. * <script id="home" type="text/ng-template">
  58345. * <!-- The title of the ion-view will be shown on the navbar -->
  58346. * <ion-view view-title="Home">
  58347. * <ion-content ng-controller="HomeCtrl">
  58348. * <!-- The content of the page -->
  58349. * <a href="#/music">Go to music page!</a>
  58350. * </ion-content>
  58351. * </ion-view>
  58352. * </script>
  58353. * ```
  58354. *
  58355. * This is good to do because the template will be cached for very fast loading, instead of
  58356. * having to fetch them from the network.
  58357. *
  58358. * ## Caching
  58359. *
  58360. * By default, views are cached to improve performance. When a view is navigated away from, its
  58361. * element is left in the DOM, and its scope is disconnected from the `$watch` cycle. When
  58362. * navigating to a view that is already cached, its scope is then reconnected, and the existing
  58363. * element that was left in the DOM becomes the active view. This also allows for the scroll
  58364. * position of previous views to be maintained.
  58365. *
  58366. * Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of
  58367. * 10 views, and not only can this be configured, but apps can also explicitly state which views
  58368. * should and should not be cached.
  58369. *
  58370. * Note that because we are caching these views, *we aren’t destroying scopes*. Instead, scopes
  58371. * are being disconnected from the watch cycle. Because scopes are not being destroyed and
  58372. * recreated, controllers are not loading again on a subsequent viewing. If the app/controller
  58373. * needs to know when a view has entered or has left, then view events emitted from the
  58374. * {@link ionic.directive:ionView} scope, such as `$ionicView.enter`, may be useful.
  58375. *
  58376. * By default, when navigating back in the history, the "forward" views are removed from the cache.
  58377. * If you navigate forward to the same view again, it'll create a new DOM element and controller
  58378. * instance. Basically, any forward views are reset each time. This can be configured using the
  58379. * {@link ionic.provider:$ionicConfigProvider}:
  58380. *
  58381. * ```js
  58382. * $ionicConfigProvider.views.forwardCache(true);
  58383. * ```
  58384. *
  58385. * #### Disable cache globally
  58386. *
  58387. * The {@link ionic.provider:$ionicConfigProvider} can be used to set the maximum allowable views
  58388. * which can be cached, but this can also be use to disable all caching by setting it to 0.
  58389. *
  58390. * ```js
  58391. * $ionicConfigProvider.views.maxCache(0);
  58392. * ```
  58393. *
  58394. * #### Disable cache within state provider
  58395. *
  58396. * ```js
  58397. * $stateProvider.state('myState', {
  58398. * cache: false,
  58399. * url : '/myUrl',
  58400. * templateUrl : 'my-template.html'
  58401. * })
  58402. * ```
  58403. *
  58404. * #### Disable cache with an attribute
  58405. *
  58406. * ```html
  58407. * <ion-view cache-view="false" view-title="My Title!">
  58408. * ...
  58409. * </ion-view>
  58410. * ```
  58411. *
  58412. *
  58413. * ## AngularUI Router
  58414. *
  58415. * Please visit [AngularUI Router's docs](https://github.com/angular-ui/ui-router/wiki) for
  58416. * more info. Below is a great video by the AngularUI Router team that may help to explain
  58417. * how it all works:
  58418. *
  58419. * <iframe width="560" height="315" src="//www.youtube.com/embed/dqJRoh8MnBo"
  58420. * frameborder="0" allowfullscreen></iframe>
  58421. *
  58422. * Note: We do not recommend using [resolve](https://github.com/angular-ui/ui-router/wiki#resolve)
  58423. * of AngularUI Router. The recommended approach is to execute any logic needed before beginning the state transition.
  58424. *
  58425. * @param {string=} name A view name. The name should be unique amongst the other views in the
  58426. * same state. You can have views of the same name that live in different states. For more
  58427. * information, see ui-router's
  58428. * [ui-view documentation](http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view).
  58429. */
  58430. IonicModule
  58431. .directive('ionNavView', [
  58432. '$state',
  58433. '$ionicConfig',
  58434. function($state, $ionicConfig) {
  58435. // IONIC's fork of Angular UI Router, v0.2.10
  58436. // the navView handles registering views in the history and how to transition between them
  58437. return {
  58438. restrict: 'E',
  58439. terminal: true,
  58440. priority: 2000,
  58441. transclude: true,
  58442. controller: '$ionicNavView',
  58443. compile: function(tElement, tAttrs, transclude) {
  58444. // a nav view element is a container for numerous views
  58445. tElement.addClass('view-container');
  58446. ionic.DomUtil.cachedAttr(tElement, 'nav-view-transition', $ionicConfig.views.transition());
  58447. return function($scope, $element, $attr, navViewCtrl) {
  58448. var latestLocals;
  58449. // Put in the compiled initial view
  58450. transclude($scope, function(clone) {
  58451. $element.append(clone);
  58452. });
  58453. var viewData = navViewCtrl.init();
  58454. // listen for $stateChangeSuccess
  58455. $scope.$on('$stateChangeSuccess', function() {
  58456. updateView(false);
  58457. });
  58458. $scope.$on('$viewContentLoading', function() {
  58459. updateView(false);
  58460. });
  58461. // initial load, ready go
  58462. updateView(true);
  58463. function updateView(firstTime) {
  58464. // get the current local according to the $state
  58465. var viewLocals = $state.$current && $state.$current.locals[viewData.name];
  58466. // do not update THIS nav-view if its is not the container for the given state
  58467. // if the viewLocals are the same as THIS latestLocals, then nothing to do
  58468. if (!viewLocals || (!firstTime && viewLocals === latestLocals)) return;
  58469. // update the latestLocals
  58470. latestLocals = viewLocals;
  58471. viewData.state = viewLocals.$$state;
  58472. // register, update and transition to the new view
  58473. navViewCtrl.register(viewLocals);
  58474. }
  58475. };
  58476. }
  58477. };
  58478. }]);
  58479. IonicModule
  58480. .config(['$provide', function($provide) {
  58481. $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
  58482. // drop the default ngClick directive
  58483. $delegate.shift();
  58484. return $delegate;
  58485. }]);
  58486. }])
  58487. /**
  58488. * @private
  58489. */
  58490. .factory('$ionicNgClick', ['$parse', function($parse) {
  58491. return function(scope, element, clickExpr) {
  58492. var clickHandler = angular.isFunction(clickExpr) ?
  58493. clickExpr :
  58494. $parse(clickExpr);
  58495. element.on('click', function(event) {
  58496. scope.$apply(function() {
  58497. clickHandler(scope, {$event: (event)});
  58498. });
  58499. });
  58500. // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
  58501. // something else nearby.
  58502. element.onclick = noop;
  58503. };
  58504. }])
  58505. .directive('ngClick', ['$ionicNgClick', function($ionicNgClick) {
  58506. return function(scope, element, attr) {
  58507. $ionicNgClick(scope, element, attr.ngClick);
  58508. };
  58509. }])
  58510. .directive('ionStopEvent', function() {
  58511. return {
  58512. restrict: 'A',
  58513. link: function(scope, element, attr) {
  58514. element.bind(attr.ionStopEvent, eventStopPropagation);
  58515. }
  58516. };
  58517. });
  58518. function eventStopPropagation(e) {
  58519. e.stopPropagation();
  58520. }
  58521. /**
  58522. * @ngdoc directive
  58523. * @name ionPane
  58524. * @module ionic
  58525. * @restrict E
  58526. *
  58527. * @description A simple container that fits content, with no side effects. Adds the 'pane' class to the element.
  58528. */
  58529. IonicModule
  58530. .directive('ionPane', function() {
  58531. return {
  58532. restrict: 'E',
  58533. link: function(scope, element) {
  58534. element.addClass('pane');
  58535. }
  58536. };
  58537. });
  58538. /*
  58539. * We don't document the ionPopover directive, we instead document
  58540. * the $ionicPopover service
  58541. */
  58542. IonicModule
  58543. .directive('ionPopover', [function() {
  58544. return {
  58545. restrict: 'E',
  58546. transclude: true,
  58547. replace: true,
  58548. controller: [function() {}],
  58549. template: '<div class="popover-backdrop">' +
  58550. '<div class="popover-wrapper" ng-transclude></div>' +
  58551. '</div>'
  58552. };
  58553. }]);
  58554. IonicModule
  58555. .directive('ionPopoverView', function() {
  58556. return {
  58557. restrict: 'E',
  58558. compile: function(element) {
  58559. element.append(jqLite('<div class="popover-arrow">'));
  58560. element.addClass('popover');
  58561. }
  58562. };
  58563. });
  58564. /**
  58565. * @ngdoc directive
  58566. * @name ionRadio
  58567. * @module ionic
  58568. * @restrict E
  58569. * @codepen saoBG
  58570. * @description
  58571. * The radio directive is no different than the HTML radio input, except it's styled differently.
  58572. *
  58573. * Radio behaves like [AngularJS radio](http://docs.angularjs.org/api/ng/input/input[radio]).
  58574. *
  58575. * @usage
  58576. * ```html
  58577. * <ion-radio ng-model="choice" ng-value="'A'">Choose A</ion-radio>
  58578. * <ion-radio ng-model="choice" ng-value="'B'">Choose B</ion-radio>
  58579. * <ion-radio ng-model="choice" ng-value="'C'">Choose C</ion-radio>
  58580. * ```
  58581. *
  58582. * @param {string=} name The name of the radio input.
  58583. * @param {expression=} value The value of the radio input.
  58584. * @param {boolean=} disabled The state of the radio input.
  58585. * @param {string=} icon The icon to use when the radio input is selected.
  58586. * @param {expression=} ng-value Angular equivalent of the value attribute.
  58587. * @param {expression=} ng-model The angular model for the radio input.
  58588. * @param {boolean=} ng-disabled Angular equivalent of the disabled attribute.
  58589. * @param {expression=} ng-change Triggers given expression when radio input's model changes
  58590. */
  58591. IonicModule
  58592. .directive('ionRadio', function() {
  58593. return {
  58594. restrict: 'E',
  58595. replace: true,
  58596. require: '?ngModel',
  58597. transclude: true,
  58598. template:
  58599. '<label class="item item-radio">' +
  58600. '<input type="radio" name="radio-group">' +
  58601. '<div class="radio-content">' +
  58602. '<div class="item-content disable-pointer-events" ng-transclude></div>' +
  58603. '<i class="radio-icon disable-pointer-events icon ion-checkmark"></i>' +
  58604. '</div>' +
  58605. '</label>',
  58606. compile: function(element, attr) {
  58607. if (attr.icon) {
  58608. var iconElm = element.find('i');
  58609. iconElm.removeClass('ion-checkmark').addClass(attr.icon);
  58610. }
  58611. var input = element.find('input');
  58612. forEach({
  58613. 'name': attr.name,
  58614. 'value': attr.value,
  58615. 'disabled': attr.disabled,
  58616. 'ng-value': attr.ngValue,
  58617. 'ng-model': attr.ngModel,
  58618. 'ng-disabled': attr.ngDisabled,
  58619. 'ng-change': attr.ngChange,
  58620. 'ng-required': attr.ngRequired,
  58621. 'required': attr.required
  58622. }, function(value, name) {
  58623. if (isDefined(value)) {
  58624. input.attr(name, value);
  58625. }
  58626. });
  58627. return function(scope, element, attr) {
  58628. scope.getValue = function() {
  58629. return scope.ngValue || attr.value;
  58630. };
  58631. };
  58632. }
  58633. };
  58634. });
  58635. /**
  58636. * @ngdoc directive
  58637. * @name ionRefresher
  58638. * @module ionic
  58639. * @restrict E
  58640. * @parent ionic.directive:ionContent, ionic.directive:ionScroll
  58641. * @description
  58642. * Allows you to add pull-to-refresh to a scrollView.
  58643. *
  58644. * Place it as the first child of your {@link ionic.directive:ionContent} or
  58645. * {@link ionic.directive:ionScroll} element.
  58646. *
  58647. * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event
  58648. * from your controller.
  58649. *
  58650. * @usage
  58651. *
  58652. * ```html
  58653. * <ion-content ng-controller="MyController">
  58654. * <ion-refresher
  58655. * pulling-text="Pull to refresh..."
  58656. * on-refresh="doRefresh()">
  58657. * </ion-refresher>
  58658. * <ion-list>
  58659. * <ion-item ng-repeat="item in items"></ion-item>
  58660. * </ion-list>
  58661. * </ion-content>
  58662. * ```
  58663. * ```js
  58664. * angular.module('testApp', ['ionic'])
  58665. * .controller('MyController', function($scope, $http) {
  58666. * $scope.items = [1,2,3];
  58667. * $scope.doRefresh = function() {
  58668. * $http.get('/new-items')
  58669. * .success(function(newItems) {
  58670. * $scope.items = newItems;
  58671. * })
  58672. * .finally(function() {
  58673. * // Stop the ion-refresher from spinning
  58674. * $scope.$broadcast('scroll.refreshComplete');
  58675. * });
  58676. * };
  58677. * });
  58678. * ```
  58679. *
  58680. * @param {expression=} on-refresh Called when the user pulls down enough and lets go
  58681. * of the refresher.
  58682. * @param {expression=} on-pulling Called when the user starts to pull down
  58683. * on the refresher.
  58684. * @param {string=} pulling-text The text to display while the user is pulling down.
  58685. * @param {string=} pulling-icon The icon to display while the user is pulling down.
  58686. * Default: 'ion-android-arrow-down'.
  58687. * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display
  58688. * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}
  58689. * is now the default, replacing rotating font icons. Set to `none` to disable both the
  58690. * spinner and the icon.
  58691. * @param {string=} refreshing-icon The font icon to display after user lets go of the
  58692. * refresher. This is deprecated in favor of the SVG {@link ionic.directive:ionSpinner}.
  58693. * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling
  58694. * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.
  58695. *
  58696. */
  58697. IonicModule
  58698. .directive('ionRefresher', [function() {
  58699. return {
  58700. restrict: 'E',
  58701. replace: true,
  58702. require: ['?^$ionicScroll', 'ionRefresher'],
  58703. controller: '$ionicRefresher',
  58704. template:
  58705. '<div class="scroll-refresher invisible" collection-repeat-ignore>' +
  58706. '<div class="ionic-refresher-content" ' +
  58707. 'ng-class="{\'ionic-refresher-with-text\': pullingText || refreshingText}">' +
  58708. '<div class="icon-pulling" ng-class="{\'pulling-rotation-disabled\':disablePullingRotation}">' +
  58709. '<i class="icon {{pullingIcon}}"></i>' +
  58710. '</div>' +
  58711. '<div class="text-pulling" ng-bind-html="pullingText"></div>' +
  58712. '<div class="icon-refreshing">' +
  58713. '<ion-spinner ng-if="showSpinner" icon="{{spinner}}"></ion-spinner>' +
  58714. '<i ng-if="showIcon" class="icon {{refreshingIcon}}"></i>' +
  58715. '</div>' +
  58716. '<div class="text-refreshing" ng-bind-html="refreshingText"></div>' +
  58717. '</div>' +
  58718. '</div>',
  58719. link: function($scope, $element, $attrs, ctrls) {
  58720. // JS Scrolling uses the scroll controller
  58721. var scrollCtrl = ctrls[0],
  58722. refresherCtrl = ctrls[1];
  58723. if (!scrollCtrl || scrollCtrl.isNative()) {
  58724. // Kick off native scrolling
  58725. refresherCtrl.init();
  58726. } else {
  58727. $element[0].classList.add('js-scrolling');
  58728. scrollCtrl._setRefresher(
  58729. $scope,
  58730. $element[0],
  58731. refresherCtrl.getRefresherDomMethods()
  58732. );
  58733. $scope.$on('scroll.refreshComplete', function() {
  58734. $scope.$evalAsync(function() {
  58735. scrollCtrl.scrollView.finishPullToRefresh();
  58736. });
  58737. });
  58738. }
  58739. }
  58740. };
  58741. }]);
  58742. /**
  58743. * @ngdoc directive
  58744. * @name ionScroll
  58745. * @module ionic
  58746. * @delegate ionic.service:$ionicScrollDelegate
  58747. * @codepen mwFuh
  58748. * @restrict E
  58749. *
  58750. * @description
  58751. * Creates a scrollable container for all content inside.
  58752. *
  58753. * @usage
  58754. *
  58755. * Basic usage:
  58756. *
  58757. * ```html
  58758. * <ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px">
  58759. * <div style="width: 5000px; height: 5000px; background: url('https://upload.wikimedia.org/wikipedia/commons/a/ad/Europe_geological_map-en.jpg') repeat"></div>
  58760. * </ion-scroll>
  58761. * ```
  58762. *
  58763. * Note that it's important to set the height of the scroll box as well as the height of the inner
  58764. * content to enable scrolling. This makes it possible to have full control over scrollable areas.
  58765. *
  58766. * If you'd just like to have a center content scrolling area, use {@link ionic.directive:ionContent} instead.
  58767. *
  58768. * @param {string=} delegate-handle The handle used to identify this scrollView
  58769. * with {@link ionic.service:$ionicScrollDelegate}.
  58770. * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.
  58771. * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.
  58772. * @param {boolean=} paging Whether to scroll with paging.
  58773. * @param {expression=} on-refresh Called on pull-to-refresh, triggered by an {@link ionic.directive:ionRefresher}.
  58774. * @param {expression=} on-scroll Called whenever the user scrolls.
  58775. * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.
  58776. * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.
  58777. * @param {boolean=} zooming Whether to support pinch-to-zoom
  58778. * @param {integer=} min-zoom The smallest zoom amount allowed (default is 0.5)
  58779. * @param {integer=} max-zoom The largest zoom amount allowed (default is 3)
  58780. * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges
  58781. * of the content. Defaults to true on iOS, false on Android.
  58782. */
  58783. IonicModule
  58784. .directive('ionScroll', [
  58785. '$timeout',
  58786. '$controller',
  58787. '$ionicBind',
  58788. '$ionicConfig',
  58789. function($timeout, $controller, $ionicBind, $ionicConfig) {
  58790. return {
  58791. restrict: 'E',
  58792. scope: true,
  58793. controller: function() {},
  58794. compile: function(element, attr) {
  58795. element.addClass('scroll-view ionic-scroll');
  58796. //We cannot transclude here because it breaks element.data() inheritance on compile
  58797. var innerElement = jqLite('<div class="scroll"></div>');
  58798. innerElement.append(element.contents());
  58799. element.append(innerElement);
  58800. var nativeScrolling = attr.overflowScroll !== "false" && (attr.overflowScroll === "true" || !$ionicConfig.scrolling.jsScrolling());
  58801. return { pre: prelink };
  58802. function prelink($scope, $element, $attr) {
  58803. $ionicBind($scope, $attr, {
  58804. direction: '@',
  58805. paging: '@',
  58806. $onScroll: '&onScroll',
  58807. scroll: '@',
  58808. scrollbarX: '@',
  58809. scrollbarY: '@',
  58810. zooming: '@',
  58811. minZoom: '@',
  58812. maxZoom: '@'
  58813. });
  58814. $scope.direction = $scope.direction || 'y';
  58815. if (isDefined($attr.padding)) {
  58816. $scope.$watch($attr.padding, function(newVal) {
  58817. innerElement.toggleClass('padding', !!newVal);
  58818. });
  58819. }
  58820. if ($scope.$eval($scope.paging) === true) {
  58821. innerElement.addClass('scroll-paging');
  58822. }
  58823. if (!$scope.direction) { $scope.direction = 'y'; }
  58824. var isPaging = $scope.$eval($scope.paging) === true;
  58825. if (nativeScrolling) {
  58826. $element.addClass('overflow-scroll');
  58827. }
  58828. $element.addClass('scroll-' + $scope.direction);
  58829. var scrollViewOptions = {
  58830. el: $element[0],
  58831. delegateHandle: $attr.delegateHandle,
  58832. locking: ($attr.locking || 'true') === 'true',
  58833. bouncing: $scope.$eval($attr.hasBouncing),
  58834. paging: isPaging,
  58835. scrollbarX: $scope.$eval($scope.scrollbarX) !== false,
  58836. scrollbarY: $scope.$eval($scope.scrollbarY) !== false,
  58837. scrollingX: $scope.direction.indexOf('x') >= 0,
  58838. scrollingY: $scope.direction.indexOf('y') >= 0,
  58839. zooming: $scope.$eval($scope.zooming) === true,
  58840. maxZoom: $scope.$eval($scope.maxZoom) || 3,
  58841. minZoom: $scope.$eval($scope.minZoom) || 0.5,
  58842. preventDefault: true,
  58843. nativeScrolling: nativeScrolling
  58844. };
  58845. if (isPaging) {
  58846. scrollViewOptions.speedMultiplier = 0.8;
  58847. scrollViewOptions.bouncing = false;
  58848. }
  58849. $controller('$ionicScroll', {
  58850. $scope: $scope,
  58851. scrollViewOptions: scrollViewOptions
  58852. });
  58853. }
  58854. }
  58855. };
  58856. }]);
  58857. /**
  58858. * @ngdoc directive
  58859. * @name ionSideMenu
  58860. * @module ionic
  58861. * @restrict E
  58862. * @parent ionic.directive:ionSideMenus
  58863. *
  58864. * @description
  58865. * A container for a side menu, sibling to an {@link ionic.directive:ionSideMenuContent} directive.
  58866. *
  58867. * @usage
  58868. * ```html
  58869. * <ion-side-menu
  58870. * side="left"
  58871. * width="myWidthValue + 20"
  58872. * is-enabled="shouldLeftSideMenuBeEnabled()">
  58873. * </ion-side-menu>
  58874. * ```
  58875. * For a complete side menu example, see the
  58876. * {@link ionic.directive:ionSideMenus} documentation.
  58877. *
  58878. * @param {string} side Which side the side menu is currently on. Allowed values: 'left' or 'right'.
  58879. * @param {boolean=} is-enabled Whether this side menu is enabled.
  58880. * @param {number=} width How many pixels wide the side menu should be. Defaults to 275.
  58881. */
  58882. IonicModule
  58883. .directive('ionSideMenu', function() {
  58884. return {
  58885. restrict: 'E',
  58886. require: '^ionSideMenus',
  58887. scope: true,
  58888. compile: function(element, attr) {
  58889. angular.isUndefined(attr.isEnabled) && attr.$set('isEnabled', 'true');
  58890. angular.isUndefined(attr.width) && attr.$set('width', '275');
  58891. element.addClass('menu menu-' + attr.side);
  58892. return function($scope, $element, $attr, sideMenuCtrl) {
  58893. $scope.side = $attr.side || 'left';
  58894. var sideMenu = sideMenuCtrl[$scope.side] = new ionic.views.SideMenu({
  58895. width: attr.width,
  58896. el: $element[0],
  58897. isEnabled: true
  58898. });
  58899. $scope.$watch($attr.width, function(val) {
  58900. var numberVal = +val;
  58901. if (numberVal && numberVal == val) {
  58902. sideMenu.setWidth(+val);
  58903. }
  58904. });
  58905. $scope.$watch($attr.isEnabled, function(val) {
  58906. sideMenu.setIsEnabled(!!val);
  58907. });
  58908. };
  58909. }
  58910. };
  58911. });
  58912. /**
  58913. * @ngdoc directive
  58914. * @name ionSideMenuContent
  58915. * @module ionic
  58916. * @restrict E
  58917. * @parent ionic.directive:ionSideMenus
  58918. *
  58919. * @description
  58920. * A container for the main visible content, sibling to one or more
  58921. * {@link ionic.directive:ionSideMenu} directives.
  58922. *
  58923. * @usage
  58924. * ```html
  58925. * <ion-side-menu-content
  58926. * edge-drag-threshold="true"
  58927. * drag-content="true">
  58928. * </ion-side-menu-content>
  58929. * ```
  58930. * For a complete side menu example, see the
  58931. * {@link ionic.directive:ionSideMenus} documentation.
  58932. *
  58933. * @param {boolean=} drag-content Whether the content can be dragged. Default true.
  58934. * @param {boolean|number=} edge-drag-threshold Whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. Default false. Accepts three types of values:
  58935. * - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.
  58936. * - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
  58937. * - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
  58938. *
  58939. */
  58940. IonicModule
  58941. .directive('ionSideMenuContent', [
  58942. '$timeout',
  58943. '$ionicGesture',
  58944. '$window',
  58945. function($timeout, $ionicGesture, $window) {
  58946. return {
  58947. restrict: 'EA', //DEPRECATED 'A'
  58948. require: '^ionSideMenus',
  58949. scope: true,
  58950. compile: function(element, attr) {
  58951. element.addClass('menu-content pane');
  58952. return { pre: prelink };
  58953. function prelink($scope, $element, $attr, sideMenuCtrl) {
  58954. var startCoord = null;
  58955. var primaryScrollAxis = null;
  58956. if (isDefined(attr.dragContent)) {
  58957. $scope.$watch(attr.dragContent, function(value) {
  58958. sideMenuCtrl.canDragContent(value);
  58959. });
  58960. } else {
  58961. sideMenuCtrl.canDragContent(true);
  58962. }
  58963. if (isDefined(attr.edgeDragThreshold)) {
  58964. $scope.$watch(attr.edgeDragThreshold, function(value) {
  58965. sideMenuCtrl.edgeDragThreshold(value);
  58966. });
  58967. }
  58968. // Listen for taps on the content to close the menu
  58969. function onContentTap(gestureEvt) {
  58970. if (sideMenuCtrl.getOpenAmount() !== 0) {
  58971. sideMenuCtrl.close();
  58972. gestureEvt.gesture.srcEvent.preventDefault();
  58973. startCoord = null;
  58974. primaryScrollAxis = null;
  58975. } else if (!startCoord) {
  58976. startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  58977. }
  58978. }
  58979. function onDragX(e) {
  58980. if (!sideMenuCtrl.isDraggableTarget(e)) return;
  58981. if (getPrimaryScrollAxis(e) == 'x') {
  58982. sideMenuCtrl._handleDrag(e);
  58983. e.gesture.srcEvent.preventDefault();
  58984. }
  58985. }
  58986. function onDragY(e) {
  58987. if (getPrimaryScrollAxis(e) == 'x') {
  58988. e.gesture.srcEvent.preventDefault();
  58989. }
  58990. }
  58991. function onDragRelease(e) {
  58992. sideMenuCtrl._endDrag(e);
  58993. startCoord = null;
  58994. primaryScrollAxis = null;
  58995. }
  58996. function getPrimaryScrollAxis(gestureEvt) {
  58997. // gets whether the user is primarily scrolling on the X or Y
  58998. // If a majority of the drag has been on the Y since the start of
  58999. // the drag, but the X has moved a little bit, it's still a Y drag
  59000. if (primaryScrollAxis) {
  59001. // we already figured out which way they're scrolling
  59002. return primaryScrollAxis;
  59003. }
  59004. if (gestureEvt && gestureEvt.gesture) {
  59005. if (!startCoord) {
  59006. // get the starting point
  59007. startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  59008. } else {
  59009. // we already have a starting point, figure out which direction they're going
  59010. var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  59011. var xDistance = Math.abs(endCoord.x - startCoord.x);
  59012. var yDistance = Math.abs(endCoord.y - startCoord.y);
  59013. var scrollAxis = (xDistance < yDistance ? 'y' : 'x');
  59014. if (Math.max(xDistance, yDistance) > 30) {
  59015. // ok, we pretty much know which way they're going
  59016. // let's lock it in
  59017. primaryScrollAxis = scrollAxis;
  59018. }
  59019. return scrollAxis;
  59020. }
  59021. }
  59022. return 'y';
  59023. }
  59024. var content = {
  59025. element: element[0],
  59026. onDrag: function() {},
  59027. endDrag: function() {},
  59028. setCanScroll: function(canScroll) {
  59029. var c = $element[0].querySelector('.scroll');
  59030. if (!c) {
  59031. return;
  59032. }
  59033. var content = angular.element(c.parentElement);
  59034. if (!content) {
  59035. return;
  59036. }
  59037. // freeze our scroll container if we have one
  59038. var scrollScope = content.scope();
  59039. scrollScope.scrollCtrl && scrollScope.scrollCtrl.freezeScrollShut(!canScroll);
  59040. },
  59041. getTranslateX: function() {
  59042. return $scope.sideMenuContentTranslateX || 0;
  59043. },
  59044. setTranslateX: ionic.animationFrameThrottle(function(amount) {
  59045. var xTransform = content.offsetX + amount;
  59046. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + xTransform + 'px,0,0)';
  59047. $timeout(function() {
  59048. $scope.sideMenuContentTranslateX = amount;
  59049. });
  59050. }),
  59051. setMarginLeft: ionic.animationFrameThrottle(function(amount) {
  59052. if (amount) {
  59053. amount = parseInt(amount, 10);
  59054. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px,0,0)';
  59055. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59056. content.offsetX = amount;
  59057. } else {
  59058. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59059. $element[0].style.width = '';
  59060. content.offsetX = 0;
  59061. }
  59062. }),
  59063. setMarginRight: ionic.animationFrameThrottle(function(amount) {
  59064. if (amount) {
  59065. amount = parseInt(amount, 10);
  59066. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59067. content.offsetX = amount;
  59068. } else {
  59069. $element[0].style.width = '';
  59070. content.offsetX = 0;
  59071. }
  59072. // reset incase left gets grabby
  59073. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59074. }),
  59075. setMarginLeftAndRight: ionic.animationFrameThrottle(function(amountLeft, amountRight) {
  59076. amountLeft = amountLeft && parseInt(amountLeft, 10) || 0;
  59077. amountRight = amountRight && parseInt(amountRight, 10) || 0;
  59078. var amount = amountLeft + amountRight;
  59079. if (amount > 0) {
  59080. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amountLeft + 'px,0,0)';
  59081. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59082. content.offsetX = amountLeft;
  59083. } else {
  59084. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59085. $element[0].style.width = '';
  59086. content.offsetX = 0;
  59087. }
  59088. // reset incase left gets grabby
  59089. //$element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59090. }),
  59091. enableAnimation: function() {
  59092. $scope.animationEnabled = true;
  59093. $element[0].classList.add('menu-animated');
  59094. },
  59095. disableAnimation: function() {
  59096. $scope.animationEnabled = false;
  59097. $element[0].classList.remove('menu-animated');
  59098. },
  59099. offsetX: 0
  59100. };
  59101. sideMenuCtrl.setContent(content);
  59102. // add gesture handlers
  59103. var gestureOpts = { stop_browser_behavior: false };
  59104. gestureOpts.prevent_default_directions = ['left', 'right'];
  59105. var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element, gestureOpts);
  59106. var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element, gestureOpts);
  59107. var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element, gestureOpts);
  59108. var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element, gestureOpts);
  59109. var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element, gestureOpts);
  59110. var releaseGesture = $ionicGesture.on('release', onDragRelease, $element, gestureOpts);
  59111. // Cleanup
  59112. $scope.$on('$destroy', function() {
  59113. if (content) {
  59114. content.element = null;
  59115. content = null;
  59116. }
  59117. $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);
  59118. $ionicGesture.off(dragRightGesture, 'dragright', onDragX);
  59119. $ionicGesture.off(dragUpGesture, 'dragup', onDragY);
  59120. $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);
  59121. $ionicGesture.off(releaseGesture, 'release', onDragRelease);
  59122. $ionicGesture.off(contentTapGesture, 'tap', onContentTap);
  59123. });
  59124. }
  59125. }
  59126. };
  59127. }]);
  59128. IonicModule
  59129. /**
  59130. * @ngdoc directive
  59131. * @name ionSideMenus
  59132. * @module ionic
  59133. * @delegate ionic.service:$ionicSideMenuDelegate
  59134. * @restrict E
  59135. *
  59136. * @description
  59137. * A container element for side menu(s) and the main content. Allows the left and/or right side menu
  59138. * to be toggled by dragging the main content area side to side.
  59139. *
  59140. * To automatically close an opened menu, you can add the {@link ionic.directive:menuClose} attribute
  59141. * directive. The `menu-close` attribute is usually added to links and buttons within
  59142. * `ion-side-menu-content`, so that when the element is clicked, the opened side menu will
  59143. * automatically close.
  59144. *
  59145. * "Burger Icon" toggles can be added to the header with the {@link ionic.directive:menuToggle}
  59146. * attribute directive. Clicking the toggle will open and close the side menu like the `menu-close`
  59147. * directive. The side menu will automatically hide on child pages, but can be overridden with the
  59148. * enable-menu-with-back-views attribute mentioned below.
  59149. *
  59150. * By default, side menus are hidden underneath their side menu content and can be opened by swiping
  59151. * the content left or right or by toggling a button to show the side menu. Additionally, by adding the
  59152. * {@link ionic.directive:exposeAsideWhen} attribute directive to an
  59153. * {@link ionic.directive:ionSideMenu} element directive, a side menu can be given instructions about
  59154. * "when" the menu should be exposed (always viewable).
  59155. *
  59156. * ![Side Menu](http://ionicframework.com.s3.amazonaws.com/docs/controllers/sidemenu.gif)
  59157. *
  59158. * For more information on side menus, check out:
  59159. *
  59160. * - {@link ionic.directive:ionSideMenuContent}
  59161. * - {@link ionic.directive:ionSideMenu}
  59162. * - {@link ionic.directive:menuToggle}
  59163. * - {@link ionic.directive:menuClose}
  59164. * - {@link ionic.directive:exposeAsideWhen}
  59165. *
  59166. * @usage
  59167. * To use side menus, add an `<ion-side-menus>` parent element. This will encompass all pages that have a
  59168. * side menu, and have at least 2 child elements: 1 `<ion-side-menu-content>` for the center content,
  59169. * and one or more `<ion-side-menu>` directives for each side menu(left/right) that you wish to place.
  59170. *
  59171. * ```html
  59172. * <ion-side-menus>
  59173. * <!-- Left menu -->
  59174. * <ion-side-menu side="left">
  59175. * </ion-side-menu>
  59176. *
  59177. * <ion-side-menu-content>
  59178. * <!-- Main content, usually <ion-nav-view> -->
  59179. * </ion-side-menu-content>
  59180. *
  59181. * <!-- Right menu -->
  59182. * <ion-side-menu side="right">
  59183. * </ion-side-menu>
  59184. *
  59185. * </ion-side-menus>
  59186. * ```
  59187. * ```js
  59188. * function ContentController($scope, $ionicSideMenuDelegate) {
  59189. * $scope.toggleLeft = function() {
  59190. * $ionicSideMenuDelegate.toggleLeft();
  59191. * };
  59192. * }
  59193. * ```
  59194. *
  59195. * @param {bool=} enable-menu-with-back-views Determines whether the side menu is enabled when the
  59196. * back button is showing. When set to `false`, any {@link ionic.directive:menuToggle} will be hidden,
  59197. * and the user cannot swipe to open the menu. When going back to the root page of the side menu (the
  59198. * page without a back button visible), then any menuToggle buttons will show again, and menus will be
  59199. * enabled again.
  59200. * @param {string=} delegate-handle The handle used to identify this side menu
  59201. * with {@link ionic.service:$ionicSideMenuDelegate}.
  59202. *
  59203. */
  59204. .directive('ionSideMenus', ['$ionicBody', function($ionicBody) {
  59205. return {
  59206. restrict: 'ECA',
  59207. controller: '$ionicSideMenus',
  59208. compile: function(element, attr) {
  59209. attr.$set('class', (attr['class'] || '') + ' view');
  59210. return { pre: prelink };
  59211. function prelink($scope, $element, $attrs, ctrl) {
  59212. ctrl.enableMenuWithBackViews($scope.$eval($attrs.enableMenuWithBackViews));
  59213. $scope.$on('$ionicExposeAside', function(evt, isAsideExposed) {
  59214. if (!$scope.$exposeAside) $scope.$exposeAside = {};
  59215. $scope.$exposeAside.active = isAsideExposed;
  59216. $ionicBody.enableClass(isAsideExposed, 'aside-open');
  59217. });
  59218. $scope.$on('$ionicView.beforeEnter', function(ev, d) {
  59219. if (d.historyId) {
  59220. $scope.$activeHistoryId = d.historyId;
  59221. }
  59222. });
  59223. $scope.$on('$destroy', function() {
  59224. $ionicBody.removeClass('menu-open', 'aside-open');
  59225. });
  59226. }
  59227. }
  59228. };
  59229. }]);
  59230. /**
  59231. * @ngdoc directive
  59232. * @name ionSlideBox
  59233. * @module ionic
  59234. * @codepen AjgEB
  59235. * @deprecated will be removed in the next Ionic release in favor of the new ion-slides component.
  59236. * Don't depend on the internal behavior of this widget.
  59237. * @delegate ionic.service:$ionicSlideBoxDelegate
  59238. * @restrict E
  59239. * @description
  59240. * The Slide Box is a multi-page container where each page can be swiped or dragged between:
  59241. *
  59242. *
  59243. * @usage
  59244. * ```html
  59245. * <ion-slide-box on-slide-changed="slideHasChanged($index)">
  59246. * <ion-slide>
  59247. * <div class="box blue"><h1>BLUE</h1></div>
  59248. * </ion-slide>
  59249. * <ion-slide>
  59250. * <div class="box yellow"><h1>YELLOW</h1></div>
  59251. * </ion-slide>
  59252. * <ion-slide>
  59253. * <div class="box pink"><h1>PINK</h1></div>
  59254. * </ion-slide>
  59255. * </ion-slide-box>
  59256. * ```
  59257. *
  59258. * @param {string=} delegate-handle The handle used to identify this slideBox
  59259. * with {@link ionic.service:$ionicSlideBoxDelegate}.
  59260. * @param {boolean=} does-continue Whether the slide box should loop.
  59261. * @param {boolean=} auto-play Whether the slide box should automatically slide. Default true if does-continue is true.
  59262. * @param {number=} slide-interval How many milliseconds to wait to change slides (if does-continue is true). Defaults to 4000.
  59263. * @param {boolean=} show-pager Whether a pager should be shown for this slide box. Accepts expressions via `show-pager="{{shouldShow()}}"`. Defaults to true.
  59264. * @param {expression=} pager-click Expression to call when a pager is clicked (if show-pager is true). Is passed the 'index' variable.
  59265. * @param {expression=} on-slide-changed Expression called whenever the slide is changed. Is passed an '$index' variable.
  59266. * @param {expression=} active-slide Model to bind the current slide index to.
  59267. */
  59268. IonicModule
  59269. .directive('ionSlideBox', [
  59270. '$animate',
  59271. '$timeout',
  59272. '$compile',
  59273. '$ionicSlideBoxDelegate',
  59274. '$ionicHistory',
  59275. '$ionicScrollDelegate',
  59276. function($animate, $timeout, $compile, $ionicSlideBoxDelegate, $ionicHistory, $ionicScrollDelegate) {
  59277. return {
  59278. restrict: 'E',
  59279. replace: true,
  59280. transclude: true,
  59281. scope: {
  59282. autoPlay: '=',
  59283. doesContinue: '@',
  59284. slideInterval: '@',
  59285. showPager: '@',
  59286. pagerClick: '&',
  59287. disableScroll: '@',
  59288. onSlideChanged: '&',
  59289. activeSlide: '=?',
  59290. bounce: '@'
  59291. },
  59292. controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
  59293. var _this = this;
  59294. var continuous = $scope.$eval($scope.doesContinue) === true;
  59295. var bouncing = ($scope.$eval($scope.bounce) !== false); //Default to true
  59296. var shouldAutoPlay = isDefined($attrs.autoPlay) ? !!$scope.autoPlay : false;
  59297. var slideInterval = shouldAutoPlay ? $scope.$eval($scope.slideInterval) || 4000 : 0;
  59298. var slider = new ionic.views.Slider({
  59299. el: $element[0],
  59300. auto: slideInterval,
  59301. continuous: continuous,
  59302. startSlide: $scope.activeSlide,
  59303. bouncing: bouncing,
  59304. slidesChanged: function() {
  59305. $scope.currentSlide = slider.currentIndex();
  59306. // Try to trigger a digest
  59307. $timeout(function() {});
  59308. },
  59309. callback: function(slideIndex) {
  59310. $scope.currentSlide = slideIndex;
  59311. $scope.onSlideChanged({ index: $scope.currentSlide, $index: $scope.currentSlide});
  59312. $scope.$parent.$broadcast('slideBox.slideChanged', slideIndex);
  59313. $scope.activeSlide = slideIndex;
  59314. // Try to trigger a digest
  59315. $timeout(function() {});
  59316. },
  59317. onDrag: function() {
  59318. freezeAllScrolls(true);
  59319. },
  59320. onDragEnd: function() {
  59321. freezeAllScrolls(false);
  59322. }
  59323. });
  59324. function freezeAllScrolls(shouldFreeze) {
  59325. if (shouldFreeze && !_this.isScrollFreeze) {
  59326. $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);
  59327. } else if (!shouldFreeze && _this.isScrollFreeze) {
  59328. $ionicScrollDelegate.freezeAllScrolls(false);
  59329. }
  59330. _this.isScrollFreeze = shouldFreeze;
  59331. }
  59332. slider.enableSlide($scope.$eval($attrs.disableScroll) !== true);
  59333. $scope.$watch('activeSlide', function(nv) {
  59334. if (isDefined(nv)) {
  59335. slider.slide(nv);
  59336. }
  59337. });
  59338. $scope.$on('slideBox.nextSlide', function() {
  59339. slider.next();
  59340. });
  59341. $scope.$on('slideBox.prevSlide', function() {
  59342. slider.prev();
  59343. });
  59344. $scope.$on('slideBox.setSlide', function(e, index) {
  59345. slider.slide(index);
  59346. });
  59347. //Exposed for testing
  59348. this.__slider = slider;
  59349. var deregisterInstance = $ionicSlideBoxDelegate._registerInstance(
  59350. slider, $attrs.delegateHandle, function() {
  59351. return $ionicHistory.isActiveScope($scope);
  59352. }
  59353. );
  59354. $scope.$on('$destroy', function() {
  59355. deregisterInstance();
  59356. slider.kill();
  59357. });
  59358. this.slidesCount = function() {
  59359. return slider.slidesCount();
  59360. };
  59361. this.onPagerClick = function(index) {
  59362. $scope.pagerClick({index: index});
  59363. };
  59364. $timeout(function() {
  59365. slider.load();
  59366. });
  59367. }],
  59368. template: '<div class="slider">' +
  59369. '<div class="slider-slides" ng-transclude>' +
  59370. '</div>' +
  59371. '</div>',
  59372. link: function($scope, $element, $attr) {
  59373. // Disable ngAnimate for slidebox and its children
  59374. $animate.enabled($element, false);
  59375. // if showPager is undefined, show the pager
  59376. if (!isDefined($attr.showPager)) {
  59377. $scope.showPager = true;
  59378. getPager().toggleClass('hide', !true);
  59379. }
  59380. $attr.$observe('showPager', function(show) {
  59381. if (show === undefined) return;
  59382. show = $scope.$eval(show);
  59383. getPager().toggleClass('hide', !show);
  59384. });
  59385. var pager;
  59386. function getPager() {
  59387. if (!pager) {
  59388. var childScope = $scope.$new();
  59389. pager = jqLite('<ion-pager></ion-pager>');
  59390. $element.append(pager);
  59391. pager = $compile(pager)(childScope);
  59392. }
  59393. return pager;
  59394. }
  59395. }
  59396. };
  59397. }])
  59398. .directive('ionSlide', function() {
  59399. return {
  59400. restrict: 'E',
  59401. require: '?^ionSlideBox',
  59402. compile: function(element) {
  59403. element.addClass('slider-slide');
  59404. }
  59405. };
  59406. })
  59407. .directive('ionPager', function() {
  59408. return {
  59409. restrict: 'E',
  59410. replace: true,
  59411. require: '^ionSlideBox',
  59412. template: '<div class="slider-pager"><span class="slider-pager-page" ng-repeat="slide in numSlides() track by $index" ng-class="{active: $index == currentSlide}" ng-click="pagerClick($index)"><i class="icon ion-record"></i></span></div>',
  59413. link: function($scope, $element, $attr, slideBox) {
  59414. var selectPage = function(index) {
  59415. var children = $element[0].children;
  59416. var length = children.length;
  59417. for (var i = 0; i < length; i++) {
  59418. if (i == index) {
  59419. children[i].classList.add('active');
  59420. } else {
  59421. children[i].classList.remove('active');
  59422. }
  59423. }
  59424. };
  59425. $scope.pagerClick = function(index) {
  59426. slideBox.onPagerClick(index);
  59427. };
  59428. $scope.numSlides = function() {
  59429. return new Array(slideBox.slidesCount());
  59430. };
  59431. $scope.$watch('currentSlide', function(v) {
  59432. selectPage(v);
  59433. });
  59434. }
  59435. };
  59436. });
  59437. /**
  59438. * @ngdoc directive
  59439. * @name ionSlides
  59440. * @module ionic
  59441. * @delegate ionic.service:$ionicSlideBoxDelegate
  59442. * @restrict E
  59443. * @description
  59444. * The Slides component is a powerful multi-page container where each page can be swiped or dragged between.
  59445. *
  59446. * Note: this is a new version of the Ionic Slide Box based on the [Swiper](http://www.idangero.us/swiper/#.Vmc1J-ODFBc) widget from
  59447. * [idangerous](http://www.idangero.us/).
  59448. *
  59449. * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)
  59450. *
  59451. * @usage
  59452. * ```html
  59453. * <ion-content scroll="false">
  59454. * <ion-slides options="options" slider="data.slider">
  59455. * <ion-slide-page>
  59456. * <div class="box blue"><h1>BLUE</h1></div>
  59457. * </ion-slide-page>
  59458. * <ion-slide-page>
  59459. * <div class="box yellow"><h1>YELLOW</h1></div>
  59460. * </ion-slide-page>
  59461. * <ion-slide-page>
  59462. * <div class="box pink"><h1>PINK</h1></div>
  59463. * </ion-slide-page>
  59464. * </ion-slides>
  59465. * </ion-content>
  59466. * ```
  59467. *
  59468. * ```js
  59469. * $scope.options = {
  59470. * loop: false,
  59471. * effect: 'fade',
  59472. * speed: 500,
  59473. * }
  59474. *
  59475. * $scope.$on("$ionicSlides.sliderInitialized", function(event, data){
  59476. * // data.slider is the instance of Swiper
  59477. * $scope.slider = data.slider;
  59478. * });
  59479. *
  59480. * $scope.$on("$ionicSlides.slideChangeStart", function(event, data){
  59481. * console.log('Slide change is beginning');
  59482. * });
  59483. *
  59484. * $scope.$on("$ionicSlides.slideChangeEnd", function(event, data){
  59485. * // note: the indexes are 0-based
  59486. * $scope.activeIndex = data.activeIndex;
  59487. * $scope.previousIndex = data.previousIndex;
  59488. * });
  59489. *
  59490. * ```
  59491. *
  59492. * ## Slide Events
  59493. *
  59494. * The slides component dispatches events when the active slide changes
  59495. *
  59496. * <table class="table">
  59497. * <tr>
  59498. * <td><code>$ionicSlides.slideChangeStart</code></td>
  59499. * <td>This event is emitted when a slide change begins</td>
  59500. * </tr>
  59501. * <tr>
  59502. * <td><code>$ionicSlides.slideChangeEnd</code></td>
  59503. * <td>This event is emitted when a slide change completes</td>
  59504. * </tr>
  59505. * <tr>
  59506. * <td><code>$ionicSlides.sliderInitialized</code></td>
  59507. * <td>This event is emitted when the slider is initialized. It provides access to an instance of the slider.</td>
  59508. * </tr>
  59509. * </table>
  59510. *
  59511. *
  59512. * ## Updating Slides Dynamically
  59513. * When applying data to the slider at runtime, typically everything will work as expected.
  59514. *
  59515. * In the event that the slides are looped, use the `updateLoop` method on the slider to ensure the slides update correctly.
  59516. *
  59517. * ```
  59518. * $scope.$on("$ionicSlides.sliderInitialized", function(event, data){
  59519. * // grab an instance of the slider
  59520. * $scope.slider = data.slider;
  59521. * });
  59522. *
  59523. * function dataChangeHandler(){
  59524. * // call this function when data changes, such as an HTTP request, etc
  59525. * if ( $scope.slider ){
  59526. * $scope.slider.updateLoop();
  59527. * }
  59528. * }
  59529. * ```
  59530. *
  59531. */
  59532. IonicModule
  59533. .directive('ionSlides', [
  59534. '$animate',
  59535. '$timeout',
  59536. '$compile',
  59537. function($animate, $timeout, $compile) {
  59538. return {
  59539. restrict: 'E',
  59540. transclude: true,
  59541. scope: {
  59542. options: '=',
  59543. slider: '='
  59544. },
  59545. template: '<div class="swiper-container">' +
  59546. '<div class="swiper-wrapper" ng-transclude>' +
  59547. '</div>' +
  59548. '<div ng-hide="!showPager" class="swiper-pagination"></div>' +
  59549. '</div>',
  59550. controller: ['$scope', '$element', function($scope, $element) {
  59551. var _this = this;
  59552. this.update = function() {
  59553. $timeout(function() {
  59554. if (!_this.__slider) {
  59555. return;
  59556. }
  59557. _this.__slider.update();
  59558. if (_this._options.loop) {
  59559. _this.__slider.createLoop();
  59560. }
  59561. var slidesLength = _this.__slider.slides.length;
  59562. // Don't allow pager to show with > 10 slides
  59563. if (slidesLength > 10) {
  59564. $scope.showPager = false;
  59565. }
  59566. // When slide index is greater than total then slide to last index
  59567. if (_this.__slider.activeIndex > slidesLength - 1) {
  59568. _this.__slider.slideTo(slidesLength - 1);
  59569. }
  59570. });
  59571. };
  59572. this.rapidUpdate = ionic.debounce(function() {
  59573. _this.update();
  59574. }, 50);
  59575. this.getSlider = function() {
  59576. return _this.__slider;
  59577. };
  59578. var options = $scope.options || {};
  59579. var newOptions = angular.extend({
  59580. pagination: $element.children().children()[1],
  59581. paginationClickable: true,
  59582. lazyLoading: true,
  59583. preloadImages: false
  59584. }, options);
  59585. this._options = newOptions;
  59586. $timeout(function() {
  59587. var slider = new ionic.views.Swiper($element.children()[0], newOptions, $scope, $compile);
  59588. $scope.$emit("$ionicSlides.sliderInitialized", { slider: slider });
  59589. _this.__slider = slider;
  59590. $scope.slider = _this.__slider;
  59591. $scope.$on('$destroy', function() {
  59592. slider.destroy();
  59593. _this.__slider = null;
  59594. });
  59595. });
  59596. $timeout(function() {
  59597. // if it's a loop, render the slides again just incase
  59598. _this.rapidUpdate();
  59599. }, 200);
  59600. }],
  59601. link: function($scope) {
  59602. $scope.showPager = true;
  59603. // Disable ngAnimate for slidebox and its children
  59604. //$animate.enabled(false, $element);
  59605. }
  59606. };
  59607. }])
  59608. .directive('ionSlidePage', [function() {
  59609. return {
  59610. restrict: 'E',
  59611. require: '?^ionSlides',
  59612. transclude: true,
  59613. replace: true,
  59614. template: '<div class="swiper-slide" ng-transclude></div>',
  59615. link: function($scope, $element, $attr, ionSlidesCtrl) {
  59616. ionSlidesCtrl.rapidUpdate();
  59617. $scope.$on('$destroy', function() {
  59618. ionSlidesCtrl.rapidUpdate();
  59619. });
  59620. }
  59621. };
  59622. }]);
  59623. /**
  59624. * @ngdoc directive
  59625. * @name ionSpinner
  59626. * @module ionic
  59627. * @restrict E
  59628. *
  59629. * @description
  59630. * The `ionSpinner` directive provides a variety of animated spinners.
  59631. * Spinners enables you to give your users feedback that the app is
  59632. * processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.
  59633. * By default, the {@link ionic.directive:ionRefresher} feature uses this spinner, rather
  59634. * than rotating font icons (previously included in [ionicons](http://ionicons.com/)).
  59635. * While font icons are great for simple or stationary graphics, they're not suited to
  59636. * provide great animations, which is why Ionic uses SVG instead.
  59637. *
  59638. * Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner
  59639. * for the platform on which it's running. Under the hood, the `ionSpinner` directive dynamically
  59640. * builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs
  59641. * within 3KB.
  59642. *
  59643. * <style>
  59644. * .spinner-table {
  59645. * max-width: 280px;
  59646. * }
  59647. * .spinner-table tbody > tr > th, .spinner-table tbody > tr > td {
  59648. * vertical-align: middle;
  59649. * width: 42px;
  59650. * height: 42px;
  59651. * }
  59652. * .spinner {
  59653. * stroke: #444;
  59654. * fill: #444; }
  59655. * .spinner svg {
  59656. * width: 28px;
  59657. * height: 28px; }
  59658. * .spinner.spinner-inverse {
  59659. * stroke: #fff;
  59660. * fill: #fff; }
  59661. *
  59662. * .spinner-android {
  59663. * stroke: #4b8bf4; }
  59664. *
  59665. * .spinner-ios, .spinner-ios-small {
  59666. * stroke: #69717d; }
  59667. *
  59668. * .spinner-spiral .stop1 {
  59669. * stop-color: #fff;
  59670. * stop-opacity: 0; }
  59671. * .spinner-spiral.spinner-inverse .stop1 {
  59672. * stop-color: #000; }
  59673. * .spinner-spiral.spinner-inverse .stop2 {
  59674. * stop-color: #fff; }
  59675. * </style>
  59676. *
  59677. * <script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
  59678. * <table class="table spinner-table" ng-app="ionic">
  59679. * <tr>
  59680. * <th>
  59681. * <code>android</code>
  59682. * </th>
  59683. * <td>
  59684. * <ion-spinner icon="android"></ion-spinner>
  59685. * </td>
  59686. * </tr>
  59687. * <tr>
  59688. * <th>
  59689. * <code>ios</code>
  59690. * </th>
  59691. * <td>
  59692. * <ion-spinner icon="ios"></ion-spinner>
  59693. * </td>
  59694. * </tr>
  59695. * <tr>
  59696. * <th>
  59697. * <code>ios-small</code>
  59698. * </th>
  59699. * <td>
  59700. * <ion-spinner icon="ios-small"></ion-spinner>
  59701. * </td>
  59702. * </tr>
  59703. * <tr>
  59704. * <th>
  59705. * <code>bubbles</code>
  59706. * </th>
  59707. * <td>
  59708. * <ion-spinner icon="bubbles"></ion-spinner>
  59709. * </td>
  59710. * </tr>
  59711. * <tr>
  59712. * <th>
  59713. * <code>circles</code>
  59714. * </th>
  59715. * <td>
  59716. * <ion-spinner icon="circles"></ion-spinner>
  59717. * </td>
  59718. * </tr>
  59719. * <tr>
  59720. * <th>
  59721. * <code>crescent</code>
  59722. * </th>
  59723. * <td>
  59724. * <ion-spinner icon="crescent"></ion-spinner>
  59725. * </td>
  59726. * </tr>
  59727. * <tr>
  59728. * <th>
  59729. * <code>dots</code>
  59730. * </th>
  59731. * <td>
  59732. * <ion-spinner icon="dots"></ion-spinner>
  59733. * </td>
  59734. * </tr>
  59735. * <tr>
  59736. * <th>
  59737. * <code>lines</code>
  59738. * </th>
  59739. * <td>
  59740. * <ion-spinner icon="lines"></ion-spinner>
  59741. * </td>
  59742. * </tr>
  59743. * <tr>
  59744. * <th>
  59745. * <code>ripple</code>
  59746. * </th>
  59747. * <td>
  59748. * <ion-spinner icon="ripple"></ion-spinner>
  59749. * </td>
  59750. * </tr>
  59751. * <tr>
  59752. * <th>
  59753. * <code>spiral</code>
  59754. * </th>
  59755. * <td>
  59756. * <ion-spinner icon="spiral"></ion-spinner>
  59757. * </td>
  59758. * </tr>
  59759. * </table>
  59760. *
  59761. * Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript
  59762. * so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,
  59763. * and scaled to any size.
  59764. *
  59765. *
  59766. * @usage
  59767. * The following code would use the default spinner for the platform it's running from. If it's neither
  59768. * iOS or Android, it'll default to use `ios`.
  59769. *
  59770. * ```html
  59771. * <ion-spinner></ion-spinner>
  59772. * ```
  59773. *
  59774. * By setting the `icon` attribute, you can specify which spinner to use, no matter what
  59775. * the platform is.
  59776. *
  59777. * ```html
  59778. * <ion-spinner icon="spiral"></ion-spinner>
  59779. * ```
  59780. *
  59781. * ## Spinner Colors
  59782. * Like with most of Ionic's other components, spinners can also be styled using
  59783. * Ionic's standard color naming convention. For example:
  59784. *
  59785. * ```html
  59786. * <ion-spinner class="spinner-energized"></ion-spinner>
  59787. * ```
  59788. *
  59789. *
  59790. * ## Styling SVG with CSS
  59791. * One cool thing about SVG is its ability to be styled with CSS! Some of the properties
  59792. * have different names, for example, SVG uses the term `stroke` instead of `border`, and
  59793. * `fill` instead of `background-color`.
  59794. *
  59795. * ```css
  59796. * .spinner svg {
  59797. * width: 28px;
  59798. * height: 28px;
  59799. * stroke: #444;
  59800. * fill: #444;
  59801. * }
  59802. * ```
  59803. *
  59804. */
  59805. IonicModule
  59806. .directive('ionSpinner', function() {
  59807. return {
  59808. restrict: 'E',
  59809. controller: '$ionicSpinner',
  59810. link: function($scope, $element, $attrs, ctrl) {
  59811. var spinnerName = ctrl.init();
  59812. $element.addClass('spinner spinner-' + spinnerName);
  59813. $element.on('$destroy', function onDestroy() {
  59814. ctrl.stop();
  59815. });
  59816. }
  59817. };
  59818. });
  59819. /**
  59820. * @ngdoc directive
  59821. * @name ionTab
  59822. * @module ionic
  59823. * @restrict E
  59824. * @parent ionic.directive:ionTabs
  59825. *
  59826. * @description
  59827. * Contains a tab's content. The content only exists while the given tab is selected.
  59828. *
  59829. * Each ionTab has its own view history.
  59830. *
  59831. * @usage
  59832. * ```html
  59833. * <ion-tab
  59834. * title="Tab!"
  59835. * icon="my-icon"
  59836. * href="#/tab/tab-link"
  59837. * on-select="onTabSelected()"
  59838. * on-deselect="onTabDeselected()">
  59839. * </ion-tab>
  59840. * ```
  59841. * For a complete, working tab bar example, see the {@link ionic.directive:ionTabs} documentation.
  59842. *
  59843. * @param {string} title The title of the tab.
  59844. * @param {string=} href The link that this tab will navigate to when tapped.
  59845. * @param {string=} icon The icon of the tab. If given, this will become the default for icon-on and icon-off.
  59846. * @param {string=} icon-on The icon of the tab while it is selected.
  59847. * @param {string=} icon-off The icon of the tab while it is not selected.
  59848. * @param {expression=} badge The badge to put on this tab (usually a number).
  59849. * @param {expression=} badge-style The style of badge to put on this tab (eg: badge-positive).
  59850. * @param {expression=} on-select Called when this tab is selected.
  59851. * @param {expression=} on-deselect Called when this tab is deselected.
  59852. * @param {expression=} ng-click By default, the tab will be selected on click. If ngClick is set, it will not. You can explicitly switch tabs using {@link ionic.service:$ionicTabsDelegate#select $ionicTabsDelegate.select()}.
  59853. * @param {expression=} hidden Whether the tab is to be hidden or not.
  59854. * @param {expression=} disabled Whether the tab is to be disabled or not.
  59855. */
  59856. IonicModule
  59857. .directive('ionTab', [
  59858. '$compile',
  59859. '$ionicConfig',
  59860. '$ionicBind',
  59861. '$ionicViewSwitcher',
  59862. function($compile, $ionicConfig, $ionicBind, $ionicViewSwitcher) {
  59863. //Returns ' key="value"' if value exists
  59864. function attrStr(k, v) {
  59865. return isDefined(v) ? ' ' + k + '="' + v + '"' : '';
  59866. }
  59867. return {
  59868. restrict: 'E',
  59869. require: ['^ionTabs', 'ionTab'],
  59870. controller: '$ionicTab',
  59871. scope: true,
  59872. compile: function(element, attr) {
  59873. //We create the tabNavTemplate in the compile phase so that the
  59874. //attributes we pass down won't be interpolated yet - we want
  59875. //to pass down the 'raw' versions of the attributes
  59876. var tabNavTemplate = '<ion-tab-nav' +
  59877. attrStr('ng-click', attr.ngClick) +
  59878. attrStr('title', attr.title) +
  59879. attrStr('icon', attr.icon) +
  59880. attrStr('icon-on', attr.iconOn) +
  59881. attrStr('icon-off', attr.iconOff) +
  59882. attrStr('badge', attr.badge) +
  59883. attrStr('badge-style', attr.badgeStyle) +
  59884. attrStr('hidden', attr.hidden) +
  59885. attrStr('disabled', attr.disabled) +
  59886. attrStr('class', attr['class']) +
  59887. '></ion-tab-nav>';
  59888. //Remove the contents of the element so we can compile them later, if tab is selected
  59889. var tabContentEle = document.createElement('div');
  59890. for (var x = 0; x < element[0].children.length; x++) {
  59891. tabContentEle.appendChild(element[0].children[x].cloneNode(true));
  59892. }
  59893. var childElementCount = tabContentEle.childElementCount;
  59894. element.empty();
  59895. var navViewName, isNavView;
  59896. if (childElementCount) {
  59897. if (tabContentEle.children[0].tagName === 'ION-NAV-VIEW') {
  59898. // get the name if it's a nav-view
  59899. navViewName = tabContentEle.children[0].getAttribute('name');
  59900. tabContentEle.children[0].classList.add('view-container');
  59901. isNavView = true;
  59902. }
  59903. if (childElementCount === 1) {
  59904. // make the 1 child element the primary tab content container
  59905. tabContentEle = tabContentEle.children[0];
  59906. }
  59907. if (!isNavView) tabContentEle.classList.add('pane');
  59908. tabContentEle.classList.add('tab-content');
  59909. }
  59910. return function link($scope, $element, $attr, ctrls) {
  59911. var childScope;
  59912. var childElement;
  59913. var tabsCtrl = ctrls[0];
  59914. var tabCtrl = ctrls[1];
  59915. var isTabContentAttached = false;
  59916. $scope.$tabSelected = false;
  59917. $ionicBind($scope, $attr, {
  59918. onSelect: '&',
  59919. onDeselect: '&',
  59920. title: '@',
  59921. uiSref: '@',
  59922. href: '@'
  59923. });
  59924. tabsCtrl.add($scope);
  59925. $scope.$on('$destroy', function() {
  59926. if (!$scope.$tabsDestroy) {
  59927. // if the containing ionTabs directive is being destroyed
  59928. // then don't bother going through the controllers remove
  59929. // method, since remove will reset the active tab as each tab
  59930. // is being destroyed, causing unnecessary view loads and transitions
  59931. tabsCtrl.remove($scope);
  59932. }
  59933. tabNavElement.isolateScope().$destroy();
  59934. tabNavElement.remove();
  59935. tabNavElement = tabContentEle = childElement = null;
  59936. });
  59937. //Remove title attribute so browser-tooltip does not apear
  59938. $element[0].removeAttribute('title');
  59939. if (navViewName) {
  59940. tabCtrl.navViewName = $scope.navViewName = navViewName;
  59941. }
  59942. $scope.$on('$stateChangeSuccess', selectIfMatchesState);
  59943. selectIfMatchesState();
  59944. function selectIfMatchesState() {
  59945. if (tabCtrl.tabMatchesState()) {
  59946. tabsCtrl.select($scope, false);
  59947. }
  59948. }
  59949. var tabNavElement = jqLite(tabNavTemplate);
  59950. tabNavElement.data('$ionTabsController', tabsCtrl);
  59951. tabNavElement.data('$ionTabController', tabCtrl);
  59952. tabsCtrl.$tabsElement.append($compile(tabNavElement)($scope));
  59953. function tabSelected(isSelected) {
  59954. if (isSelected && childElementCount) {
  59955. // this tab is being selected
  59956. // check if the tab is already in the DOM
  59957. // only do this if the tab has child elements
  59958. if (!isTabContentAttached) {
  59959. // tab should be selected and is NOT in the DOM
  59960. // create a new scope and append it
  59961. childScope = $scope.$new();
  59962. childElement = jqLite(tabContentEle);
  59963. $ionicViewSwitcher.viewEleIsActive(childElement, true);
  59964. tabsCtrl.$element.append(childElement);
  59965. $compile(childElement)(childScope);
  59966. isTabContentAttached = true;
  59967. }
  59968. // remove the hide class so the tabs content shows up
  59969. $ionicViewSwitcher.viewEleIsActive(childElement, true);
  59970. } else if (isTabContentAttached && childElement) {
  59971. // this tab should NOT be selected, and it is already in the DOM
  59972. if ($ionicConfig.views.maxCache() > 0) {
  59973. // keep the tabs in the DOM, only css hide it
  59974. $ionicViewSwitcher.viewEleIsActive(childElement, false);
  59975. } else {
  59976. // do not keep tabs in the DOM
  59977. destroyTab();
  59978. }
  59979. }
  59980. }
  59981. function destroyTab() {
  59982. childScope && childScope.$destroy();
  59983. isTabContentAttached && childElement && childElement.remove();
  59984. tabContentEle.innerHTML = '';
  59985. isTabContentAttached = childScope = childElement = null;
  59986. }
  59987. $scope.$watch('$tabSelected', tabSelected);
  59988. $scope.$on('$ionicView.afterEnter', function() {
  59989. $ionicViewSwitcher.viewEleIsActive(childElement, $scope.$tabSelected);
  59990. });
  59991. $scope.$on('$ionicView.clearCache', function() {
  59992. if (!$scope.$tabSelected) {
  59993. destroyTab();
  59994. }
  59995. });
  59996. };
  59997. }
  59998. };
  59999. }]);
  60000. IonicModule
  60001. .directive('ionTabNav', [function() {
  60002. return {
  60003. restrict: 'E',
  60004. replace: true,
  60005. require: ['^ionTabs', '^ionTab'],
  60006. template:
  60007. '<a ng-class="{\'has-badge\':badge, \'tab-hidden\':isHidden(), \'tab-item-active\': isTabActive()}" ' +
  60008. ' ng-disabled="disabled()" class="tab-item">' +
  60009. '<span class="badge {{badgeStyle}}" ng-if="badge">{{badge}}</span>' +
  60010. '<i class="icon {{getIcon()}}" ng-if="getIcon()"></i>' +
  60011. '<span class="tab-title" ng-bind-html="title"></span>' +
  60012. '</a>',
  60013. scope: {
  60014. title: '@',
  60015. icon: '@',
  60016. iconOn: '@',
  60017. iconOff: '@',
  60018. badge: '=',
  60019. hidden: '@',
  60020. disabled: '&',
  60021. badgeStyle: '@',
  60022. 'class': '@'
  60023. },
  60024. link: function($scope, $element, $attrs, ctrls) {
  60025. var tabsCtrl = ctrls[0],
  60026. tabCtrl = ctrls[1];
  60027. //Remove title attribute so browser-tooltip does not apear
  60028. $element[0].removeAttribute('title');
  60029. $scope.selectTab = function(e) {
  60030. e.preventDefault();
  60031. tabsCtrl.select(tabCtrl.$scope, true);
  60032. };
  60033. if (!$attrs.ngClick) {
  60034. $element.on('click', function(event) {
  60035. $scope.$apply(function() {
  60036. $scope.selectTab(event);
  60037. });
  60038. });
  60039. }
  60040. $scope.isHidden = function() {
  60041. if ($attrs.hidden === 'true' || $attrs.hidden === true) return true;
  60042. return false;
  60043. };
  60044. $scope.getIconOn = function() {
  60045. return $scope.iconOn || $scope.icon;
  60046. };
  60047. $scope.getIconOff = function() {
  60048. return $scope.iconOff || $scope.icon;
  60049. };
  60050. $scope.isTabActive = function() {
  60051. return tabsCtrl.selectedTab() === tabCtrl.$scope;
  60052. };
  60053. $scope.getIcon = function() {
  60054. if ( tabsCtrl.selectedTab() === tabCtrl.$scope ) {
  60055. // active
  60056. return $scope.iconOn || $scope.icon;
  60057. }
  60058. else {
  60059. // inactive
  60060. return $scope.iconOff || $scope.icon;
  60061. }
  60062. };
  60063. }
  60064. };
  60065. }]);
  60066. /**
  60067. * @ngdoc directive
  60068. * @name ionTabs
  60069. * @module ionic
  60070. * @delegate ionic.service:$ionicTabsDelegate
  60071. * @restrict E
  60072. * @codepen odqCz
  60073. *
  60074. * @description
  60075. * Powers a multi-tabbed interface with a Tab Bar and a set of "pages" that can be tabbed
  60076. * through.
  60077. *
  60078. * Assign any [tabs class](/docs/components#tabs) to the element to define
  60079. * its look and feel.
  60080. *
  60081. * For iOS, tabs will appear at the bottom of the screen. For Android, tabs will be at the top
  60082. * of the screen, below the nav-bar. This follows each OS's design specification, but can be
  60083. * configured with the {@link ionic.provider:$ionicConfigProvider}.
  60084. *
  60085. * See the {@link ionic.directive:ionTab} directive's documentation for more details on
  60086. * individual tabs.
  60087. *
  60088. * Note: do not place ion-tabs inside of an ion-content element; it has been known to cause a
  60089. * certain CSS bug.
  60090. *
  60091. * @usage
  60092. * ```html
  60093. * <ion-tabs class="tabs-positive tabs-icon-top">
  60094. *
  60095. * <ion-tab title="Home" icon-on="ion-ios-filing" icon-off="ion-ios-filing-outline">
  60096. * <!-- Tab 1 content -->
  60097. * </ion-tab>
  60098. *
  60099. * <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
  60100. * <!-- Tab 2 content -->
  60101. * </ion-tab>
  60102. *
  60103. * <ion-tab title="Settings" icon-on="ion-ios-gear" icon-off="ion-ios-gear-outline">
  60104. * <!-- Tab 3 content -->
  60105. * </ion-tab>
  60106. *
  60107. * </ion-tabs>
  60108. * ```
  60109. *
  60110. * @param {string=} delegate-handle The handle used to identify these tabs
  60111. * with {@link ionic.service:$ionicTabsDelegate}.
  60112. */
  60113. IonicModule
  60114. .directive('ionTabs', [
  60115. '$ionicTabsDelegate',
  60116. '$ionicConfig',
  60117. function($ionicTabsDelegate, $ionicConfig) {
  60118. return {
  60119. restrict: 'E',
  60120. scope: true,
  60121. controller: '$ionicTabs',
  60122. compile: function(tElement) {
  60123. //We cannot use regular transclude here because it breaks element.data()
  60124. //inheritance on compile
  60125. var innerElement = jqLite('<div class="tab-nav tabs">');
  60126. innerElement.append(tElement.contents());
  60127. tElement.append(innerElement)
  60128. .addClass('tabs-' + $ionicConfig.tabs.position() + ' tabs-' + $ionicConfig.tabs.style());
  60129. return { pre: prelink, post: postLink };
  60130. function prelink($scope, $element, $attr, tabsCtrl) {
  60131. var deregisterInstance = $ionicTabsDelegate._registerInstance(
  60132. tabsCtrl, $attr.delegateHandle, tabsCtrl.hasActiveScope
  60133. );
  60134. tabsCtrl.$scope = $scope;
  60135. tabsCtrl.$element = $element;
  60136. tabsCtrl.$tabsElement = jqLite($element[0].querySelector('.tabs'));
  60137. $scope.$watch(function() { return $element[0].className; }, function(value) {
  60138. var isTabsTop = value.indexOf('tabs-top') !== -1;
  60139. var isHidden = value.indexOf('tabs-item-hide') !== -1;
  60140. $scope.$hasTabs = !isTabsTop && !isHidden;
  60141. $scope.$hasTabsTop = isTabsTop && !isHidden;
  60142. $scope.$emit('$ionicTabs.top', $scope.$hasTabsTop);
  60143. });
  60144. function emitLifecycleEvent(ev, data) {
  60145. ev.stopPropagation();
  60146. var previousSelectedTab = tabsCtrl.previousSelectedTab();
  60147. if (previousSelectedTab) {
  60148. previousSelectedTab.$broadcast(ev.name.replace('NavView', 'Tabs'), data);
  60149. }
  60150. }
  60151. $scope.$on('$ionicNavView.beforeLeave', emitLifecycleEvent);
  60152. $scope.$on('$ionicNavView.afterLeave', emitLifecycleEvent);
  60153. $scope.$on('$ionicNavView.leave', emitLifecycleEvent);
  60154. $scope.$on('$destroy', function() {
  60155. // variable to inform child tabs that they're all being blown away
  60156. // used so that while destorying an individual tab, each one
  60157. // doesn't select the next tab as the active one, which causes unnecessary
  60158. // loading of tab views when each will eventually all go away anyway
  60159. $scope.$tabsDestroy = true;
  60160. deregisterInstance();
  60161. tabsCtrl.$tabsElement = tabsCtrl.$element = tabsCtrl.$scope = innerElement = null;
  60162. delete $scope.$hasTabs;
  60163. delete $scope.$hasTabsTop;
  60164. });
  60165. }
  60166. function postLink($scope, $element, $attr, tabsCtrl) {
  60167. if (!tabsCtrl.selectedTab()) {
  60168. // all the tabs have been added
  60169. // but one hasn't been selected yet
  60170. tabsCtrl.select(0);
  60171. }
  60172. }
  60173. }
  60174. };
  60175. }]);
  60176. /**
  60177. * @ngdoc directive
  60178. * @name ionTitle
  60179. * @module ionic
  60180. * @restrict E
  60181. *
  60182. * Used for titles in header and nav bars. New in 1.2
  60183. *
  60184. * Identical to <div class="title"> but with future compatibility for Ionic 2
  60185. *
  60186. * @usage
  60187. *
  60188. * ```html
  60189. * <ion-nav-bar>
  60190. * <ion-title>Hello</ion-title>
  60191. * <ion-nav-bar>
  60192. * ```
  60193. */
  60194. IonicModule
  60195. .directive('ionTitle', [function() {
  60196. return {
  60197. restrict: 'E',
  60198. compile: function(element) {
  60199. element.addClass('title');
  60200. }
  60201. };
  60202. }]);
  60203. /**
  60204. * @ngdoc directive
  60205. * @name ionToggle
  60206. * @module ionic
  60207. * @codepen tfAzj
  60208. * @restrict E
  60209. *
  60210. * @description
  60211. * A toggle is an animated switch which binds a given model to a boolean.
  60212. *
  60213. * Allows dragging of the switch's nub.
  60214. *
  60215. * The toggle behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]) otherwise.
  60216. *
  60217. * @param toggle-class {string=} Sets the CSS class on the inner `label.toggle` element created by the directive.
  60218. *
  60219. * @usage
  60220. * Below is an example of a toggle directive which is wired up to the `airplaneMode` model
  60221. * and has the `toggle-calm` CSS class assigned to the inner element.
  60222. *
  60223. * ```html
  60224. * <ion-toggle ng-model="airplaneMode" toggle-class="toggle-calm">Airplane Mode</ion-toggle>
  60225. * ```
  60226. */
  60227. IonicModule
  60228. .directive('ionToggle', [
  60229. '$timeout',
  60230. '$ionicConfig',
  60231. function($timeout, $ionicConfig) {
  60232. return {
  60233. restrict: 'E',
  60234. replace: true,
  60235. require: '?ngModel',
  60236. transclude: true,
  60237. template:
  60238. '<div class="item item-toggle">' +
  60239. '<div ng-transclude></div>' +
  60240. '<label class="toggle">' +
  60241. '<input type="checkbox">' +
  60242. '<div class="track">' +
  60243. '<div class="handle"></div>' +
  60244. '</div>' +
  60245. '</label>' +
  60246. '</div>',
  60247. compile: function(element, attr) {
  60248. var input = element.find('input');
  60249. forEach({
  60250. 'name': attr.name,
  60251. 'ng-value': attr.ngValue,
  60252. 'ng-model': attr.ngModel,
  60253. 'ng-checked': attr.ngChecked,
  60254. 'ng-disabled': attr.ngDisabled,
  60255. 'ng-true-value': attr.ngTrueValue,
  60256. 'ng-false-value': attr.ngFalseValue,
  60257. 'ng-change': attr.ngChange,
  60258. 'ng-required': attr.ngRequired,
  60259. 'required': attr.required
  60260. }, function(value, name) {
  60261. if (isDefined(value)) {
  60262. input.attr(name, value);
  60263. }
  60264. });
  60265. if (attr.toggleClass) {
  60266. element[0].getElementsByTagName('label')[0].classList.add(attr.toggleClass);
  60267. }
  60268. element.addClass('toggle-' + $ionicConfig.form.toggle());
  60269. return function($scope, $element) {
  60270. var el = $element[0].getElementsByTagName('label')[0];
  60271. var checkbox = el.children[0];
  60272. var track = el.children[1];
  60273. var handle = track.children[0];
  60274. var ngModelController = jqLite(checkbox).controller('ngModel');
  60275. $scope.toggle = new ionic.views.Toggle({
  60276. el: el,
  60277. track: track,
  60278. checkbox: checkbox,
  60279. handle: handle,
  60280. onChange: function() {
  60281. if (ngModelController) {
  60282. ngModelController.$setViewValue(checkbox.checked);
  60283. $scope.$apply();
  60284. }
  60285. }
  60286. });
  60287. $scope.$on('$destroy', function() {
  60288. $scope.toggle.destroy();
  60289. });
  60290. };
  60291. }
  60292. };
  60293. }]);
  60294. /**
  60295. * @ngdoc directive
  60296. * @name ionView
  60297. * @module ionic
  60298. * @restrict E
  60299. * @parent ionNavView
  60300. *
  60301. * @description
  60302. * A container for view content and any navigational and header bar information. When a view
  60303. * enters and exits its parent {@link ionic.directive:ionNavView}, the view also emits view
  60304. * information, such as its title, whether the back button should be displayed or not, whether the
  60305. * corresponding {@link ionic.directive:ionNavBar} should be displayed or not, which transition the view
  60306. * should use to animate, and which direction to animate.
  60307. *
  60308. * *Views are cached to improve performance.* When a view is navigated away from, its element is
  60309. * left in the DOM, and its scope is disconnected from the `$watch` cycle. When navigating to a
  60310. * view that is already cached, its scope is reconnected, and the existing element, which was
  60311. * left in the DOM, becomes active again. This can be disabled, or the maximum number of cached
  60312. * views changed in {@link ionic.provider:$ionicConfigProvider}, in the view's `$state` configuration, or
  60313. * as an attribute on the view itself (see below).
  60314. *
  60315. * @usage
  60316. * Below is an example where our page will load with a {@link ionic.directive:ionNavBar} containing
  60317. * "My Page" as the title.
  60318. *
  60319. * ```html
  60320. * <ion-nav-bar></ion-nav-bar>
  60321. * <ion-nav-view>
  60322. * <ion-view view-title="My Page">
  60323. * <ion-content>
  60324. * Hello!
  60325. * </ion-content>
  60326. * </ion-view>
  60327. * </ion-nav-view>
  60328. * ```
  60329. *
  60330. * ## View LifeCycle and Events
  60331. *
  60332. * Views can be cached, which means ***controllers normally only load once***, which may
  60333. * affect your controller logic. To know when a view has entered or left, events
  60334. * have been added that are emitted from the view's scope. These events also
  60335. * contain data about the view, such as the title and whether the back button should
  60336. * show. Also contained is transition data, such as the transition type and
  60337. * direction that will be or was used.
  60338. *
  60339. * Life cycle events are emitted upwards from the transitioning view's scope. In some cases, it is
  60340. * desirable for a child/nested view to be notified of the event.
  60341. * For this use case, `$ionicParentView` life cycle events are broadcast downwards.
  60342. *
  60343. * <table class="table">
  60344. * <tr>
  60345. * <td><code>$ionicView.loaded</code></td>
  60346. * <td>The view has loaded. This event only happens once per
  60347. * view being created and added to the DOM. If a view leaves but is cached,
  60348. * then this event will not fire again on a subsequent viewing. The loaded event
  60349. * is good place to put your setup code for the view; however, it is not the
  60350. * recommended event to listen to when a view becomes active.</td>
  60351. * </tr>
  60352. * <tr>
  60353. * <td><code>$ionicView.enter</code></td>
  60354. * <td>The view has fully entered and is now the active view.
  60355. * This event will fire, whether it was the first load or a cached view.</td>
  60356. * </tr>
  60357. * <tr>
  60358. * <td><code>$ionicView.leave</code></td>
  60359. * <td>The view has finished leaving and is no longer the
  60360. * active view. This event will fire, whether it is cached or destroyed.</td>
  60361. * </tr>
  60362. * <tr>
  60363. * <td><code>$ionicView.beforeEnter</code></td>
  60364. * <td>The view is about to enter and become the active view.</td>
  60365. * </tr>
  60366. * <tr>
  60367. * <td><code>$ionicView.beforeLeave</code></td>
  60368. * <td>The view is about to leave and no longer be the active view.</td>
  60369. * </tr>
  60370. * <tr>
  60371. * <td><code>$ionicView.afterEnter</code></td>
  60372. * <td>The view has fully entered and is now the active view.</td>
  60373. * </tr>
  60374. * <tr>
  60375. * <td><code>$ionicView.afterLeave</code></td>
  60376. * <td>The view has finished leaving and is no longer the active view.</td>
  60377. * </tr>
  60378. * <tr>
  60379. * <td><code>$ionicView.unloaded</code></td>
  60380. * <td>The view's controller has been destroyed and its element has been
  60381. * removed from the DOM.</td>
  60382. * </tr>
  60383. * <tr>
  60384. * <td><code>$ionicParentView.enter</code></td>
  60385. * <td>The parent view has fully entered and is now the active view.
  60386. * This event will fire, whether it was the first load or a cached view.</td>
  60387. * </tr>
  60388. * <tr>
  60389. * <td><code>$ionicParentView.leave</code></td>
  60390. * <td>The parent view has finished leaving and is no longer the
  60391. * active view. This event will fire, whether it is cached or destroyed.</td>
  60392. * </tr>
  60393. * <tr>
  60394. * <td><code>$ionicParentView.beforeEnter</code></td>
  60395. * <td>The parent view is about to enter and become the active view.</td>
  60396. * </tr>
  60397. * <tr>
  60398. * <td><code>$ionicParentView.beforeLeave</code></td>
  60399. * <td>The parent view is about to leave and no longer be the active view.</td>
  60400. * </tr>
  60401. * <tr>
  60402. * <td><code>$ionicParentView.afterEnter</code></td>
  60403. * <td>The parent view has fully entered and is now the active view.</td>
  60404. * </tr>
  60405. * <tr>
  60406. * <td><code>$ionicParentView.afterLeave</code></td>
  60407. * <td>The parent view has finished leaving and is no longer the active view.</td>
  60408. * </tr>
  60409. * </table>
  60410. *
  60411. * ## LifeCycle Event Usage
  60412. *
  60413. * Below is an example of how to listen to life cycle events and
  60414. * access state parameter data
  60415. *
  60416. * ```js
  60417. * $scope.$on("$ionicView.beforeEnter", function(event, data){
  60418. * // handle event
  60419. * console.log("State Params: ", data.stateParams);
  60420. * });
  60421. *
  60422. * $scope.$on("$ionicView.enter", function(event, data){
  60423. * // handle event
  60424. * console.log("State Params: ", data.stateParams);
  60425. * });
  60426. *
  60427. * $scope.$on("$ionicView.afterEnter", function(event, data){
  60428. * // handle event
  60429. * console.log("State Params: ", data.stateParams);
  60430. * });
  60431. * ```
  60432. *
  60433. * ## Caching
  60434. *
  60435. * Caching can be disabled and enabled in multiple ways. By default, Ionic will
  60436. * cache a maximum of 10 views. You can optionally choose to disable caching at
  60437. * either an individual view basis, or by global configuration. Please see the
  60438. * _Caching_ section in {@link ionic.directive:ionNavView} for more info.
  60439. *
  60440. * @param {string=} view-title A text-only title to display on the parent {@link ionic.directive:ionNavBar}.
  60441. * For an HTML title, such as an image, see {@link ionic.directive:ionNavTitle} instead.
  60442. * @param {boolean=} cache-view If this view should be allowed to be cached or not.
  60443. * Please see the _Caching_ section in {@link ionic.directive:ionNavView} for
  60444. * more info. Default `true`
  60445. * @param {boolean=} can-swipe-back If this view should be allowed to use the swipe to go back gesture or not.
  60446. * This does not enable the swipe to go back feature if it is not available for the platform it's running
  60447. * from, or there isn't a previous view. Default `true`
  60448. * @param {boolean=} hide-back-button Whether to hide the back button on the parent
  60449. * {@link ionic.directive:ionNavBar} by default.
  60450. * @param {boolean=} hide-nav-bar Whether to hide the parent
  60451. * {@link ionic.directive:ionNavBar} by default.
  60452. */
  60453. IonicModule
  60454. .directive('ionView', function() {
  60455. return {
  60456. restrict: 'EA',
  60457. priority: 1000,
  60458. controller: '$ionicView',
  60459. compile: function(tElement) {
  60460. tElement.addClass('pane');
  60461. tElement[0].removeAttribute('title');
  60462. return function link($scope, $element, $attrs, viewCtrl) {
  60463. viewCtrl.init();
  60464. };
  60465. }
  60466. };
  60467. });
  60468. })();