ionic.bundle.js 2.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582
  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.4
  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.4';
  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 `ionic plugin add cordova-plugin-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 `ionic plugin add cordova-plugin-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/ionic-team/ionic/blob/1.x/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) && !e.target.isContentEditable && !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(e.target.tagName == 'SELECT') {
  2703. return true;
  2704. }
  2705. if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) {
  2706. e.preventDefault();
  2707. return true;
  2708. }
  2709. }
  2710. function tapHandleFocus(ele) {
  2711. tapTouchFocusedInput = null;
  2712. var triggerFocusIn = false;
  2713. if (ele.tagName == 'SELECT') {
  2714. // trick to force Android options to show up
  2715. triggerMouseEvent('mousedown', ele, 0, 0);
  2716. ele.focus && ele.focus();
  2717. triggerFocusIn = true;
  2718. } else if (tapActiveElement() === ele) {
  2719. // already is the active element and has focus
  2720. triggerFocusIn = true;
  2721. } else if ((/^(input|textarea|ion-label)$/i).test(ele.tagName) || ele.isContentEditable) {
  2722. triggerFocusIn = true;
  2723. ele.focus && ele.focus();
  2724. ele.value = ele.value;
  2725. if (tapEnabledTouchEvents) {
  2726. tapTouchFocusedInput = ele;
  2727. }
  2728. } else {
  2729. tapFocusOutActive();
  2730. }
  2731. if (triggerFocusIn) {
  2732. tapActiveElement(ele);
  2733. ionic.trigger('ionic.focusin', {
  2734. target: ele
  2735. }, true);
  2736. }
  2737. }
  2738. function tapFocusOutActive() {
  2739. var ele = tapActiveElement();
  2740. if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) {
  2741. //console.log('tapFocusOutActive', ele.tagName);
  2742. ele.blur();
  2743. }
  2744. tapActiveElement(null);
  2745. }
  2746. function tapFocusIn(e) {
  2747. //console.log('focusin ' + Date.now());
  2748. // Because a text input doesn't preventDefault (so the caret still works) there's a chance
  2749. // that its mousedown event 300ms later will change the focus to another element after
  2750. // the keyboard shows up.
  2751. if (tapEnabledTouchEvents &&
  2752. ionic.tap.isTextInput(tapActiveElement()) &&
  2753. ionic.tap.isTextInput(tapTouchFocusedInput) &&
  2754. tapTouchFocusedInput !== e.target) {
  2755. // 1) The pointer is from touch events
  2756. // 2) There is an active element which is a text input
  2757. // 3) A text input was just set to be focused on by a touch event
  2758. // 4) A new focus has been set, however the target isn't the one the touch event wanted
  2759. //console.log('focusin', 'tapTouchFocusedInput');
  2760. tapTouchFocusedInput.focus();
  2761. tapTouchFocusedInput = null;
  2762. }
  2763. ionic.scroll.isScrolling = false;
  2764. }
  2765. function tapFocusOut() {
  2766. //console.log("focusout");
  2767. tapActiveElement(null);
  2768. }
  2769. function tapActiveElement(ele) {
  2770. if (arguments.length) {
  2771. tapActiveEle = ele;
  2772. }
  2773. return tapActiveEle || document.activeElement;
  2774. }
  2775. function tapHasPointerMoved(endEvent) {
  2776. if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) {
  2777. return false;
  2778. }
  2779. var endCoordinates = ionic.tap.pointerCoord(endEvent);
  2780. var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains &&
  2781. typeof endEvent.target.classList.contains === 'function');
  2782. var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ?
  2783. TAP_RELEASE_BUTTON_TOLERANCE :
  2784. TAP_RELEASE_TOLERANCE;
  2785. return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance ||
  2786. Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance;
  2787. }
  2788. function tapContainingElement(ele, allowSelf) {
  2789. var climbEle = ele;
  2790. for (var x = 0; x < 6; x++) {
  2791. if (!climbEle) break;
  2792. if (climbEle.tagName === 'LABEL') return climbEle;
  2793. climbEle = climbEle.parentElement;
  2794. }
  2795. if (allowSelf !== false) return ele;
  2796. }
  2797. function tapTargetElement(ele) {
  2798. if (ele && ele.tagName === 'LABEL') {
  2799. if (ele.control) return ele.control;
  2800. // older devices do not support the "control" property
  2801. if (ele.querySelector) {
  2802. var control = ele.querySelector('input,textarea,select');
  2803. if (control) return control;
  2804. }
  2805. }
  2806. return ele;
  2807. }
  2808. function isSelectOrOption(tagName){
  2809. return (/^(select|option)$/i).test(tagName);
  2810. }
  2811. ionic.DomUtil.ready(function() {
  2812. var ng = typeof angular !== 'undefined' ? angular : null;
  2813. //do nothing for e2e tests
  2814. if (!ng || (ng && !ng.scenario)) {
  2815. ionic.tap.register(document);
  2816. }
  2817. });
  2818. (function(document, ionic) {
  2819. 'use strict';
  2820. var queueElements = {}; // elements that should get an active state in XX milliseconds
  2821. var activeElements = {}; // elements that are currently active
  2822. var keyId = 0; // a counter for unique keys for the above ojects
  2823. var ACTIVATED_CLASS = 'activated';
  2824. ionic.activator = {
  2825. start: function(e) {
  2826. var hitX = ionic.tap.pointerCoord(e).x;
  2827. if (hitX > 0 && hitX < 30) {
  2828. return;
  2829. }
  2830. // when an element is touched/clicked, it climbs up a few
  2831. // parents to see if it is an .item or .button element
  2832. ionic.requestAnimationFrame(function() {
  2833. if ((ionic.scroll && ionic.scroll.isScrolling) || ionic.tap.requiresNativeClick(e.target)) return;
  2834. var ele = e.target;
  2835. var eleToActivate;
  2836. for (var x = 0; x < 6; x++) {
  2837. if (!ele || ele.nodeType !== 1) break;
  2838. if (eleToActivate && ele.classList && ele.classList.contains('item')) {
  2839. eleToActivate = ele;
  2840. break;
  2841. }
  2842. if (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click')) {
  2843. eleToActivate = ele;
  2844. break;
  2845. }
  2846. if (ele.classList && ele.classList.contains('button')) {
  2847. eleToActivate = ele;
  2848. break;
  2849. }
  2850. // no sense climbing past these
  2851. if (ele.tagName == 'ION-CONTENT' || (ele.classList && ele.classList.contains('pane')) || ele.tagName == 'BODY') {
  2852. break;
  2853. }
  2854. ele = ele.parentElement;
  2855. }
  2856. if (eleToActivate) {
  2857. // queue that this element should be set to active
  2858. queueElements[keyId] = eleToActivate;
  2859. // on the next frame, set the queued elements to active
  2860. ionic.requestAnimationFrame(activateElements);
  2861. keyId = (keyId > 29 ? 0 : keyId + 1);
  2862. }
  2863. });
  2864. },
  2865. end: function() {
  2866. // clear out any active/queued elements after XX milliseconds
  2867. setTimeout(clear, 200);
  2868. }
  2869. };
  2870. function clear() {
  2871. // clear out any elements that are queued to be set to active
  2872. queueElements = {};
  2873. // in the next frame, remove the active class from all active elements
  2874. ionic.requestAnimationFrame(deactivateElements);
  2875. }
  2876. function activateElements() {
  2877. // activate all elements in the queue
  2878. for (var key in queueElements) {
  2879. if (queueElements[key]) {
  2880. queueElements[key].classList.add(ACTIVATED_CLASS);
  2881. activeElements[key] = queueElements[key];
  2882. }
  2883. }
  2884. queueElements = {};
  2885. }
  2886. function deactivateElements() {
  2887. if (ionic.transition && ionic.transition.isActive) {
  2888. setTimeout(deactivateElements, 400);
  2889. return;
  2890. }
  2891. for (var key in activeElements) {
  2892. if (activeElements[key]) {
  2893. activeElements[key].classList.remove(ACTIVATED_CLASS);
  2894. delete activeElements[key];
  2895. }
  2896. }
  2897. }
  2898. })(document, ionic);
  2899. (function(ionic) {
  2900. /* for nextUid function below */
  2901. var nextId = 0;
  2902. /**
  2903. * Various utilities used throughout Ionic
  2904. *
  2905. * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed.
  2906. */
  2907. ionic.Utils = {
  2908. arrayMove: function(arr, oldIndex, newIndex) {
  2909. if (newIndex >= arr.length) {
  2910. var k = newIndex - arr.length;
  2911. while ((k--) + 1) {
  2912. arr.push(undefined);
  2913. }
  2914. }
  2915. arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
  2916. return arr;
  2917. },
  2918. /**
  2919. * Return a function that will be called with the given context
  2920. */
  2921. proxy: function(func, context) {
  2922. var args = Array.prototype.slice.call(arguments, 2);
  2923. return function() {
  2924. return func.apply(context, args.concat(Array.prototype.slice.call(arguments)));
  2925. };
  2926. },
  2927. /**
  2928. * Only call a function once in the given interval.
  2929. *
  2930. * @param func {Function} the function to call
  2931. * @param wait {int} how long to wait before/after to allow function calls
  2932. * @param immediate {boolean} whether to call immediately or after the wait interval
  2933. */
  2934. debounce: function(func, wait, immediate) {
  2935. var timeout, args, context, timestamp, result;
  2936. return function() {
  2937. context = this;
  2938. args = arguments;
  2939. timestamp = new Date();
  2940. var later = function() {
  2941. var last = (new Date()) - timestamp;
  2942. if (last < wait) {
  2943. timeout = setTimeout(later, wait - last);
  2944. } else {
  2945. timeout = null;
  2946. if (!immediate) result = func.apply(context, args);
  2947. }
  2948. };
  2949. var callNow = immediate && !timeout;
  2950. if (!timeout) {
  2951. timeout = setTimeout(later, wait);
  2952. }
  2953. if (callNow) result = func.apply(context, args);
  2954. return result;
  2955. };
  2956. },
  2957. /**
  2958. * Throttle the given fun, only allowing it to be
  2959. * called at most every `wait` ms.
  2960. */
  2961. throttle: function(func, wait, options) {
  2962. var context, args, result;
  2963. var timeout = null;
  2964. var previous = 0;
  2965. options || (options = {});
  2966. var later = function() {
  2967. previous = options.leading === false ? 0 : Date.now();
  2968. timeout = null;
  2969. result = func.apply(context, args);
  2970. };
  2971. return function() {
  2972. var now = Date.now();
  2973. if (!previous && options.leading === false) previous = now;
  2974. var remaining = wait - (now - previous);
  2975. context = this;
  2976. args = arguments;
  2977. if (remaining <= 0) {
  2978. clearTimeout(timeout);
  2979. timeout = null;
  2980. previous = now;
  2981. result = func.apply(context, args);
  2982. } else if (!timeout && options.trailing !== false) {
  2983. timeout = setTimeout(later, remaining);
  2984. }
  2985. return result;
  2986. };
  2987. },
  2988. // Borrowed from Backbone.js's extend
  2989. // Helper function to correctly set up the prototype chain, for subclasses.
  2990. // Similar to `goog.inherits`, but uses a hash of prototype properties and
  2991. // class properties to be extended.
  2992. inherit: function(protoProps, staticProps) {
  2993. var parent = this;
  2994. var child;
  2995. // The constructor function for the new subclass is either defined by you
  2996. // (the "constructor" property in your `extend` definition), or defaulted
  2997. // by us to simply call the parent's constructor.
  2998. if (protoProps && protoProps.hasOwnProperty('constructor')) {
  2999. child = protoProps.constructor;
  3000. } else {
  3001. child = function() { return parent.apply(this, arguments); };
  3002. }
  3003. // Add static properties to the constructor function, if supplied.
  3004. ionic.extend(child, parent, staticProps);
  3005. // Set the prototype chain to inherit from `parent`, without calling
  3006. // `parent`'s constructor function.
  3007. var Surrogate = function() { this.constructor = child; };
  3008. Surrogate.prototype = parent.prototype;
  3009. child.prototype = new Surrogate();
  3010. // Add prototype properties (instance properties) to the subclass,
  3011. // if supplied.
  3012. if (protoProps) ionic.extend(child.prototype, protoProps);
  3013. // Set a convenience property in case the parent's prototype is needed
  3014. // later.
  3015. child.__super__ = parent.prototype;
  3016. return child;
  3017. },
  3018. // Extend adapted from Underscore.js
  3019. extend: function(obj) {
  3020. var args = Array.prototype.slice.call(arguments, 1);
  3021. for (var i = 0; i < args.length; i++) {
  3022. var source = args[i];
  3023. if (source) {
  3024. for (var prop in source) {
  3025. obj[prop] = source[prop];
  3026. }
  3027. }
  3028. }
  3029. return obj;
  3030. },
  3031. nextUid: function() {
  3032. return 'ion' + (nextId++);
  3033. },
  3034. disconnectScope: function disconnectScope(scope) {
  3035. if (!scope) return;
  3036. if (scope.$root === scope) {
  3037. return; // we can't disconnect the root node;
  3038. }
  3039. var parent = scope.$parent;
  3040. scope.$$disconnected = true;
  3041. scope.$broadcast('$ionic.disconnectScope', scope);
  3042. // See Scope.$destroy
  3043. if (parent.$$childHead === scope) {
  3044. parent.$$childHead = scope.$$nextSibling;
  3045. }
  3046. if (parent.$$childTail === scope) {
  3047. parent.$$childTail = scope.$$prevSibling;
  3048. }
  3049. if (scope.$$prevSibling) {
  3050. scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;
  3051. }
  3052. if (scope.$$nextSibling) {
  3053. scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;
  3054. }
  3055. scope.$$nextSibling = scope.$$prevSibling = null;
  3056. },
  3057. reconnectScope: function reconnectScope(scope) {
  3058. if (!scope) return;
  3059. if (scope.$root === scope) {
  3060. return; // we can't disconnect the root node;
  3061. }
  3062. if (!scope.$$disconnected) {
  3063. return;
  3064. }
  3065. var parent = scope.$parent;
  3066. scope.$$disconnected = false;
  3067. scope.$broadcast('$ionic.reconnectScope', scope);
  3068. // See Scope.$new for this logic...
  3069. scope.$$prevSibling = parent.$$childTail;
  3070. if (parent.$$childHead) {
  3071. parent.$$childTail.$$nextSibling = scope;
  3072. parent.$$childTail = scope;
  3073. } else {
  3074. parent.$$childHead = parent.$$childTail = scope;
  3075. }
  3076. },
  3077. isScopeDisconnected: function(scope) {
  3078. var climbScope = scope;
  3079. while (climbScope) {
  3080. if (climbScope.$$disconnected) return true;
  3081. climbScope = climbScope.$parent;
  3082. }
  3083. return false;
  3084. }
  3085. };
  3086. // Bind a few of the most useful functions to the ionic scope
  3087. ionic.inherit = ionic.Utils.inherit;
  3088. ionic.extend = ionic.Utils.extend;
  3089. ionic.throttle = ionic.Utils.throttle;
  3090. ionic.proxy = ionic.Utils.proxy;
  3091. ionic.debounce = ionic.Utils.debounce;
  3092. })(window.ionic);
  3093. /**
  3094. * @ngdoc page
  3095. * @name keyboard
  3096. * @module ionic
  3097. * @description
  3098. * On both Android and iOS, Ionic will attempt to prevent the keyboard from
  3099. * obscuring inputs and focusable elements when it appears by scrolling them
  3100. * into view. In order for this to work, any focusable elements must be within
  3101. * a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/)
  3102. * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/)
  3103. * that has a Scroll View.
  3104. *
  3105. * It will also attempt to prevent the native overflow scrolling on focus,
  3106. * which can cause layout issues such as pushing headers up and out of view.
  3107. *
  3108. * The keyboard fixes work best in conjunction with the
  3109. * [Ionic Keyboard Plugin](https://github.com/ionic-team/ionic-plugins-keyboard),
  3110. * although it will perform reasonably well without. However, if you are using
  3111. * Cordova there is no reason not to use the plugin.
  3112. *
  3113. * ### Hide when keyboard shows
  3114. *
  3115. * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`.
  3116. *
  3117. * ```html
  3118. * <div class="hide-on-keyboard-open">
  3119. * <div id="google-map"></div>
  3120. * </div>
  3121. * ```
  3122. *
  3123. * Note: For performance reasons, elements will not be hidden for 400ms after the start of the `native.keyboardshow` event
  3124. * from the Ionic Keyboard plugin. If you would like them to disappear immediately, you could do something
  3125. * like:
  3126. *
  3127. * ```js
  3128. * window.addEventListener('native.keyboardshow', function(){
  3129. * document.body.classList.add('keyboard-open');
  3130. * });
  3131. * ```
  3132. * This adds the same `keyboard-open` class that is normally added by Ionic 400ms after the keyboard
  3133. * opens. However, bear in mind that adding this class to the body immediately may cause jank in any
  3134. * animations on Android that occur when the keyboard opens (for example, scrolling any obscured inputs into view).
  3135. *
  3136. * ----------
  3137. *
  3138. * ### Plugin Usage
  3139. * Information on using the plugin can be found at
  3140. * [https://github.com/ionic-team/ionic-plugins-keyboard](https://github.com/ionic-team/ionic-plugins-keyboard).
  3141. *
  3142. * ----------
  3143. *
  3144. * ### Android Notes
  3145. * - If your app is running in fullscreen, i.e. you have
  3146. * `<preference name="Fullscreen" value="true" />` in your `config.xml` file
  3147. * you will need to set `ionic.Platform.isFullScreen = true` manually.
  3148. *
  3149. * - You can configure the behavior of the web view when the keyboard shows by setting
  3150. * [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode)
  3151. * to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's
  3152. * activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting
  3153. * for Ionic, but if for some reason you do use `adjustPan` you will need to
  3154. * set `ionic.Platform.isFullScreen = true`.
  3155. *
  3156. * ```xml
  3157. * <activity android:windowSoftInputMode="adjustResize">
  3158. *
  3159. * ```
  3160. *
  3161. * ### iOS Notes
  3162. * - If the content of your app (including the header) is being pushed up and
  3163. * out of view on input focus, try setting `cordova.plugins.Keyboard.disableScroll(true)`.
  3164. * This does **not** disable scrolling in the Ionic scroll view, rather it
  3165. * disables the native overflow scrolling that happens automatically as a
  3166. * result of focusing on inputs below the keyboard.
  3167. *
  3168. */
  3169. /**
  3170. * The current viewport height.
  3171. */
  3172. var keyboardCurrentViewportHeight = 0;
  3173. /**
  3174. * The viewport height when in portrait orientation.
  3175. */
  3176. var keyboardPortraitViewportHeight = 0;
  3177. /**
  3178. * The viewport height when in landscape orientation.
  3179. */
  3180. var keyboardLandscapeViewportHeight = 0;
  3181. /**
  3182. * The currently focused input.
  3183. */
  3184. var keyboardActiveElement;
  3185. /**
  3186. * The previously focused input used to reset keyboard after focusing on a
  3187. * new non-keyboard element
  3188. */
  3189. var lastKeyboardActiveElement;
  3190. /**
  3191. * The scroll view containing the currently focused input.
  3192. */
  3193. var scrollView;
  3194. /**
  3195. * Timer for the setInterval that polls window.innerHeight to determine whether
  3196. * the layout has updated for the keyboard showing/hiding.
  3197. */
  3198. var waitForResizeTimer;
  3199. /**
  3200. * Sometimes when switching inputs or orientations, focusout will fire before
  3201. * focusin, so this timer is for the small setTimeout to determine if we should
  3202. * really focusout/hide the keyboard.
  3203. */
  3204. var keyboardFocusOutTimer;
  3205. /**
  3206. * on Android, orientationchange will fire before the keyboard plugin notifies
  3207. * the browser that the keyboard will show/is showing, so this flag indicates
  3208. * to nativeShow that there was an orientationChange and we should update
  3209. * the viewport height with an accurate keyboard height value
  3210. */
  3211. var wasOrientationChange = false;
  3212. /**
  3213. * CSS class added to the body indicating the keyboard is open.
  3214. */
  3215. var KEYBOARD_OPEN_CSS = 'keyboard-open';
  3216. /**
  3217. * CSS class that indicates a scroll container.
  3218. */
  3219. var SCROLL_CONTAINER_CSS = 'scroll-content';
  3220. /**
  3221. * Debounced keyboardFocusIn function
  3222. */
  3223. var debouncedKeyboardFocusIn = ionic.debounce(keyboardFocusIn, 200, true);
  3224. /**
  3225. * Debounced keyboardNativeShow function
  3226. */
  3227. var debouncedKeyboardNativeShow = ionic.debounce(keyboardNativeShow, 100, true);
  3228. /**
  3229. * Ionic keyboard namespace.
  3230. * @namespace keyboard
  3231. */
  3232. ionic.keyboard = {
  3233. /**
  3234. * Whether the keyboard is open or not.
  3235. */
  3236. isOpen: false,
  3237. /**
  3238. * Whether the keyboard is closing or not.
  3239. */
  3240. isClosing: false,
  3241. /**
  3242. * Whether the keyboard is opening or not.
  3243. */
  3244. isOpening: false,
  3245. /**
  3246. * The height of the keyboard in pixels, as reported by the keyboard plugin.
  3247. * If the plugin is not available, calculated as the difference in
  3248. * window.innerHeight after the keyboard has shown.
  3249. */
  3250. height: 0,
  3251. /**
  3252. * Whether the device is in landscape orientation or not.
  3253. */
  3254. isLandscape: false,
  3255. /**
  3256. * Whether the keyboard event listeners have been added or not
  3257. */
  3258. isInitialized: false,
  3259. /**
  3260. * Hide the keyboard, if it is open.
  3261. */
  3262. hide: function() {
  3263. if (keyboardHasPlugin()) {
  3264. cordova.plugins.Keyboard.close();
  3265. }
  3266. keyboardActiveElement && keyboardActiveElement.blur();
  3267. },
  3268. /**
  3269. * An alias for cordova.plugins.Keyboard.show(). If the keyboard plugin
  3270. * is installed, show the keyboard.
  3271. */
  3272. show: function() {
  3273. if (keyboardHasPlugin()) {
  3274. cordova.plugins.Keyboard.show();
  3275. }
  3276. },
  3277. /**
  3278. * Remove all keyboard related event listeners, effectively disabling Ionic's
  3279. * keyboard adjustments.
  3280. */
  3281. disable: function() {
  3282. if (keyboardHasPlugin()) {
  3283. window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );
  3284. window.removeEventListener('native.keyboardhide', keyboardFocusOut);
  3285. } else {
  3286. document.body.removeEventListener('focusout', keyboardFocusOut);
  3287. }
  3288. document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);
  3289. document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);
  3290. window.removeEventListener('orientationchange', keyboardOrientationChange);
  3291. if ( window.navigator.msPointerEnabled ) {
  3292. document.removeEventListener("MSPointerDown", keyboardInit);
  3293. } else {
  3294. document.removeEventListener('touchstart', keyboardInit);
  3295. }
  3296. ionic.keyboard.isInitialized = false;
  3297. },
  3298. /**
  3299. * Alias for keyboardInit, initialize all keyboard related event listeners.
  3300. */
  3301. enable: function() {
  3302. keyboardInit();
  3303. }
  3304. };
  3305. // Initialize the viewport height (after ionic.keyboard.height has been
  3306. // defined).
  3307. keyboardCurrentViewportHeight = getViewportHeight();
  3308. /* Event handlers */
  3309. /* ------------------------------------------------------------------------- */
  3310. /**
  3311. * Event handler for first touch event, initializes all event listeners
  3312. * for keyboard related events. Also aliased by ionic.keyboard.enable.
  3313. */
  3314. function keyboardInit() {
  3315. if (ionic.keyboard.isInitialized) return;
  3316. if (keyboardHasPlugin()) {
  3317. window.addEventListener('native.keyboardshow', debouncedKeyboardNativeShow);
  3318. window.addEventListener('native.keyboardhide', keyboardFocusOut);
  3319. } else {
  3320. document.body.addEventListener('focusout', keyboardFocusOut);
  3321. }
  3322. document.body.addEventListener('ionic.focusin', debouncedKeyboardFocusIn);
  3323. document.body.addEventListener('focusin', debouncedKeyboardFocusIn);
  3324. if (window.navigator.msPointerEnabled) {
  3325. document.removeEventListener("MSPointerDown", keyboardInit);
  3326. } else {
  3327. document.removeEventListener('touchstart', keyboardInit);
  3328. }
  3329. ionic.keyboard.isInitialized = true;
  3330. }
  3331. /**
  3332. * Event handler for 'native.keyboardshow' event, sets keyboard.height to the
  3333. * reported height and keyboard.isOpening to true. Then calls
  3334. * keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as
  3335. * the callback depending on whether the event was triggered by a focusin or
  3336. * an orientationchange.
  3337. */
  3338. function keyboardNativeShow(e) {
  3339. clearTimeout(keyboardFocusOutTimer);
  3340. //console.log("keyboardNativeShow fired at: " + Date.now());
  3341. //console.log("keyboardNativeshow window.innerHeight: " + window.innerHeight);
  3342. if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
  3343. ionic.keyboard.isOpening = true;
  3344. ionic.keyboard.isClosing = false;
  3345. }
  3346. ionic.keyboard.height = e.keyboardHeight;
  3347. //console.log('nativeshow keyboard height:' + e.keyboardHeight);
  3348. if (wasOrientationChange) {
  3349. keyboardWaitForResize(keyboardUpdateViewportHeight, true);
  3350. } else {
  3351. keyboardWaitForResize(keyboardShow, true);
  3352. }
  3353. }
  3354. /**
  3355. * Event handler for 'focusin' and 'ionic.focusin' events. Initializes
  3356. * keyboard state (keyboardActiveElement and keyboard.isOpening) for the
  3357. * appropriate adjustments once the window has resized. If not using the
  3358. * keyboard plugin, calls keyboardWaitForResize with keyboardShow as the
  3359. * callback or keyboardShow right away if the keyboard is already open. If
  3360. * using the keyboard plugin does nothing and lets keyboardNativeShow handle
  3361. * adjustments with a more accurate keyboard height.
  3362. */
  3363. function keyboardFocusIn(e) {
  3364. clearTimeout(keyboardFocusOutTimer);
  3365. //console.log("keyboardFocusIn from: " + e.type + " at: " + Date.now());
  3366. if (!e.target ||
  3367. e.target.readOnly ||
  3368. !ionic.tap.isKeyboardElement(e.target) ||
  3369. !(scrollView = ionic.DomUtil.getParentWithClass(e.target, SCROLL_CONTAINER_CSS))) {
  3370. if (keyboardActiveElement) {
  3371. lastKeyboardActiveElement = keyboardActiveElement;
  3372. }
  3373. keyboardActiveElement = null;
  3374. return;
  3375. }
  3376. keyboardActiveElement = e.target;
  3377. // if using JS scrolling, undo the effects of native overflow scroll so the
  3378. // scroll view is positioned correctly
  3379. if (!scrollView.classList.contains("overflow-scroll")) {
  3380. document.body.scrollTop = 0;
  3381. scrollView.scrollTop = 0;
  3382. ionic.requestAnimationFrame(function(){
  3383. document.body.scrollTop = 0;
  3384. scrollView.scrollTop = 0;
  3385. });
  3386. // any showing part of the document that isn't within the scroll the user
  3387. // could touchmove and cause some ugly changes to the app, so disable
  3388. // any touchmove events while the keyboard is open using e.preventDefault()
  3389. if (window.navigator.msPointerEnabled) {
  3390. document.addEventListener("MSPointerMove", keyboardPreventDefault, false);
  3391. } else {
  3392. document.addEventListener('touchmove', keyboardPreventDefault, false);
  3393. }
  3394. }
  3395. if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {
  3396. ionic.keyboard.isOpening = true;
  3397. ionic.keyboard.isClosing = false;
  3398. }
  3399. // attempt to prevent browser from natively scrolling input into view while
  3400. // we are trying to do the same (while we are scrolling) if the user taps the
  3401. // keyboard
  3402. document.addEventListener('keydown', keyboardOnKeyDown, false);
  3403. // if we aren't using the plugin and the keyboard isn't open yet, wait for the
  3404. // window to resize so we can get an accurate estimate of the keyboard size,
  3405. // otherwise we do nothing and let nativeShow call keyboardShow once we have
  3406. // an exact keyboard height
  3407. // if the keyboard is already open, go ahead and scroll the input into view
  3408. // if necessary
  3409. if (!ionic.keyboard.isOpen && !keyboardHasPlugin()) {
  3410. keyboardWaitForResize(keyboardShow, true);
  3411. } else if (ionic.keyboard.isOpen) {
  3412. keyboardShow();
  3413. }
  3414. }
  3415. /**
  3416. * Event handler for 'focusout' events. Sets keyboard.isClosing to true and
  3417. * calls keyboardWaitForResize with keyboardHide as the callback after a small
  3418. * timeout.
  3419. */
  3420. function keyboardFocusOut() {
  3421. clearTimeout(keyboardFocusOutTimer);
  3422. //console.log("keyboardFocusOut fired at: " + Date.now());
  3423. //console.log("keyboardFocusOut event type: " + e.type);
  3424. if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {
  3425. ionic.keyboard.isClosing = true;
  3426. ionic.keyboard.isOpening = false;
  3427. }
  3428. // Call keyboardHide with a slight delay because sometimes on focus or
  3429. // orientation change focusin is called immediately after, so we give it time
  3430. // to cancel keyboardHide
  3431. keyboardFocusOutTimer = setTimeout(function() {
  3432. ionic.requestAnimationFrame(function() {
  3433. // focusOut during or right after an orientationchange, so we didn't get
  3434. // a chance to update the viewport height yet, do it and keyboardHide
  3435. //console.log("focusOut, wasOrientationChange: " + wasOrientationChange);
  3436. if (wasOrientationChange) {
  3437. keyboardWaitForResize(function(){
  3438. keyboardUpdateViewportHeight();
  3439. keyboardHide();
  3440. }, false);
  3441. } else {
  3442. keyboardWaitForResize(keyboardHide, false);
  3443. }
  3444. });
  3445. }, 50);
  3446. }
  3447. /**
  3448. * Event handler for 'orientationchange' events. If using the keyboard plugin
  3449. * and the keyboard is open on Android, sets wasOrientationChange to true so
  3450. * nativeShow can update the viewport height with an accurate keyboard height.
  3451. * If the keyboard isn't open or keyboard plugin isn't being used,
  3452. * waits for the window to resize before updating the viewport height.
  3453. *
  3454. * On iOS, where orientationchange fires after the keyboard has already shown,
  3455. * updates the viewport immediately, regardless of if the keyboard is already
  3456. * open.
  3457. */
  3458. function keyboardOrientationChange() {
  3459. //console.log("orientationchange fired at: " + Date.now());
  3460. //console.log("orientation was: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
  3461. // toggle orientation
  3462. ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;
  3463. // //console.log("now orientation is: " + (ionic.keyboard.isLandscape ? "landscape" : "portrait"));
  3464. // no need to wait for resizing on iOS, and orientationchange always fires
  3465. // after the keyboard has opened, so it doesn't matter if it's open or not
  3466. if (ionic.Platform.isIOS()) {
  3467. keyboardUpdateViewportHeight();
  3468. }
  3469. // On Android, if the keyboard isn't open or we aren't using the keyboard
  3470. // plugin, update the viewport height once everything has resized. If the
  3471. // keyboard is open and we are using the keyboard plugin do nothing and let
  3472. // nativeShow handle it using an accurate keyboard height.
  3473. if ( ionic.Platform.isAndroid()) {
  3474. if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {
  3475. keyboardWaitForResize(keyboardUpdateViewportHeight, false);
  3476. } else {
  3477. wasOrientationChange = true;
  3478. }
  3479. }
  3480. }
  3481. /**
  3482. * Event handler for 'keydown' event. Tries to prevent browser from natively
  3483. * scrolling an input into view when a user taps the keyboard while we are
  3484. * scrolling the input into view ourselves with JS.
  3485. */
  3486. function keyboardOnKeyDown(e) {
  3487. if (ionic.scroll.isScrolling) {
  3488. keyboardPreventDefault(e);
  3489. }
  3490. }
  3491. /**
  3492. * Event for 'touchmove' or 'MSPointerMove'. Prevents native scrolling on
  3493. * elements outside the scroll view while the keyboard is open.
  3494. */
  3495. function keyboardPreventDefault(e) {
  3496. if (e.target.tagName !== 'TEXTAREA') {
  3497. e.preventDefault();
  3498. }
  3499. }
  3500. /* Private API */
  3501. /* -------------------------------------------------------------------------- */
  3502. /**
  3503. * Polls window.innerHeight until it has updated to an expected value (or
  3504. * sufficient time has passed) before calling the specified callback function.
  3505. * Only necessary for non-fullscreen Android which sometimes reports multiple
  3506. * window.innerHeight values during interim layouts while it is resizing.
  3507. *
  3508. * On iOS, the window.innerHeight will already be updated, but we use the 50ms
  3509. * delay as essentially a timeout so that scroll view adjustments happen after
  3510. * the keyboard has shown so there isn't a white flash from us resizing too
  3511. * quickly.
  3512. *
  3513. * @param {Function} callback the function to call once the window has resized
  3514. * @param {boolean} isOpening whether the resize is from the keyboard opening
  3515. * or not
  3516. */
  3517. function keyboardWaitForResize(callback, isOpening) {
  3518. clearInterval(waitForResizeTimer);
  3519. var count = 0;
  3520. var maxCount;
  3521. var initialHeight = getViewportHeight();
  3522. var viewportHeight = initialHeight;
  3523. //console.log("waitForResize initial viewport height: " + viewportHeight);
  3524. //var start = Date.now();
  3525. //console.log("start: " + start);
  3526. // want to fail relatively quickly on modern android devices, since it's much
  3527. // more likely we just have a bad keyboard height
  3528. if (ionic.Platform.isAndroid() && ionic.Platform.version() < 4.4) {
  3529. maxCount = 30;
  3530. } else if (ionic.Platform.isAndroid()) {
  3531. maxCount = 10;
  3532. } else {
  3533. maxCount = 1;
  3534. }
  3535. // poll timer
  3536. waitForResizeTimer = setInterval(function(){
  3537. viewportHeight = getViewportHeight();
  3538. // height hasn't updated yet, try again in 50ms
  3539. // if not using plugin, wait for maxCount to ensure we have waited long enough
  3540. // to get an accurate keyboard height
  3541. if (++count < maxCount &&
  3542. ((!isPortraitViewportHeight(viewportHeight) &&
  3543. !isLandscapeViewportHeight(viewportHeight)) ||
  3544. !ionic.keyboard.height)) {
  3545. return;
  3546. }
  3547. // infer the keyboard height from the resize if not using the keyboard plugin
  3548. if (!keyboardHasPlugin()) {
  3549. ionic.keyboard.height = Math.abs(initialHeight - window.innerHeight);
  3550. }
  3551. // set to true if we were waiting for the keyboard to open
  3552. ionic.keyboard.isOpen = isOpening;
  3553. clearInterval(waitForResizeTimer);
  3554. //var end = Date.now();
  3555. //console.log("waitForResize count: " + count);
  3556. //console.log("end: " + end);
  3557. //console.log("difference: " + ( end - start ) + "ms");
  3558. //console.log("callback: " + callback.name);
  3559. callback();
  3560. }, 50);
  3561. return maxCount; //for tests
  3562. }
  3563. /**
  3564. * On keyboard close sets keyboard state to closed, resets the scroll view,
  3565. * removes CSS from body indicating keyboard was open, removes any event
  3566. * listeners for when the keyboard is open and on Android blurs the active
  3567. * element (which in some cases will still have focus even if the keyboard
  3568. * is closed and can cause it to reappear on subsequent taps).
  3569. */
  3570. function keyboardHide() {
  3571. clearTimeout(keyboardFocusOutTimer);
  3572. //console.log("keyboardHide");
  3573. ionic.keyboard.isOpen = false;
  3574. ionic.keyboard.isClosing = false;
  3575. if (keyboardActiveElement || lastKeyboardActiveElement) {
  3576. ionic.trigger('resetScrollView', {
  3577. target: keyboardActiveElement || lastKeyboardActiveElement
  3578. }, true);
  3579. }
  3580. ionic.requestAnimationFrame(function(){
  3581. document.body.classList.remove(KEYBOARD_OPEN_CSS);
  3582. });
  3583. // the keyboard is gone now, remove the touchmove that disables native scroll
  3584. if (window.navigator.msPointerEnabled) {
  3585. document.removeEventListener("MSPointerMove", keyboardPreventDefault);
  3586. } else {
  3587. document.removeEventListener('touchmove', keyboardPreventDefault);
  3588. }
  3589. document.removeEventListener('keydown', keyboardOnKeyDown);
  3590. if (ionic.Platform.isAndroid()) {
  3591. // on android closing the keyboard with the back/dismiss button won't remove
  3592. // focus and keyboard can re-appear on subsequent taps (like scrolling)
  3593. if (keyboardHasPlugin()) cordova.plugins.Keyboard.close();
  3594. keyboardActiveElement && keyboardActiveElement.blur();
  3595. }
  3596. keyboardActiveElement = null;
  3597. lastKeyboardActiveElement = null;
  3598. }
  3599. /**
  3600. * On keyboard open sets keyboard state to open, adds CSS to the body
  3601. * indicating the keyboard is open and tells the scroll view to resize and
  3602. * the currently focused input into view if necessary.
  3603. */
  3604. function keyboardShow() {
  3605. ionic.keyboard.isOpen = true;
  3606. ionic.keyboard.isOpening = false;
  3607. var details = {
  3608. keyboardHeight: keyboardGetHeight(),
  3609. viewportHeight: keyboardCurrentViewportHeight
  3610. };
  3611. if (keyboardActiveElement) {
  3612. details.target = keyboardActiveElement;
  3613. var elementBounds = keyboardActiveElement.getBoundingClientRect();
  3614. details.elementTop = Math.round(elementBounds.top);
  3615. details.elementBottom = Math.round(elementBounds.bottom);
  3616. details.windowHeight = details.viewportHeight - details.keyboardHeight;
  3617. //console.log("keyboardShow viewportHeight: " + details.viewportHeight +
  3618. //", windowHeight: " + details.windowHeight +
  3619. //", keyboardHeight: " + details.keyboardHeight);
  3620. // figure out if the element is under the keyboard
  3621. details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);
  3622. //console.log("isUnderKeyboard: " + details.isElementUnderKeyboard);
  3623. //console.log("elementBottom: " + details.elementBottom);
  3624. // send event so the scroll view adjusts
  3625. ionic.trigger('scrollChildIntoView', details, true);
  3626. }
  3627. setTimeout(function(){
  3628. document.body.classList.add(KEYBOARD_OPEN_CSS);
  3629. }, 400);
  3630. return details; //for testing
  3631. }
  3632. /* eslint no-unused-vars:0 */
  3633. function keyboardGetHeight() {
  3634. // check if we already have a keyboard height from the plugin or resize calculations
  3635. if (ionic.keyboard.height) {
  3636. return ionic.keyboard.height;
  3637. }
  3638. if (ionic.Platform.isAndroid()) {
  3639. // should be using the plugin, no way to know how big the keyboard is, so guess
  3640. if ( ionic.Platform.isFullScreen ) {
  3641. return 275;
  3642. }
  3643. // otherwise just calculate it
  3644. var contentHeight = window.innerHeight;
  3645. if (contentHeight < keyboardCurrentViewportHeight) {
  3646. return keyboardCurrentViewportHeight - contentHeight;
  3647. } else {
  3648. return 0;
  3649. }
  3650. }
  3651. // fallback for when it's the webview without the plugin
  3652. // or for just the standard web browser
  3653. // TODO: have these be based on device
  3654. if (ionic.Platform.isIOS()) {
  3655. if (ionic.keyboard.isLandscape) {
  3656. return 206;
  3657. }
  3658. if (!ionic.Platform.isWebView()) {
  3659. return 216;
  3660. }
  3661. return 260;
  3662. }
  3663. // safe guess
  3664. return 275;
  3665. }
  3666. function isPortraitViewportHeight(viewportHeight) {
  3667. return !!(!ionic.keyboard.isLandscape &&
  3668. keyboardPortraitViewportHeight &&
  3669. (Math.abs(keyboardPortraitViewportHeight - viewportHeight) < 2));
  3670. }
  3671. function isLandscapeViewportHeight(viewportHeight) {
  3672. return !!(ionic.keyboard.isLandscape &&
  3673. keyboardLandscapeViewportHeight &&
  3674. (Math.abs(keyboardLandscapeViewportHeight - viewportHeight) < 2));
  3675. }
  3676. function keyboardUpdateViewportHeight() {
  3677. wasOrientationChange = false;
  3678. keyboardCurrentViewportHeight = getViewportHeight();
  3679. if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {
  3680. //console.log("saved landscape: " + keyboardCurrentViewportHeight);
  3681. keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;
  3682. } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {
  3683. //console.log("saved portrait: " + keyboardCurrentViewportHeight);
  3684. keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;
  3685. }
  3686. if (keyboardActiveElement) {
  3687. ionic.trigger('resetScrollView', {
  3688. target: keyboardActiveElement
  3689. }, true);
  3690. }
  3691. if (ionic.keyboard.isOpen && ionic.tap.isTextInput(keyboardActiveElement)) {
  3692. keyboardShow();
  3693. }
  3694. }
  3695. function keyboardInitViewportHeight() {
  3696. var viewportHeight = getViewportHeight();
  3697. //console.log("Keyboard init VP: " + viewportHeight + " " + window.innerWidth);
  3698. // can't just use window.innerHeight in case the keyboard is opened immediately
  3699. if ((viewportHeight / window.innerWidth) < 1) {
  3700. ionic.keyboard.isLandscape = true;
  3701. }
  3702. //console.log("ionic.keyboard.isLandscape is: " + ionic.keyboard.isLandscape);
  3703. // initialize or update the current viewport height values
  3704. keyboardCurrentViewportHeight = viewportHeight;
  3705. if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {
  3706. keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;
  3707. } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {
  3708. keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;
  3709. }
  3710. }
  3711. function getViewportHeight() {
  3712. var windowHeight = window.innerHeight;
  3713. //console.log('window.innerHeight is: ' + windowHeight);
  3714. //console.log('kb height is: ' + ionic.keyboard.height);
  3715. //console.log('kb isOpen: ' + ionic.keyboard.isOpen);
  3716. //TODO: add iPad undocked/split kb once kb plugin supports it
  3717. // the keyboard overlays the window on Android fullscreen
  3718. if (!(ionic.Platform.isAndroid() && ionic.Platform.isFullScreen) &&
  3719. (ionic.keyboard.isOpen || ionic.keyboard.isOpening) &&
  3720. !ionic.keyboard.isClosing) {
  3721. return windowHeight + keyboardGetHeight();
  3722. }
  3723. return windowHeight;
  3724. }
  3725. function keyboardHasPlugin() {
  3726. return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard);
  3727. }
  3728. ionic.Platform.ready(function() {
  3729. keyboardInitViewportHeight();
  3730. window.addEventListener('orientationchange', keyboardOrientationChange);
  3731. // if orientation changes while app is in background, update on resuming
  3732. /*
  3733. if ( ionic.Platform.isWebView() ) {
  3734. document.addEventListener('resume', keyboardInitViewportHeight);
  3735. if (ionic.Platform.isAndroid()) {
  3736. //TODO: onbackpressed to detect keyboard close without focusout or plugin
  3737. }
  3738. }
  3739. */
  3740. // if orientation changes while app is in background, update on resuming
  3741. /* if ( ionic.Platform.isWebView() ) {
  3742. document.addEventListener('pause', function() {
  3743. window.removeEventListener('orientationchange', keyboardOrientationChange);
  3744. })
  3745. document.addEventListener('resume', function() {
  3746. keyboardInitViewportHeight();
  3747. window.addEventListener('orientationchange', keyboardOrientationChange)
  3748. });
  3749. }*/
  3750. // Android sometimes reports bad innerHeight on window.load
  3751. // try it again in a lil bit to play it safe
  3752. setTimeout(keyboardInitViewportHeight, 999);
  3753. // only initialize the adjustments for the virtual keyboard
  3754. // if a touchstart event happens
  3755. if (window.navigator.msPointerEnabled) {
  3756. document.addEventListener("MSPointerDown", keyboardInit, false);
  3757. } else {
  3758. document.addEventListener('touchstart', keyboardInit, false);
  3759. }
  3760. });
  3761. var viewportTag;
  3762. var viewportProperties = {};
  3763. ionic.viewport = {
  3764. orientation: function() {
  3765. // 0 = Portrait
  3766. // 90 = Landscape
  3767. // not using window.orientation because each device has a different implementation
  3768. return (window.innerWidth > window.innerHeight ? 90 : 0);
  3769. }
  3770. };
  3771. function viewportLoadTag() {
  3772. var x;
  3773. for (x = 0; x < document.head.children.length; x++) {
  3774. if (document.head.children[x].name == 'viewport') {
  3775. viewportTag = document.head.children[x];
  3776. break;
  3777. }
  3778. }
  3779. if (viewportTag) {
  3780. var props = viewportTag.content.toLowerCase().replace(/\s+/g, '').split(',');
  3781. var keyValue;
  3782. for (x = 0; x < props.length; x++) {
  3783. if (props[x]) {
  3784. keyValue = props[x].split('=');
  3785. viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_');
  3786. }
  3787. }
  3788. viewportUpdate();
  3789. }
  3790. }
  3791. function viewportUpdate() {
  3792. // unit tests in viewport.unit.js
  3793. var initWidth = viewportProperties.width;
  3794. var initHeight = viewportProperties.height;
  3795. var p = ionic.Platform;
  3796. var version = p.version();
  3797. var DEVICE_WIDTH = 'device-width';
  3798. var DEVICE_HEIGHT = 'device-height';
  3799. var orientation = ionic.viewport.orientation();
  3800. // Most times we're removing the height and adding the width
  3801. // So this is the default to start with, then modify per platform/version/oreintation
  3802. delete viewportProperties.height;
  3803. viewportProperties.width = DEVICE_WIDTH;
  3804. if (p.isIPad()) {
  3805. // iPad
  3806. if (version > 7) {
  3807. // iPad >= 7.1
  3808. // https://issues.apache.org/jira/browse/CB-4323
  3809. delete viewportProperties.width;
  3810. } else {
  3811. // iPad <= 7.0
  3812. if (p.isWebView()) {
  3813. // iPad <= 7.0 WebView
  3814. if (orientation == 90) {
  3815. // iPad <= 7.0 WebView Landscape
  3816. viewportProperties.height = '0';
  3817. } else if (version == 7) {
  3818. // iPad <= 7.0 WebView Portait
  3819. viewportProperties.height = DEVICE_HEIGHT;
  3820. }
  3821. } else {
  3822. // iPad <= 6.1 Browser
  3823. if (version < 7) {
  3824. viewportProperties.height = '0';
  3825. }
  3826. }
  3827. }
  3828. } else if (p.isIOS()) {
  3829. // iPhone
  3830. if (p.isWebView()) {
  3831. // iPhone WebView
  3832. if (version > 7) {
  3833. // iPhone >= 7.1 WebView
  3834. delete viewportProperties.width;
  3835. } else if (version < 7) {
  3836. // iPhone <= 6.1 WebView
  3837. // if height was set it needs to get removed with this hack for <= 6.1
  3838. if (initHeight) viewportProperties.height = '0';
  3839. } else if (version == 7) {
  3840. //iPhone == 7.0 WebView
  3841. viewportProperties.height = DEVICE_HEIGHT;
  3842. }
  3843. } else {
  3844. // iPhone Browser
  3845. if (version < 7) {
  3846. // iPhone <= 6.1 Browser
  3847. // if height was set it needs to get removed with this hack for <= 6.1
  3848. if (initHeight) viewportProperties.height = '0';
  3849. }
  3850. }
  3851. }
  3852. // only update the viewport tag if there was a change
  3853. if (initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) {
  3854. viewportTagUpdate();
  3855. }
  3856. }
  3857. function viewportTagUpdate() {
  3858. var key, props = [];
  3859. for (key in viewportProperties) {
  3860. if (viewportProperties[key]) {
  3861. props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key]));
  3862. }
  3863. }
  3864. viewportTag.content = props.join(', ');
  3865. }
  3866. ionic.Platform.ready(function() {
  3867. viewportLoadTag();
  3868. window.addEventListener("orientationchange", function() {
  3869. setTimeout(viewportUpdate, 1000);
  3870. }, false);
  3871. });
  3872. (function(ionic) {
  3873. 'use strict';
  3874. ionic.views.View = function() {
  3875. this.initialize.apply(this, arguments);
  3876. };
  3877. ionic.views.View.inherit = ionic.inherit;
  3878. ionic.extend(ionic.views.View.prototype, {
  3879. initialize: function() {}
  3880. });
  3881. })(window.ionic);
  3882. /*
  3883. * Scroller
  3884. * http://github.com/zynga/scroller
  3885. *
  3886. * Copyright 2011, Zynga Inc.
  3887. * Licensed under the MIT License.
  3888. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
  3889. *
  3890. * Based on the work of: Unify Project (unify-project.org)
  3891. * http://unify-project.org
  3892. * Copyright 2011, Deutsche Telekom AG
  3893. * License: MIT + Apache (V2)
  3894. */
  3895. /* jshint eqnull: true */
  3896. /**
  3897. * Generic animation class with support for dropped frames both optional easing and duration.
  3898. *
  3899. * Optional duration is useful when the lifetime is defined by another condition than time
  3900. * e.g. speed of an animating object, etc.
  3901. *
  3902. * Dropped frame logic allows to keep using the same updater logic independent from the actual
  3903. * rendering. This eases a lot of cases where it might be pretty complex to break down a state
  3904. * based on the pure time difference.
  3905. */
  3906. var zyngaCore = { effect: {} };
  3907. (function(global) {
  3908. var time = Date.now || function() {
  3909. return +new Date();
  3910. };
  3911. var desiredFrames = 60;
  3912. var millisecondsPerSecond = 1000;
  3913. var running = {};
  3914. var counter = 1;
  3915. zyngaCore.effect.Animate = {
  3916. /**
  3917. * A requestAnimationFrame wrapper / polyfill.
  3918. *
  3919. * @param callback {Function} The callback to be invoked before the next repaint.
  3920. * @param root {HTMLElement} The root element for the repaint
  3921. */
  3922. requestAnimationFrame: (function() {
  3923. // Check for request animation Frame support
  3924. var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame;
  3925. var isNative = !!requestFrame;
  3926. if (requestFrame && !/requestAnimationFrame\(\)\s*\{\s*\[native code\]\s*\}/i.test(requestFrame.toString())) {
  3927. isNative = false;
  3928. }
  3929. if (isNative) {
  3930. return function(callback, root) {
  3931. requestFrame(callback, root);
  3932. };
  3933. }
  3934. var TARGET_FPS = 60;
  3935. var requests = {};
  3936. var requestCount = 0;
  3937. var rafHandle = 1;
  3938. var intervalHandle = null;
  3939. var lastActive = +new Date();
  3940. return function(callback) {
  3941. var callbackHandle = rafHandle++;
  3942. // Store callback
  3943. requests[callbackHandle] = callback;
  3944. requestCount++;
  3945. // Create timeout at first request
  3946. if (intervalHandle === null) {
  3947. intervalHandle = setInterval(function() {
  3948. var time = +new Date();
  3949. var currentRequests = requests;
  3950. // Reset data structure before executing callbacks
  3951. requests = {};
  3952. requestCount = 0;
  3953. for(var key in currentRequests) {
  3954. if (currentRequests.hasOwnProperty(key)) {
  3955. currentRequests[key](time);
  3956. lastActive = time;
  3957. }
  3958. }
  3959. // Disable the timeout when nothing happens for a certain
  3960. // period of time
  3961. if (time - lastActive > 2500) {
  3962. clearInterval(intervalHandle);
  3963. intervalHandle = null;
  3964. }
  3965. }, 1000 / TARGET_FPS);
  3966. }
  3967. return callbackHandle;
  3968. };
  3969. })(),
  3970. /**
  3971. * Stops the given animation.
  3972. *
  3973. * @param id {Integer} Unique animation ID
  3974. * @return {Boolean} Whether the animation was stopped (aka, was running before)
  3975. */
  3976. stop: function(id) {
  3977. var cleared = running[id] != null;
  3978. if (cleared) {
  3979. running[id] = null;
  3980. }
  3981. return cleared;
  3982. },
  3983. /**
  3984. * Whether the given animation is still running.
  3985. *
  3986. * @param id {Integer} Unique animation ID
  3987. * @return {Boolean} Whether the animation is still running
  3988. */
  3989. isRunning: function(id) {
  3990. return running[id] != null;
  3991. },
  3992. /**
  3993. * Start the animation.
  3994. *
  3995. * @param stepCallback {Function} Pointer to function which is executed on every step.
  3996. * Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }`
  3997. * @param verifyCallback {Function} Executed before every animation step.
  3998. * Signature of the method should be `function() { return continueWithAnimation; }`
  3999. * @param completedCallback {Function}
  4000. * Signature of the method should be `function(droppedFrames, finishedAnimation) {}`
  4001. * @param duration {Integer} Milliseconds to run the animation
  4002. * @param easingMethod {Function} Pointer to easing function
  4003. * Signature of the method should be `function(percent) { return modifiedValue; }`
  4004. * @param root {Element} Render root, when available. Used for internal
  4005. * usage of requestAnimationFrame.
  4006. * @return {Integer} Identifier of animation. Can be used to stop it any time.
  4007. */
  4008. start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {
  4009. var start = time();
  4010. var lastFrame = start;
  4011. var percent = 0;
  4012. var dropCounter = 0;
  4013. var id = counter++;
  4014. if (!root) {
  4015. root = document.body;
  4016. }
  4017. // Compacting running db automatically every few new animations
  4018. if (id % 20 === 0) {
  4019. var newRunning = {};
  4020. for (var usedId in running) {
  4021. newRunning[usedId] = true;
  4022. }
  4023. running = newRunning;
  4024. }
  4025. // This is the internal step method which is called every few milliseconds
  4026. var step = function(virtual) {
  4027. // Normalize virtual value
  4028. var render = virtual !== true;
  4029. // Get current time
  4030. var now = time();
  4031. // Verification is executed before next animation step
  4032. if (!running[id] || (verifyCallback && !verifyCallback(id))) {
  4033. running[id] = null;
  4034. completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false);
  4035. return;
  4036. }
  4037. // For the current rendering to apply let's update omitted steps in memory.
  4038. // This is important to bring internal state variables up-to-date with progress in time.
  4039. if (render) {
  4040. var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1;
  4041. for (var j = 0; j < Math.min(droppedFrames, 4); j++) {
  4042. step(true);
  4043. dropCounter++;
  4044. }
  4045. }
  4046. // Compute percent value
  4047. if (duration) {
  4048. percent = (now - start) / duration;
  4049. if (percent > 1) {
  4050. percent = 1;
  4051. }
  4052. }
  4053. // Execute step callback, then...
  4054. var value = easingMethod ? easingMethod(percent) : percent;
  4055. if ((stepCallback(value, now, render) === false || percent === 1) && render) {
  4056. running[id] = null;
  4057. completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null);
  4058. } else if (render) {
  4059. lastFrame = now;
  4060. zyngaCore.effect.Animate.requestAnimationFrame(step, root);
  4061. }
  4062. };
  4063. // Mark as running
  4064. running[id] = true;
  4065. // Init first step
  4066. zyngaCore.effect.Animate.requestAnimationFrame(step, root);
  4067. // Return unique animation ID
  4068. return id;
  4069. }
  4070. };
  4071. })(window);
  4072. /*
  4073. * Scroller
  4074. * http://github.com/zynga/scroller
  4075. *
  4076. * Copyright 2011, Zynga Inc.
  4077. * Licensed under the MIT License.
  4078. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt
  4079. *
  4080. * Based on the work of: Unify Project (unify-project.org)
  4081. * http://unify-project.org
  4082. * Copyright 2011, Deutsche Telekom AG
  4083. * License: MIT + Apache (V2)
  4084. */
  4085. (function(ionic) {
  4086. var NOOP = function(){};
  4087. // Easing Equations (c) 2003 Robert Penner, all rights reserved.
  4088. // Open source under the BSD License.
  4089. /**
  4090. * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
  4091. **/
  4092. var easeOutCubic = function(pos) {
  4093. return (Math.pow((pos - 1), 3) + 1);
  4094. };
  4095. /**
  4096. * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)
  4097. **/
  4098. var easeInOutCubic = function(pos) {
  4099. if ((pos /= 0.5) < 1) {
  4100. return 0.5 * Math.pow(pos, 3);
  4101. }
  4102. return 0.5 * (Math.pow((pos - 2), 3) + 2);
  4103. };
  4104. /**
  4105. * ionic.views.Scroll
  4106. * A powerful scroll view with support for bouncing, pull to refresh, and paging.
  4107. * @param {Object} options options for the scroll view
  4108. * @class A scroll view system
  4109. * @memberof ionic.views
  4110. */
  4111. ionic.views.Scroll = ionic.views.View.inherit({
  4112. initialize: function(options) {
  4113. var self = this;
  4114. self.__container = options.el;
  4115. self.__content = options.el.firstElementChild;
  4116. //Remove any scrollTop attached to these elements; they are virtual scroll now
  4117. //This also stops on-load-scroll-to-window.location.hash that the browser does
  4118. setTimeout(function() {
  4119. if (self.__container && self.__content) {
  4120. self.__container.scrollTop = 0;
  4121. self.__content.scrollTop = 0;
  4122. }
  4123. });
  4124. self.options = {
  4125. /** Disable scrolling on x-axis by default */
  4126. scrollingX: false,
  4127. scrollbarX: true,
  4128. /** Enable scrolling on y-axis */
  4129. scrollingY: true,
  4130. scrollbarY: true,
  4131. startX: 0,
  4132. startY: 0,
  4133. /** The amount to dampen mousewheel events */
  4134. wheelDampen: 6,
  4135. /** The minimum size the scrollbars scale to while scrolling */
  4136. minScrollbarSizeX: 5,
  4137. minScrollbarSizeY: 5,
  4138. /** Scrollbar fading after scrolling */
  4139. scrollbarsFade: true,
  4140. scrollbarFadeDelay: 300,
  4141. /** The initial fade delay when the pane is resized or initialized */
  4142. scrollbarResizeFadeDelay: 1000,
  4143. /** Enable animations for deceleration, snap back, zooming and scrolling */
  4144. animating: true,
  4145. /** duration for animations triggered by scrollTo/zoomTo */
  4146. animationDuration: 250,
  4147. /** The velocity required to make the scroll view "slide" after touchend */
  4148. decelVelocityThreshold: 4,
  4149. /** The velocity required to make the scroll view "slide" after touchend when using paging */
  4150. decelVelocityThresholdPaging: 4,
  4151. /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */
  4152. bouncing: true,
  4153. /** Enable locking to the main axis if user moves only slightly on one of them at start */
  4154. locking: true,
  4155. /** Enable pagination mode (switching between full page content panes) */
  4156. paging: false,
  4157. /** Enable snapping of content to a configured pixel grid */
  4158. snapping: false,
  4159. /** Enable zooming of content via API, fingers and mouse wheel */
  4160. zooming: false,
  4161. /** Minimum zoom level */
  4162. minZoom: 0.5,
  4163. /** Maximum zoom level */
  4164. maxZoom: 3,
  4165. /** Multiply or decrease scrolling speed **/
  4166. speedMultiplier: 1,
  4167. deceleration: 0.97,
  4168. /** Whether to prevent default on a scroll operation to capture drag events **/
  4169. preventDefault: false,
  4170. /** Callback that is fired on the later of touch end or deceleration end,
  4171. provided that another scrolling action has not begun. Used to know
  4172. when to fade out a scrollbar. */
  4173. scrollingComplete: NOOP,
  4174. /** This configures the amount of change applied to deceleration when reaching boundaries **/
  4175. penetrationDeceleration: 0.03,
  4176. /** This configures the amount of change applied to acceleration when reaching boundaries **/
  4177. penetrationAcceleration: 0.08,
  4178. // The ms interval for triggering scroll events
  4179. scrollEventInterval: 10,
  4180. freeze: false,
  4181. getContentWidth: function() {
  4182. return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);
  4183. },
  4184. getContentHeight: function() {
  4185. return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));
  4186. }
  4187. };
  4188. for (var key in options) {
  4189. self.options[key] = options[key];
  4190. }
  4191. self.hintResize = ionic.debounce(function() {
  4192. self.resize();
  4193. }, 1000, true);
  4194. self.onScroll = function() {
  4195. if (!ionic.scroll.isScrolling) {
  4196. setTimeout(self.setScrollStart, 50);
  4197. } else {
  4198. clearTimeout(self.scrollTimer);
  4199. self.scrollTimer = setTimeout(self.setScrollStop, 80);
  4200. }
  4201. };
  4202. self.freeze = function(shouldFreeze) {
  4203. if (arguments.length) {
  4204. self.options.freeze = shouldFreeze;
  4205. }
  4206. return self.options.freeze;
  4207. };
  4208. // We can just use the standard freeze pop in our mouth
  4209. self.freezeShut = self.freeze;
  4210. self.setScrollStart = function() {
  4211. ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1;
  4212. clearTimeout(self.scrollTimer);
  4213. self.scrollTimer = setTimeout(self.setScrollStop, 80);
  4214. };
  4215. self.setScrollStop = function() {
  4216. ionic.scroll.isScrolling = false;
  4217. ionic.scroll.lastTop = self.__scrollTop;
  4218. };
  4219. self.triggerScrollEvent = ionic.throttle(function() {
  4220. self.onScroll();
  4221. ionic.trigger('scroll', {
  4222. scrollTop: self.__scrollTop,
  4223. scrollLeft: self.__scrollLeft,
  4224. target: self.__container
  4225. });
  4226. }, self.options.scrollEventInterval);
  4227. self.triggerScrollEndEvent = function() {
  4228. ionic.trigger('scrollend', {
  4229. scrollTop: self.__scrollTop,
  4230. scrollLeft: self.__scrollLeft,
  4231. target: self.__container
  4232. });
  4233. };
  4234. self.__scrollLeft = self.options.startX;
  4235. self.__scrollTop = self.options.startY;
  4236. // Get the render update function, initialize event handlers,
  4237. // and calculate the size of the scroll container
  4238. self.__callback = self.getRenderFn();
  4239. self.__initEventHandlers();
  4240. self.__createScrollbars();
  4241. },
  4242. run: function() {
  4243. this.resize();
  4244. // Fade them out
  4245. this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay);
  4246. },
  4247. /*
  4248. ---------------------------------------------------------------------------
  4249. INTERNAL FIELDS :: STATUS
  4250. ---------------------------------------------------------------------------
  4251. */
  4252. /** Whether only a single finger is used in touch handling */
  4253. __isSingleTouch: false,
  4254. /** Whether a touch event sequence is in progress */
  4255. __isTracking: false,
  4256. /** Whether a deceleration animation went to completion. */
  4257. __didDecelerationComplete: false,
  4258. /**
  4259. * Whether a gesture zoom/rotate event is in progress. Activates when
  4260. * a gesturestart event happens. This has higher priority than dragging.
  4261. */
  4262. __isGesturing: false,
  4263. /**
  4264. * Whether the user has moved by such a distance that we have enabled
  4265. * dragging mode. Hint: It's only enabled after some pixels of movement to
  4266. * not interrupt with clicks etc.
  4267. */
  4268. __isDragging: false,
  4269. /**
  4270. * Not touching and dragging anymore, and smoothly animating the
  4271. * touch sequence using deceleration.
  4272. */
  4273. __isDecelerating: false,
  4274. /**
  4275. * Smoothly animating the currently configured change
  4276. */
  4277. __isAnimating: false,
  4278. /*
  4279. ---------------------------------------------------------------------------
  4280. INTERNAL FIELDS :: DIMENSIONS
  4281. ---------------------------------------------------------------------------
  4282. */
  4283. /** Available outer left position (from document perspective) */
  4284. __clientLeft: 0,
  4285. /** Available outer top position (from document perspective) */
  4286. __clientTop: 0,
  4287. /** Available outer width */
  4288. __clientWidth: 0,
  4289. /** Available outer height */
  4290. __clientHeight: 0,
  4291. /** Outer width of content */
  4292. __contentWidth: 0,
  4293. /** Outer height of content */
  4294. __contentHeight: 0,
  4295. /** Snapping width for content */
  4296. __snapWidth: 100,
  4297. /** Snapping height for content */
  4298. __snapHeight: 100,
  4299. /** Height to assign to refresh area */
  4300. __refreshHeight: null,
  4301. /** Whether the refresh process is enabled when the event is released now */
  4302. __refreshActive: false,
  4303. /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */
  4304. __refreshActivate: null,
  4305. /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */
  4306. __refreshDeactivate: null,
  4307. /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */
  4308. __refreshStart: null,
  4309. /** Zoom level */
  4310. __zoomLevel: 1,
  4311. /** Scroll position on x-axis */
  4312. __scrollLeft: 0,
  4313. /** Scroll position on y-axis */
  4314. __scrollTop: 0,
  4315. /** Maximum allowed scroll position on x-axis */
  4316. __maxScrollLeft: 0,
  4317. /** Maximum allowed scroll position on y-axis */
  4318. __maxScrollTop: 0,
  4319. /* Scheduled left position (final position when animating) */
  4320. __scheduledLeft: 0,
  4321. /* Scheduled top position (final position when animating) */
  4322. __scheduledTop: 0,
  4323. /* Scheduled zoom level (final scale when animating) */
  4324. __scheduledZoom: 0,
  4325. /*
  4326. ---------------------------------------------------------------------------
  4327. INTERNAL FIELDS :: LAST POSITIONS
  4328. ---------------------------------------------------------------------------
  4329. */
  4330. /** Left position of finger at start */
  4331. __lastTouchLeft: null,
  4332. /** Top position of finger at start */
  4333. __lastTouchTop: null,
  4334. /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */
  4335. __lastTouchMove: null,
  4336. /** List of positions, uses three indexes for each state: left, top, timestamp */
  4337. __positions: null,
  4338. /*
  4339. ---------------------------------------------------------------------------
  4340. INTERNAL FIELDS :: DECELERATION SUPPORT
  4341. ---------------------------------------------------------------------------
  4342. */
  4343. /** Minimum left scroll position during deceleration */
  4344. __minDecelerationScrollLeft: null,
  4345. /** Minimum top scroll position during deceleration */
  4346. __minDecelerationScrollTop: null,
  4347. /** Maximum left scroll position during deceleration */
  4348. __maxDecelerationScrollLeft: null,
  4349. /** Maximum top scroll position during deceleration */
  4350. __maxDecelerationScrollTop: null,
  4351. /** Current factor to modify horizontal scroll position with on every step */
  4352. __decelerationVelocityX: null,
  4353. /** Current factor to modify vertical scroll position with on every step */
  4354. __decelerationVelocityY: null,
  4355. /** the browser-specific property to use for transforms */
  4356. __transformProperty: null,
  4357. __perspectiveProperty: null,
  4358. /** scrollbar indicators */
  4359. __indicatorX: null,
  4360. __indicatorY: null,
  4361. /** Timeout for scrollbar fading */
  4362. __scrollbarFadeTimeout: null,
  4363. /** whether we've tried to wait for size already */
  4364. __didWaitForSize: null,
  4365. __sizerTimeout: null,
  4366. __initEventHandlers: function() {
  4367. var self = this;
  4368. // Event Handler
  4369. var container = self.__container;
  4370. // save height when scroll view is shrunk so we don't need to reflow
  4371. var scrollViewOffsetHeight;
  4372. /**
  4373. * Shrink the scroll view when the keyboard is up if necessary and if the
  4374. * focused input is below the bottom of the shrunk scroll view, scroll it
  4375. * into view.
  4376. */
  4377. self.scrollChildIntoView = function(e) {
  4378. //console.log("scrollChildIntoView at: " + Date.now());
  4379. // D
  4380. var scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  4381. // D - A
  4382. scrollViewOffsetHeight = container.offsetHeight;
  4383. var alreadyShrunk = self.isShrunkForKeyboard;
  4384. var isModal = container.parentNode.classList.contains('modal');
  4385. // 680px is when the media query for 60% modal width kicks in
  4386. var isInsetModal = isModal && window.innerWidth >= 680;
  4387. /*
  4388. * _______
  4389. * |---A---| <- top of scroll view
  4390. * | |
  4391. * |---B---| <- keyboard
  4392. * | C | <- input
  4393. * |---D---| <- initial bottom of scroll view
  4394. * |___E___| <- bottom of viewport
  4395. *
  4396. * All commented calculations relative to the top of the viewport (ie E
  4397. * is the viewport height, not 0)
  4398. */
  4399. if (!alreadyShrunk) {
  4400. // shrink scrollview so we can actually scroll if the input is hidden
  4401. // if it isn't shrink so we can scroll to inputs under the keyboard
  4402. // inset modals won't shrink on Android on their own when the keyboard appears
  4403. if ( ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal ) {
  4404. // if there are things below the scroll view account for them and
  4405. // subtract them from the keyboard height when resizing
  4406. // E - D E D
  4407. var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;
  4408. // 0 or D - B if D > B E - B E - D
  4409. var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom);
  4410. ionic.requestAnimationFrame(function(){
  4411. // D - A or B - A if D > B D - A max(0, D - B)
  4412. scrollViewOffsetHeight = scrollViewOffsetHeight - keyboardOffset;
  4413. container.style.height = scrollViewOffsetHeight + "px";
  4414. container.style.overflow = "visible";
  4415. //update scroll view
  4416. self.resize();
  4417. });
  4418. }
  4419. self.isShrunkForKeyboard = true;
  4420. }
  4421. /*
  4422. * _______
  4423. * |---A---| <- top of scroll view
  4424. * | * | <- where we want to scroll to
  4425. * |--B-D--| <- keyboard, bottom of scroll view
  4426. * | C | <- input
  4427. * | |
  4428. * |___E___| <- bottom of viewport
  4429. *
  4430. * All commented calculations relative to the top of the viewport (ie E
  4431. * is the viewport height, not 0)
  4432. */
  4433. // if the element is positioned under the keyboard scroll it into view
  4434. if (e.detail.isElementUnderKeyboard) {
  4435. ionic.requestAnimationFrame(function(){
  4436. container.scrollTop = 0;
  4437. // update D if we shrunk
  4438. if (self.isShrunkForKeyboard && !alreadyShrunk) {
  4439. scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  4440. }
  4441. // middle of the scrollview, this is where we want to scroll to
  4442. // (D - A) / 2
  4443. var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;
  4444. //console.log("container.offsetHeight: " + scrollViewOffsetHeight);
  4445. // middle of the input we want to scroll into view
  4446. // C
  4447. var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);
  4448. // distance from middle of input to the bottom of the scroll view
  4449. // C - D C D
  4450. var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;
  4451. //C - D + (D - A)/2 C - D (D - A)/ 2
  4452. var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;
  4453. if ( scrollTop > 0) {
  4454. if (ionic.Platform.isIOS()) ionic.tap.cloneFocusedInput(container, self);
  4455. self.scrollBy(0, scrollTop, true);
  4456. self.onScroll();
  4457. }
  4458. });
  4459. }
  4460. // Only the first scrollView parent of the element that broadcasted this event
  4461. // (the active element that needs to be shown) should receive this event
  4462. e.stopPropagation();
  4463. };
  4464. self.resetScrollView = function() {
  4465. //return scrollview to original height once keyboard has hidden
  4466. if ( self.isShrunkForKeyboard ) {
  4467. self.isShrunkForKeyboard = false;
  4468. container.style.height = "";
  4469. container.style.overflow = "";
  4470. }
  4471. self.resize();
  4472. };
  4473. //Broadcasted when keyboard is shown on some platforms.
  4474. //See js/utils/keyboard.js
  4475. container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);
  4476. // Listen on document because container may not have had the last
  4477. // keyboardActiveElement, for example after closing a modal with a focused
  4478. // input and returning to a previously resized scroll view in an ion-content.
  4479. // Since we can only resize scroll views that are currently visible, just resize
  4480. // the current scroll view when the keyboard is closed.
  4481. document.addEventListener('resetScrollView', self.resetScrollView);
  4482. function getEventTouches(e) {
  4483. return e.touches && e.touches.length ? e.touches : [{
  4484. pageX: e.pageX,
  4485. pageY: e.pageY
  4486. }];
  4487. }
  4488. self.touchStart = function(e) {
  4489. self.startCoordinates = ionic.tap.pointerCoord(e);
  4490. if ( ionic.tap.ignoreScrollStart(e) ) {
  4491. return;
  4492. }
  4493. self.__isDown = true;
  4494. if ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) {
  4495. // do not start if the target is a text input
  4496. // if there is a touchmove on this input, then we can start the scroll
  4497. self.__hasStarted = false;
  4498. return;
  4499. }
  4500. self.__isSelectable = true;
  4501. self.__enableScrollY = true;
  4502. self.__hasStarted = true;
  4503. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4504. e.preventDefault();
  4505. };
  4506. self.touchMove = function(e) {
  4507. if (self.options.freeze || !self.__isDown ||
  4508. (!self.__isDown && e.defaultPrevented) ||
  4509. (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) {
  4510. return;
  4511. }
  4512. if ( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) {
  4513. // the target is a text input and scroll has started
  4514. // since the text input doesn't start on touchStart, do it here
  4515. self.__hasStarted = true;
  4516. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4517. e.preventDefault();
  4518. return;
  4519. }
  4520. if (self.startCoordinates) {
  4521. // we have start coordinates, so get this touch move's current coordinates
  4522. var currentCoordinates = ionic.tap.pointerCoord(e);
  4523. if ( self.__isSelectable &&
  4524. ionic.tap.isTextInput(e.target) &&
  4525. Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) {
  4526. // user slid the text input's caret on its x axis, disable any future y scrolling
  4527. self.__enableScrollY = false;
  4528. self.__isSelectable = true;
  4529. }
  4530. if ( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) {
  4531. // user scrolled the entire view on the y axis
  4532. // disabled being able to select text on an input
  4533. // hide the input which has focus, and show a cloned one that doesn't have focus
  4534. self.__isSelectable = false;
  4535. ionic.tap.cloneFocusedInput(container, self);
  4536. }
  4537. }
  4538. self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale);
  4539. self.__isDown = true;
  4540. };
  4541. self.touchMoveBubble = function(e) {
  4542. if(self.__isDown && self.options.preventDefault) {
  4543. e.preventDefault();
  4544. }
  4545. };
  4546. self.touchEnd = function(e) {
  4547. if (!self.__isDown) return;
  4548. self.doTouchEnd(e, e.timeStamp);
  4549. self.__isDown = false;
  4550. self.__hasStarted = false;
  4551. self.__isSelectable = true;
  4552. self.__enableScrollY = true;
  4553. if ( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) {
  4554. ionic.tap.removeClonedInputs(container, self);
  4555. }
  4556. };
  4557. self.mouseWheel = ionic.animationFrameThrottle(function(e) {
  4558. var scrollParent = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'ionic-scroll');
  4559. if (!self.options.freeze && scrollParent === self.__container) {
  4560. self.hintResize();
  4561. self.scrollBy(
  4562. (e.wheelDeltaX || e.deltaX || 0) / self.options.wheelDampen,
  4563. (-e.wheelDeltaY || e.deltaY || 0) / self.options.wheelDampen
  4564. );
  4565. self.__fadeScrollbars('in');
  4566. clearTimeout(self.__wheelHideBarTimeout);
  4567. self.__wheelHideBarTimeout = setTimeout(function() {
  4568. self.__fadeScrollbars('out');
  4569. }, 100);
  4570. }
  4571. });
  4572. if ('ontouchstart' in window) {
  4573. // Touch Events
  4574. container.addEventListener("touchstart", self.touchStart, false);
  4575. if(self.options.preventDefault) container.addEventListener("touchmove", self.touchMoveBubble, false);
  4576. document.addEventListener("touchmove", self.touchMove, false);
  4577. document.addEventListener("touchend", self.touchEnd, false);
  4578. document.addEventListener("touchcancel", self.touchEnd, false);
  4579. document.addEventListener("wheel", self.mouseWheel, false);
  4580. } else if (window.navigator.pointerEnabled) {
  4581. // Pointer Events
  4582. container.addEventListener("pointerdown", self.touchStart, false);
  4583. if(self.options.preventDefault) container.addEventListener("pointermove", self.touchMoveBubble, false);
  4584. document.addEventListener("pointermove", self.touchMove, false);
  4585. document.addEventListener("pointerup", self.touchEnd, false);
  4586. document.addEventListener("pointercancel", self.touchEnd, false);
  4587. document.addEventListener("wheel", self.mouseWheel, false);
  4588. } else if (window.navigator.msPointerEnabled) {
  4589. // IE10, WP8 (Pointer Events)
  4590. container.addEventListener("MSPointerDown", self.touchStart, false);
  4591. if(self.options.preventDefault) container.addEventListener("MSPointerMove", self.touchMoveBubble, false);
  4592. document.addEventListener("MSPointerMove", self.touchMove, false);
  4593. document.addEventListener("MSPointerUp", self.touchEnd, false);
  4594. document.addEventListener("MSPointerCancel", self.touchEnd, false);
  4595. document.addEventListener("wheel", self.mouseWheel, false);
  4596. } else {
  4597. // Mouse Events
  4598. var mousedown = false;
  4599. self.mouseDown = function(e) {
  4600. if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) {
  4601. return;
  4602. }
  4603. self.doTouchStart(getEventTouches(e), e.timeStamp);
  4604. if ( !ionic.tap.isTextInput(e.target) ) {
  4605. e.preventDefault();
  4606. }
  4607. mousedown = true;
  4608. };
  4609. self.mouseMove = function(e) {
  4610. if (self.options.freeze || !mousedown || (!mousedown && e.defaultPrevented)) {
  4611. return;
  4612. }
  4613. self.doTouchMove(getEventTouches(e), e.timeStamp);
  4614. mousedown = true;
  4615. };
  4616. self.mouseMoveBubble = function(e) {
  4617. if (mousedown && self.options.preventDefault) {
  4618. e.preventDefault();
  4619. }
  4620. };
  4621. self.mouseUp = function(e) {
  4622. if (!mousedown) {
  4623. return;
  4624. }
  4625. self.doTouchEnd(e, e.timeStamp);
  4626. mousedown = false;
  4627. };
  4628. container.addEventListener("mousedown", self.mouseDown, false);
  4629. if(self.options.preventDefault) container.addEventListener("mousemove", self.mouseMoveBubble, false);
  4630. document.addEventListener("mousemove", self.mouseMove, false);
  4631. document.addEventListener("mouseup", self.mouseUp, false);
  4632. document.addEventListener('mousewheel', self.mouseWheel, false);
  4633. document.addEventListener('wheel', self.mouseWheel, false);
  4634. }
  4635. },
  4636. __cleanup: function() {
  4637. var self = this;
  4638. var container = self.__container;
  4639. container.removeEventListener('touchstart', self.touchStart);
  4640. container.removeEventListener('touchmove', self.touchMoveBubble);
  4641. document.removeEventListener('touchmove', self.touchMove);
  4642. document.removeEventListener('touchend', self.touchEnd);
  4643. document.removeEventListener('touchcancel', self.touchEnd);
  4644. container.removeEventListener("pointerdown", self.touchStart);
  4645. container.removeEventListener("pointermove", self.touchMoveBubble);
  4646. document.removeEventListener("pointermove", self.touchMove);
  4647. document.removeEventListener("pointerup", self.touchEnd);
  4648. document.removeEventListener("pointercancel", self.touchEnd);
  4649. container.removeEventListener("MSPointerDown", self.touchStart);
  4650. container.removeEventListener("MSPointerMove", self.touchMoveBubble);
  4651. document.removeEventListener("MSPointerMove", self.touchMove);
  4652. document.removeEventListener("MSPointerUp", self.touchEnd);
  4653. document.removeEventListener("MSPointerCancel", self.touchEnd);
  4654. container.removeEventListener("mousedown", self.mouseDown);
  4655. container.removeEventListener("mousemove", self.mouseMoveBubble);
  4656. document.removeEventListener("mousemove", self.mouseMove);
  4657. document.removeEventListener("mouseup", self.mouseUp);
  4658. document.removeEventListener('mousewheel', self.mouseWheel);
  4659. document.removeEventListener('wheel', self.mouseWheel);
  4660. container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);
  4661. document.removeEventListener('resetScrollView', self.resetScrollView);
  4662. ionic.tap.removeClonedInputs(container, self);
  4663. delete self.__container;
  4664. delete self.__content;
  4665. delete self.__indicatorX;
  4666. delete self.__indicatorY;
  4667. delete self.options.el;
  4668. self.__callback = self.scrollChildIntoView = self.resetScrollView = NOOP;
  4669. self.mouseMove = self.mouseDown = self.mouseUp = self.mouseWheel =
  4670. self.touchStart = self.touchMove = self.touchEnd = self.touchCancel = NOOP;
  4671. self.resize = self.scrollTo = self.zoomTo =
  4672. self.__scrollingComplete = NOOP;
  4673. container = null;
  4674. },
  4675. /** Create a scroll bar div with the given direction **/
  4676. __createScrollbar: function(direction) {
  4677. var bar = document.createElement('div'),
  4678. indicator = document.createElement('div');
  4679. indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';
  4680. if (direction == 'h') {
  4681. bar.className = 'scroll-bar scroll-bar-h';
  4682. } else {
  4683. bar.className = 'scroll-bar scroll-bar-v';
  4684. }
  4685. bar.appendChild(indicator);
  4686. return bar;
  4687. },
  4688. __createScrollbars: function() {
  4689. var self = this;
  4690. var indicatorX, indicatorY;
  4691. if (self.options.scrollingX) {
  4692. indicatorX = {
  4693. el: self.__createScrollbar('h'),
  4694. sizeRatio: 1
  4695. };
  4696. indicatorX.indicator = indicatorX.el.children[0];
  4697. if (self.options.scrollbarX) {
  4698. self.__container.appendChild(indicatorX.el);
  4699. }
  4700. self.__indicatorX = indicatorX;
  4701. }
  4702. if (self.options.scrollingY) {
  4703. indicatorY = {
  4704. el: self.__createScrollbar('v'),
  4705. sizeRatio: 1
  4706. };
  4707. indicatorY.indicator = indicatorY.el.children[0];
  4708. if (self.options.scrollbarY) {
  4709. self.__container.appendChild(indicatorY.el);
  4710. }
  4711. self.__indicatorY = indicatorY;
  4712. }
  4713. },
  4714. __resizeScrollbars: function() {
  4715. var self = this;
  4716. // Update horiz bar
  4717. if (self.__indicatorX) {
  4718. var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20);
  4719. if (width > self.__contentWidth) {
  4720. width = 0;
  4721. }
  4722. if (width !== self.__indicatorX.size) {
  4723. ionic.requestAnimationFrame(function(){
  4724. self.__indicatorX.indicator.style.width = width + 'px';
  4725. });
  4726. }
  4727. self.__indicatorX.size = width;
  4728. self.__indicatorX.minScale = self.options.minScrollbarSizeX / width;
  4729. self.__indicatorX.maxPos = self.__clientWidth - width;
  4730. self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1;
  4731. }
  4732. // Update vert bar
  4733. if (self.__indicatorY) {
  4734. var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20);
  4735. if (height > self.__contentHeight) {
  4736. height = 0;
  4737. }
  4738. if (height !== self.__indicatorY.size) {
  4739. ionic.requestAnimationFrame(function(){
  4740. self.__indicatorY && (self.__indicatorY.indicator.style.height = height + 'px');
  4741. });
  4742. }
  4743. self.__indicatorY.size = height;
  4744. self.__indicatorY.minScale = self.options.minScrollbarSizeY / height;
  4745. self.__indicatorY.maxPos = self.__clientHeight - height;
  4746. self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1;
  4747. }
  4748. },
  4749. /**
  4750. * Move and scale the scrollbars as the page scrolls.
  4751. */
  4752. __repositionScrollbars: function() {
  4753. var self = this,
  4754. heightScale, widthScale,
  4755. widthDiff, heightDiff,
  4756. x, y,
  4757. xstop = 0, ystop = 0;
  4758. if (self.__indicatorX) {
  4759. // Handle the X scrollbar
  4760. // Don't go all the way to the right if we have a vertical scrollbar as well
  4761. if (self.__indicatorY) xstop = 10;
  4762. x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0;
  4763. // The the difference between the last content X position, and our overscrolled one
  4764. widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop);
  4765. if (self.__scrollLeft < 0) {
  4766. widthScale = Math.max(self.__indicatorX.minScale,
  4767. (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size);
  4768. // Stay at left
  4769. x = 0;
  4770. // Make sure scale is transformed from the left/center origin point
  4771. self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center';
  4772. } else if (widthDiff > 0) {
  4773. widthScale = Math.max(self.__indicatorX.minScale,
  4774. (self.__indicatorX.size - widthDiff) / self.__indicatorX.size);
  4775. // Stay at the furthest x for the scrollable viewport
  4776. x = self.__indicatorX.maxPos - xstop;
  4777. // Make sure scale is transformed from the right/center origin point
  4778. self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center';
  4779. } else {
  4780. // Normal motion
  4781. x = Math.min(self.__maxScrollLeft, Math.max(0, x));
  4782. widthScale = 1;
  4783. }
  4784. var translate3dX = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')';
  4785. if (self.__indicatorX.transformProp !== translate3dX) {
  4786. self.__indicatorX.indicator.style[self.__transformProperty] = translate3dX;
  4787. self.__indicatorX.transformProp = translate3dX;
  4788. }
  4789. }
  4790. if (self.__indicatorY) {
  4791. y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0;
  4792. // Don't go all the way to the right if we have a vertical scrollbar as well
  4793. if (self.__indicatorX) ystop = 10;
  4794. heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop);
  4795. if (self.__scrollTop < 0) {
  4796. heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size);
  4797. // Stay at top
  4798. y = 0;
  4799. // Make sure scale is transformed from the center/top origin point
  4800. if (self.__indicatorY.originProp !== 'center top') {
  4801. self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top';
  4802. self.__indicatorY.originProp = 'center top';
  4803. }
  4804. } else if (heightDiff > 0) {
  4805. heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size);
  4806. // Stay at bottom of scrollable viewport
  4807. y = self.__indicatorY.maxPos - ystop;
  4808. // Make sure scale is transformed from the center/bottom origin point
  4809. if (self.__indicatorY.originProp !== 'center bottom') {
  4810. self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom';
  4811. self.__indicatorY.originProp = 'center bottom';
  4812. }
  4813. } else {
  4814. // Normal motion
  4815. y = Math.min(self.__maxScrollTop, Math.max(0, y));
  4816. heightScale = 1;
  4817. }
  4818. var translate3dY = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')';
  4819. if (self.__indicatorY.transformProp !== translate3dY) {
  4820. self.__indicatorY.indicator.style[self.__transformProperty] = translate3dY;
  4821. self.__indicatorY.transformProp = translate3dY;
  4822. }
  4823. }
  4824. },
  4825. __fadeScrollbars: function(direction, delay) {
  4826. var self = this;
  4827. if (!self.options.scrollbarsFade) {
  4828. return;
  4829. }
  4830. var className = 'scroll-bar-fade-out';
  4831. if (self.options.scrollbarsFade === true) {
  4832. clearTimeout(self.__scrollbarFadeTimeout);
  4833. if (direction == 'in') {
  4834. if (self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); }
  4835. if (self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); }
  4836. } else {
  4837. self.__scrollbarFadeTimeout = setTimeout(function() {
  4838. if (self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); }
  4839. if (self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); }
  4840. }, delay || self.options.scrollbarFadeDelay);
  4841. }
  4842. }
  4843. },
  4844. __scrollingComplete: function() {
  4845. this.options.scrollingComplete();
  4846. ionic.tap.removeClonedInputs(this.__container, this);
  4847. this.__fadeScrollbars('out');
  4848. },
  4849. resize: function(continueScrolling) {
  4850. var self = this;
  4851. if (!self.__container || !self.options) return;
  4852. // Update Scroller dimensions for changed content
  4853. // Add padding to bottom of content
  4854. self.setDimensions(
  4855. self.__container.clientWidth,
  4856. self.__container.clientHeight,
  4857. self.options.getContentWidth(),
  4858. self.options.getContentHeight(),
  4859. continueScrolling
  4860. );
  4861. },
  4862. /*
  4863. ---------------------------------------------------------------------------
  4864. PUBLIC API
  4865. ---------------------------------------------------------------------------
  4866. */
  4867. getRenderFn: function() {
  4868. var self = this;
  4869. var content = self.__content;
  4870. var docStyle = document.documentElement.style;
  4871. var engine;
  4872. if ('MozAppearance' in docStyle) {
  4873. engine = 'gecko';
  4874. } else if ('WebkitAppearance' in docStyle) {
  4875. engine = 'webkit';
  4876. } else if (typeof navigator.cpuClass === 'string') {
  4877. engine = 'trident';
  4878. }
  4879. var vendorPrefix = {
  4880. trident: 'ms',
  4881. gecko: 'Moz',
  4882. webkit: 'Webkit',
  4883. presto: 'O'
  4884. }[engine];
  4885. var helperElem = document.createElement("div");
  4886. var undef;
  4887. var perspectiveProperty = vendorPrefix + "Perspective";
  4888. var transformProperty = vendorPrefix + "Transform";
  4889. var transformOriginProperty = vendorPrefix + 'TransformOrigin';
  4890. self.__perspectiveProperty = transformProperty;
  4891. self.__transformProperty = transformProperty;
  4892. self.__transformOriginProperty = transformOriginProperty;
  4893. if (helperElem.style[perspectiveProperty] !== undef) {
  4894. return function(left, top, zoom, wasResize) {
  4895. var translate3d = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';
  4896. if (translate3d !== self.contentTransform) {
  4897. content.style[transformProperty] = translate3d;
  4898. self.contentTransform = translate3d;
  4899. }
  4900. self.__repositionScrollbars();
  4901. if (!wasResize) {
  4902. self.triggerScrollEvent();
  4903. }
  4904. };
  4905. } else if (helperElem.style[transformProperty] !== undef) {
  4906. return function(left, top, zoom, wasResize) {
  4907. content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';
  4908. self.__repositionScrollbars();
  4909. if (!wasResize) {
  4910. self.triggerScrollEvent();
  4911. }
  4912. };
  4913. } else {
  4914. return function(left, top, zoom, wasResize) {
  4915. content.style.marginLeft = left ? (-left / zoom) + 'px' : '';
  4916. content.style.marginTop = top ? (-top / zoom) + 'px' : '';
  4917. content.style.zoom = zoom || '';
  4918. self.__repositionScrollbars();
  4919. if (!wasResize) {
  4920. self.triggerScrollEvent();
  4921. }
  4922. };
  4923. }
  4924. },
  4925. /**
  4926. * Configures the dimensions of the client (outer) and content (inner) elements.
  4927. * Requires the available space for the outer element and the outer size of the inner element.
  4928. * All values which are falsy (null or zero etc.) are ignored and the old value is kept.
  4929. *
  4930. * @param clientWidth {Integer} Inner width of outer element
  4931. * @param clientHeight {Integer} Inner height of outer element
  4932. * @param contentWidth {Integer} Outer width of inner element
  4933. * @param contentHeight {Integer} Outer height of inner element
  4934. */
  4935. setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight, continueScrolling) {
  4936. var self = this;
  4937. if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {
  4938. // this scrollview isn't rendered, don't bother
  4939. return;
  4940. }
  4941. // Only update values which are defined
  4942. if (clientWidth === +clientWidth) {
  4943. self.__clientWidth = clientWidth;
  4944. }
  4945. if (clientHeight === +clientHeight) {
  4946. self.__clientHeight = clientHeight;
  4947. }
  4948. if (contentWidth === +contentWidth) {
  4949. self.__contentWidth = contentWidth;
  4950. }
  4951. if (contentHeight === +contentHeight) {
  4952. self.__contentHeight = contentHeight;
  4953. }
  4954. // Refresh maximums
  4955. self.__computeScrollMax();
  4956. self.__resizeScrollbars();
  4957. // Refresh scroll position
  4958. if (!continueScrolling) {
  4959. self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true);
  4960. }
  4961. },
  4962. /**
  4963. * Sets the client coordinates in relation to the document.
  4964. *
  4965. * @param left {Integer} Left position of outer element
  4966. * @param top {Integer} Top position of outer element
  4967. */
  4968. setPosition: function(left, top) {
  4969. this.__clientLeft = left || 0;
  4970. this.__clientTop = top || 0;
  4971. },
  4972. /**
  4973. * Configures the snapping (when snapping is active)
  4974. *
  4975. * @param width {Integer} Snapping width
  4976. * @param height {Integer} Snapping height
  4977. */
  4978. setSnapSize: function(width, height) {
  4979. this.__snapWidth = width;
  4980. this.__snapHeight = height;
  4981. },
  4982. /**
  4983. * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever
  4984. * the user event is released during visibility of this zone. This was introduced by some apps on iOS like
  4985. * the official Twitter client.
  4986. *
  4987. * @param height {Integer} Height of pull-to-refresh zone on top of rendered list
  4988. * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release.
  4989. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled.
  4990. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh.
  4991. * @param showCallback {Function} Callback to execute when the refresher should be shown. This is for showing the refresher during a negative scrollTop.
  4992. * @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.
  4993. * @param tailCallback {Function} Callback to execute just before the refresher returns to it's original state. This is for zooming out the refresher.
  4994. * @param pullProgressCallback Callback to state the progress while pulling to refresh
  4995. */
  4996. activatePullToRefresh: function(height, refresherMethods) {
  4997. var self = this;
  4998. self.__refreshHeight = height;
  4999. self.__refreshActivate = function() { ionic.requestAnimationFrame(refresherMethods.activate); };
  5000. self.__refreshDeactivate = function() { ionic.requestAnimationFrame(refresherMethods.deactivate); };
  5001. self.__refreshStart = function() { ionic.requestAnimationFrame(refresherMethods.start); };
  5002. self.__refreshShow = function() { ionic.requestAnimationFrame(refresherMethods.show); };
  5003. self.__refreshHide = function() { ionic.requestAnimationFrame(refresherMethods.hide); };
  5004. self.__refreshTail = function() { ionic.requestAnimationFrame(refresherMethods.tail); };
  5005. self.__refreshTailTime = 100;
  5006. self.__minSpinTime = 600;
  5007. },
  5008. /**
  5009. * Starts pull-to-refresh manually.
  5010. */
  5011. triggerPullToRefresh: function() {
  5012. // Use publish instead of scrollTo to allow scrolling to out of boundary position
  5013. // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
  5014. this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true);
  5015. var d = new Date();
  5016. this.refreshStartTime = d.getTime();
  5017. if (this.__refreshStart) {
  5018. this.__refreshStart();
  5019. }
  5020. },
  5021. /**
  5022. * Signalizes that pull-to-refresh is finished.
  5023. */
  5024. finishPullToRefresh: function() {
  5025. var self = this;
  5026. // delay to make sure the spinner has a chance to spin for a split second before it's dismissed
  5027. var d = new Date();
  5028. var delay = 0;
  5029. if (self.refreshStartTime + self.__minSpinTime > d.getTime()) {
  5030. delay = self.refreshStartTime + self.__minSpinTime - d.getTime();
  5031. }
  5032. setTimeout(function() {
  5033. if (self.__refreshTail) {
  5034. self.__refreshTail();
  5035. }
  5036. setTimeout(function() {
  5037. self.__refreshActive = false;
  5038. if (self.__refreshDeactivate) {
  5039. self.__refreshDeactivate();
  5040. }
  5041. if (self.__refreshHide) {
  5042. self.__refreshHide();
  5043. }
  5044. self.scrollTo(self.__scrollLeft, self.__scrollTop, true);
  5045. }, self.__refreshTailTime);
  5046. }, delay);
  5047. },
  5048. /**
  5049. * Returns the scroll position and zooming values
  5050. *
  5051. * @return {Map} `left` and `top` scroll position and `zoom` level
  5052. */
  5053. getValues: function() {
  5054. return {
  5055. left: this.__scrollLeft,
  5056. top: this.__scrollTop,
  5057. zoom: this.__zoomLevel
  5058. };
  5059. },
  5060. /**
  5061. * Returns the maximum scroll values
  5062. *
  5063. * @return {Map} `left` and `top` maximum scroll values
  5064. */
  5065. getScrollMax: function() {
  5066. return {
  5067. left: this.__maxScrollLeft,
  5068. top: this.__maxScrollTop
  5069. };
  5070. },
  5071. /**
  5072. * Zooms to the given level. Supports optional animation. Zooms
  5073. * the center when no coordinates are given.
  5074. *
  5075. * @param level {Number} Level to zoom to
  5076. * @param animate {Boolean} Whether to use animation
  5077. * @param originLeft {Number} Zoom in at given left coordinate
  5078. * @param originTop {Number} Zoom in at given top coordinate
  5079. */
  5080. zoomTo: function(level, animate, originLeft, originTop) {
  5081. var self = this;
  5082. if (!self.options.zooming) {
  5083. throw new Error("Zooming is not enabled!");
  5084. }
  5085. // Stop deceleration
  5086. if (self.__isDecelerating) {
  5087. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5088. self.__isDecelerating = false;
  5089. }
  5090. var oldLevel = self.__zoomLevel;
  5091. // Normalize input origin to center of viewport if not defined
  5092. if (originLeft == null) {
  5093. originLeft = self.__clientWidth / 2;
  5094. }
  5095. if (originTop == null) {
  5096. originTop = self.__clientHeight / 2;
  5097. }
  5098. // Limit level according to configuration
  5099. level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
  5100. // Recompute maximum values while temporary tweaking maximum scroll ranges
  5101. self.__computeScrollMax(level);
  5102. // Recompute left and top coordinates based on new zoom level
  5103. var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft;
  5104. var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop;
  5105. // Limit x-axis
  5106. if (left > self.__maxScrollLeft) {
  5107. left = self.__maxScrollLeft;
  5108. } else if (left < 0) {
  5109. left = 0;
  5110. }
  5111. // Limit y-axis
  5112. if (top > self.__maxScrollTop) {
  5113. top = self.__maxScrollTop;
  5114. } else if (top < 0) {
  5115. top = 0;
  5116. }
  5117. // Push values out
  5118. self.__publish(left, top, level, animate);
  5119. },
  5120. /**
  5121. * Zooms the content by the given factor.
  5122. *
  5123. * @param factor {Number} Zoom by given factor
  5124. * @param animate {Boolean} Whether to use animation
  5125. * @param originLeft {Number} Zoom in at given left coordinate
  5126. * @param originTop {Number} Zoom in at given top coordinate
  5127. */
  5128. zoomBy: function(factor, animate, originLeft, originTop) {
  5129. this.zoomTo(this.__zoomLevel * factor, animate, originLeft, originTop);
  5130. },
  5131. /**
  5132. * Scrolls to the given position. Respect limitations and snapping automatically.
  5133. *
  5134. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5135. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5136. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5137. * @param zoom {Number} Zoom level to go to
  5138. */
  5139. scrollTo: function(left, top, animate, zoom, wasResize) {
  5140. var self = this;
  5141. // Stop deceleration
  5142. if (self.__isDecelerating) {
  5143. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5144. self.__isDecelerating = false;
  5145. }
  5146. // Correct coordinates based on new zoom level
  5147. if (zoom != null && zoom !== self.__zoomLevel) {
  5148. if (!self.options.zooming) {
  5149. throw new Error("Zooming is not enabled!");
  5150. }
  5151. left *= zoom;
  5152. top *= zoom;
  5153. // Recompute maximum values while temporary tweaking maximum scroll ranges
  5154. self.__computeScrollMax(zoom);
  5155. } else {
  5156. // Keep zoom when not defined
  5157. zoom = self.__zoomLevel;
  5158. }
  5159. if (!self.options.scrollingX) {
  5160. left = self.__scrollLeft;
  5161. } else {
  5162. if (self.options.paging) {
  5163. left = Math.round(left / self.__clientWidth) * self.__clientWidth;
  5164. } else if (self.options.snapping) {
  5165. left = Math.round(left / self.__snapWidth) * self.__snapWidth;
  5166. }
  5167. }
  5168. if (!self.options.scrollingY) {
  5169. top = self.__scrollTop;
  5170. } else {
  5171. if (self.options.paging) {
  5172. top = Math.round(top / self.__clientHeight) * self.__clientHeight;
  5173. } else if (self.options.snapping) {
  5174. top = Math.round(top / self.__snapHeight) * self.__snapHeight;
  5175. }
  5176. }
  5177. // Limit for allowed ranges
  5178. left = Math.max(Math.min(self.__maxScrollLeft, left), 0);
  5179. top = Math.max(Math.min(self.__maxScrollTop, top), 0);
  5180. // Don't animate when no change detected, still call publish to make sure
  5181. // that rendered position is really in-sync with internal data
  5182. if (left === self.__scrollLeft && top === self.__scrollTop) {
  5183. animate = false;
  5184. }
  5185. // Publish new values
  5186. self.__publish(left, top, zoom, animate, wasResize);
  5187. },
  5188. /**
  5189. * Scroll by the given offset
  5190. *
  5191. * @param left {Number} Scroll x-axis by given offset
  5192. * @param top {Number} Scroll y-axis by given offset
  5193. * @param animate {Boolean} Whether to animate the given change
  5194. */
  5195. scrollBy: function(left, top, animate) {
  5196. var self = this;
  5197. var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;
  5198. var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;
  5199. self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);
  5200. },
  5201. /*
  5202. ---------------------------------------------------------------------------
  5203. EVENT CALLBACKS
  5204. ---------------------------------------------------------------------------
  5205. */
  5206. /**
  5207. * Mouse wheel handler for zooming support
  5208. */
  5209. doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) {
  5210. var change = wheelDelta > 0 ? 0.97 : 1.03;
  5211. return this.zoomTo(this.__zoomLevel * change, false, pageX - this.__clientLeft, pageY - this.__clientTop);
  5212. },
  5213. /**
  5214. * Touch start handler for scrolling support
  5215. */
  5216. doTouchStart: function(touches, timeStamp) {
  5217. var self = this;
  5218. // remember if the deceleration was just stopped
  5219. self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);
  5220. self.hintResize();
  5221. if (timeStamp instanceof Date) {
  5222. timeStamp = timeStamp.valueOf();
  5223. }
  5224. if (typeof timeStamp !== "number") {
  5225. timeStamp = Date.now();
  5226. }
  5227. // Reset interruptedAnimation flag
  5228. self.__interruptedAnimation = true;
  5229. // Stop deceleration
  5230. if (self.__isDecelerating) {
  5231. zyngaCore.effect.Animate.stop(self.__isDecelerating);
  5232. self.__isDecelerating = false;
  5233. self.__interruptedAnimation = true;
  5234. }
  5235. // Stop animation
  5236. if (self.__isAnimating) {
  5237. zyngaCore.effect.Animate.stop(self.__isAnimating);
  5238. self.__isAnimating = false;
  5239. self.__interruptedAnimation = true;
  5240. }
  5241. // Use center point when dealing with two fingers
  5242. var currentTouchLeft, currentTouchTop;
  5243. var isSingleTouch = touches.length === 1;
  5244. if (isSingleTouch) {
  5245. currentTouchLeft = touches[0].pageX;
  5246. currentTouchTop = touches[0].pageY;
  5247. } else {
  5248. currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
  5249. currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
  5250. }
  5251. // Store initial positions
  5252. self.__initialTouchLeft = currentTouchLeft;
  5253. self.__initialTouchTop = currentTouchTop;
  5254. // Store initial touchList for scale calculation
  5255. self.__initialTouches = touches;
  5256. // Store current zoom level
  5257. self.__zoomLevelStart = self.__zoomLevel;
  5258. // Store initial touch positions
  5259. self.__lastTouchLeft = currentTouchLeft;
  5260. self.__lastTouchTop = currentTouchTop;
  5261. // Store initial move time stamp
  5262. self.__lastTouchMove = timeStamp;
  5263. // Reset initial scale
  5264. self.__lastScale = 1;
  5265. // Reset locking flags
  5266. self.__enableScrollX = !isSingleTouch && self.options.scrollingX;
  5267. self.__enableScrollY = !isSingleTouch && self.options.scrollingY;
  5268. // Reset tracking flag
  5269. self.__isTracking = true;
  5270. // Reset deceleration complete flag
  5271. self.__didDecelerationComplete = false;
  5272. // Dragging starts directly with two fingers, otherwise lazy with an offset
  5273. self.__isDragging = !isSingleTouch;
  5274. // Some features are disabled in multi touch scenarios
  5275. self.__isSingleTouch = isSingleTouch;
  5276. // Clearing data structure
  5277. self.__positions = [];
  5278. },
  5279. /**
  5280. * Touch move handler for scrolling support
  5281. */
  5282. doTouchMove: function(touches, timeStamp, scale) {
  5283. if (timeStamp instanceof Date) {
  5284. timeStamp = timeStamp.valueOf();
  5285. }
  5286. if (typeof timeStamp !== "number") {
  5287. timeStamp = Date.now();
  5288. }
  5289. var self = this;
  5290. // Ignore event when tracking is not enabled (event might be outside of element)
  5291. if (!self.__isTracking) {
  5292. return;
  5293. }
  5294. var currentTouchLeft, currentTouchTop;
  5295. // Compute move based around of center of fingers
  5296. if (touches.length === 2) {
  5297. currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;
  5298. currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;
  5299. // Calculate scale when not present and only when touches are used
  5300. if (!scale && self.options.zooming) {
  5301. scale = self.__getScale(self.__initialTouches, touches);
  5302. }
  5303. } else {
  5304. currentTouchLeft = touches[0].pageX;
  5305. currentTouchTop = touches[0].pageY;
  5306. }
  5307. var positions = self.__positions;
  5308. // Are we already is dragging mode?
  5309. if (self.__isDragging) {
  5310. self.__decStopped = false;
  5311. // Compute move distance
  5312. var moveX = currentTouchLeft - self.__lastTouchLeft;
  5313. var moveY = currentTouchTop - self.__lastTouchTop;
  5314. // Read previous scroll position and zooming
  5315. var scrollLeft = self.__scrollLeft;
  5316. var scrollTop = self.__scrollTop;
  5317. var level = self.__zoomLevel;
  5318. // Work with scaling
  5319. if (scale != null && self.options.zooming) {
  5320. var oldLevel = level;
  5321. // Recompute level based on previous scale and new scale
  5322. level = level / self.__lastScale * scale;
  5323. // Limit level according to configuration
  5324. level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);
  5325. // Only do further compution when change happened
  5326. if (oldLevel !== level) {
  5327. // Compute relative event position to container
  5328. var currentTouchLeftRel = currentTouchLeft - self.__clientLeft;
  5329. var currentTouchTopRel = currentTouchTop - self.__clientTop;
  5330. // Recompute left and top coordinates based on new zoom level
  5331. scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel;
  5332. scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel;
  5333. // Recompute max scroll values
  5334. self.__computeScrollMax(level);
  5335. }
  5336. }
  5337. if (self.__enableScrollX) {
  5338. scrollLeft -= moveX * self.options.speedMultiplier;
  5339. var maxScrollLeft = self.__maxScrollLeft;
  5340. if (scrollLeft > maxScrollLeft || scrollLeft < 0) {
  5341. // Slow down on the edges
  5342. if (self.options.bouncing) {
  5343. scrollLeft += (moveX / 2 * self.options.speedMultiplier);
  5344. } else if (scrollLeft > maxScrollLeft) {
  5345. scrollLeft = maxScrollLeft;
  5346. } else {
  5347. scrollLeft = 0;
  5348. }
  5349. }
  5350. }
  5351. // Compute new vertical scroll position
  5352. if (self.__enableScrollY) {
  5353. scrollTop -= moveY * self.options.speedMultiplier;
  5354. var maxScrollTop = self.__maxScrollTop;
  5355. if (scrollTop > maxScrollTop || scrollTop < 0) {
  5356. // Slow down on the edges
  5357. if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) {
  5358. scrollTop += (moveY / 2 * self.options.speedMultiplier);
  5359. // Support pull-to-refresh (only when only y is scrollable)
  5360. if (!self.__enableScrollX && self.__refreshHeight != null) {
  5361. // hide the refresher when it's behind the header bar in case of header transparency
  5362. if (scrollTop < 0) {
  5363. self.__refreshHidden = false;
  5364. self.__refreshShow();
  5365. } else {
  5366. self.__refreshHide();
  5367. self.__refreshHidden = true;
  5368. }
  5369. if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) {
  5370. self.__refreshActive = true;
  5371. if (self.__refreshActivate) {
  5372. self.__refreshActivate();
  5373. }
  5374. } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) {
  5375. self.__refreshActive = false;
  5376. if (self.__refreshDeactivate) {
  5377. self.__refreshDeactivate();
  5378. }
  5379. }
  5380. }
  5381. } else if (scrollTop > maxScrollTop) {
  5382. scrollTop = maxScrollTop;
  5383. } else {
  5384. scrollTop = 0;
  5385. }
  5386. } else if (self.__refreshHeight && !self.__refreshHidden) {
  5387. // if a positive scroll value and the refresher is still not hidden, hide it
  5388. self.__refreshHide();
  5389. self.__refreshHidden = true;
  5390. }
  5391. }
  5392. // Keep list from growing infinitely (holding min 10, max 20 measure points)
  5393. if (positions.length > 60) {
  5394. positions.splice(0, 30);
  5395. }
  5396. // Track scroll movement for decleration
  5397. positions.push(scrollLeft, scrollTop, timeStamp);
  5398. // Sync scroll position
  5399. self.__publish(scrollLeft, scrollTop, level);
  5400. // Otherwise figure out whether we are switching into dragging mode now.
  5401. } else {
  5402. var minimumTrackingForScroll = self.options.locking ? 3 : 0;
  5403. var minimumTrackingForDrag = 5;
  5404. var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft);
  5405. var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);
  5406. self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll;
  5407. self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll;
  5408. positions.push(self.__scrollLeft, self.__scrollTop, timeStamp);
  5409. self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag);
  5410. if (self.__isDragging) {
  5411. self.__interruptedAnimation = false;
  5412. self.__fadeScrollbars('in');
  5413. }
  5414. }
  5415. // Update last touch positions and time stamp for next event
  5416. self.__lastTouchLeft = currentTouchLeft;
  5417. self.__lastTouchTop = currentTouchTop;
  5418. self.__lastTouchMove = timeStamp;
  5419. self.__lastScale = scale;
  5420. },
  5421. /**
  5422. * Touch end handler for scrolling support
  5423. */
  5424. doTouchEnd: function(e, timeStamp) {
  5425. if (timeStamp instanceof Date) {
  5426. timeStamp = timeStamp.valueOf();
  5427. }
  5428. if (typeof timeStamp !== "number") {
  5429. timeStamp = Date.now();
  5430. }
  5431. var self = this;
  5432. // Ignore event when tracking is not enabled (no touchstart event on element)
  5433. // This is required as this listener ('touchmove') sits on the document and not on the element itself.
  5434. if (!self.__isTracking) {
  5435. return;
  5436. }
  5437. // Not touching anymore (when two finger hit the screen there are two touch end events)
  5438. self.__isTracking = false;
  5439. // Be sure to reset the dragging flag now. Here we also detect whether
  5440. // the finger has moved fast enough to switch into a deceleration animation.
  5441. if (self.__isDragging) {
  5442. // Reset dragging flag
  5443. self.__isDragging = false;
  5444. // Start deceleration
  5445. // Verify that the last move detected was in some relevant time frame
  5446. if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) {
  5447. // Then figure out what the scroll position was about 100ms ago
  5448. var positions = self.__positions;
  5449. var endPos = positions.length - 1;
  5450. var startPos = endPos;
  5451. // Move pointer to position measured 100ms ago
  5452. for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) {
  5453. startPos = i;
  5454. }
  5455. // If start and stop position is identical in a 100ms timeframe,
  5456. // we cannot compute any useful deceleration.
  5457. if (startPos !== endPos) {
  5458. // Compute relative movement between these two points
  5459. var timeOffset = positions[endPos] - positions[startPos];
  5460. var movedLeft = self.__scrollLeft - positions[startPos - 2];
  5461. var movedTop = self.__scrollTop - positions[startPos - 1];
  5462. // Based on 50ms compute the movement to apply for each render step
  5463. self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60);
  5464. self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60);
  5465. // How much velocity is required to start the deceleration
  5466. var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? self.options.decelVelocityThresholdPaging : self.options.decelVelocityThreshold;
  5467. // Verify that we have enough velocity to start deceleration
  5468. if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) {
  5469. // Deactivate pull-to-refresh when decelerating
  5470. if (!self.__refreshActive) {
  5471. self.__startDeceleration(timeStamp);
  5472. }
  5473. }
  5474. } else {
  5475. self.__scrollingComplete();
  5476. }
  5477. } else if ((timeStamp - self.__lastTouchMove) > 100) {
  5478. self.__scrollingComplete();
  5479. }
  5480. } else if (self.__decStopped) {
  5481. // the deceleration was stopped
  5482. // user flicked the scroll fast, and stop dragging, then did a touchstart to stop the srolling
  5483. // tell the touchend event code to do nothing, we don't want to actually send a click
  5484. e.isTapHandled = true;
  5485. self.__decStopped = false;
  5486. }
  5487. // If this was a slower move it is per default non decelerated, but this
  5488. // still means that we want snap back to the bounds which is done here.
  5489. // This is placed outside the condition above to improve edge case stability
  5490. // e.g. touchend fired without enabled dragging. This should normally do not
  5491. // have modified the scroll positions or even showed the scrollbars though.
  5492. if (!self.__isDecelerating) {
  5493. if (self.__refreshActive && self.__refreshStart) {
  5494. // Use publish instead of scrollTo to allow scrolling to out of boundary position
  5495. // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled
  5496. self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true);
  5497. var d = new Date();
  5498. self.refreshStartTime = d.getTime();
  5499. if (self.__refreshStart) {
  5500. self.__refreshStart();
  5501. }
  5502. // for iOS-ey style scrolling
  5503. if (!ionic.Platform.isAndroid())self.__startDeceleration();
  5504. } else {
  5505. if (self.__interruptedAnimation || self.__isDragging) {
  5506. self.__scrollingComplete();
  5507. }
  5508. self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel);
  5509. // Directly signalize deactivation (nothing todo on refresh?)
  5510. if (self.__refreshActive) {
  5511. self.__refreshActive = false;
  5512. if (self.__refreshDeactivate) {
  5513. self.__refreshDeactivate();
  5514. }
  5515. }
  5516. }
  5517. }
  5518. // Fully cleanup list
  5519. self.__positions.length = 0;
  5520. },
  5521. /*
  5522. ---------------------------------------------------------------------------
  5523. PRIVATE API
  5524. ---------------------------------------------------------------------------
  5525. */
  5526. /**
  5527. * Applies the scroll position to the content element
  5528. *
  5529. * @param left {Number} Left scroll position
  5530. * @param top {Number} Top scroll position
  5531. * @param animate {Boolean} Whether animation should be used to move to the new coordinates
  5532. */
  5533. __publish: function(left, top, zoom, animate, wasResize) {
  5534. var self = this;
  5535. // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation
  5536. var wasAnimating = self.__isAnimating;
  5537. if (wasAnimating) {
  5538. zyngaCore.effect.Animate.stop(wasAnimating);
  5539. self.__isAnimating = false;
  5540. }
  5541. if (animate && self.options.animating) {
  5542. // Keep scheduled positions for scrollBy/zoomBy functionality
  5543. self.__scheduledLeft = left;
  5544. self.__scheduledTop = top;
  5545. self.__scheduledZoom = zoom;
  5546. var oldLeft = self.__scrollLeft;
  5547. var oldTop = self.__scrollTop;
  5548. var oldZoom = self.__zoomLevel;
  5549. var diffLeft = left - oldLeft;
  5550. var diffTop = top - oldTop;
  5551. var diffZoom = zoom - oldZoom;
  5552. var step = function(percent, now, render) {
  5553. if (render) {
  5554. self.__scrollLeft = oldLeft + (diffLeft * percent);
  5555. self.__scrollTop = oldTop + (diffTop * percent);
  5556. self.__zoomLevel = oldZoom + (diffZoom * percent);
  5557. // Push values out
  5558. if (self.__callback) {
  5559. self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize);
  5560. }
  5561. }
  5562. };
  5563. var verify = function(id) {
  5564. return self.__isAnimating === id;
  5565. };
  5566. var completed = function(renderedFramesPerSecond, animationId, wasFinished) {
  5567. if (animationId === self.__isAnimating) {
  5568. self.__isAnimating = false;
  5569. }
  5570. if (self.__didDecelerationComplete || wasFinished) {
  5571. self.__scrollingComplete();
  5572. }
  5573. if (self.options.zooming) {
  5574. self.__computeScrollMax();
  5575. }
  5576. };
  5577. // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out
  5578. self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic);
  5579. } else {
  5580. self.__scheduledLeft = self.__scrollLeft = left;
  5581. self.__scheduledTop = self.__scrollTop = top;
  5582. self.__scheduledZoom = self.__zoomLevel = zoom;
  5583. // Push values out
  5584. if (self.__callback) {
  5585. self.__callback(left, top, zoom, wasResize);
  5586. }
  5587. // Fix max scroll ranges
  5588. if (self.options.zooming) {
  5589. self.__computeScrollMax();
  5590. }
  5591. }
  5592. },
  5593. /**
  5594. * Recomputes scroll minimum values based on client dimensions and content dimensions.
  5595. */
  5596. __computeScrollMax: function(zoomLevel) {
  5597. var self = this;
  5598. if (zoomLevel == null) {
  5599. zoomLevel = self.__zoomLevel;
  5600. }
  5601. self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0);
  5602. self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0);
  5603. if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {
  5604. self.__didWaitForSize = true;
  5605. self.__waitForSize();
  5606. }
  5607. },
  5608. /**
  5609. * If the scroll view isn't sized correctly on start, wait until we have at least some size
  5610. */
  5611. __waitForSize: function() {
  5612. var self = this;
  5613. clearTimeout(self.__sizerTimeout);
  5614. var sizer = function() {
  5615. self.resize(true);
  5616. };
  5617. sizer();
  5618. self.__sizerTimeout = setTimeout(sizer, 500);
  5619. },
  5620. /*
  5621. ---------------------------------------------------------------------------
  5622. ANIMATION (DECELERATION) SUPPORT
  5623. ---------------------------------------------------------------------------
  5624. */
  5625. /**
  5626. * Called when a touch sequence end and the speed of the finger was high enough
  5627. * to switch into deceleration mode.
  5628. */
  5629. __startDeceleration: function() {
  5630. var self = this;
  5631. if (self.options.paging) {
  5632. var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0);
  5633. var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0);
  5634. var clientWidth = self.__clientWidth;
  5635. var clientHeight = self.__clientHeight;
  5636. // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area.
  5637. // Each page should have exactly the size of the client area.
  5638. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth;
  5639. self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight;
  5640. self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth;
  5641. self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight;
  5642. } else {
  5643. self.__minDecelerationScrollLeft = 0;
  5644. self.__minDecelerationScrollTop = 0;
  5645. self.__maxDecelerationScrollLeft = self.__maxScrollLeft;
  5646. self.__maxDecelerationScrollTop = self.__maxScrollTop;
  5647. if (self.__refreshActive) self.__minDecelerationScrollTop = self.__refreshHeight * -1;
  5648. }
  5649. // Wrap class method
  5650. var step = function(percent, now, render) {
  5651. self.__stepThroughDeceleration(render);
  5652. };
  5653. // How much velocity is required to keep the deceleration running
  5654. self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1;
  5655. // Detect whether it's still worth to continue animating steps
  5656. // If we are already slow enough to not being user perceivable anymore, we stop the whole process here.
  5657. var verify = function() {
  5658. var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating ||
  5659. Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating;
  5660. if (!shouldContinue) {
  5661. self.__didDecelerationComplete = true;
  5662. //Make sure the scroll values are within the boundaries after a bounce,
  5663. //not below 0 or above maximum
  5664. if (self.options.bouncing && !self.__refreshActive) {
  5665. self.scrollTo(
  5666. Math.min( Math.max(self.__scrollLeft, 0), self.__maxScrollLeft ),
  5667. Math.min( Math.max(self.__scrollTop, 0), self.__maxScrollTop ),
  5668. self.__refreshActive
  5669. );
  5670. }
  5671. }
  5672. return shouldContinue;
  5673. };
  5674. var completed = function() {
  5675. self.__isDecelerating = false;
  5676. if (self.__didDecelerationComplete) {
  5677. self.__scrollingComplete();
  5678. }
  5679. // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions
  5680. if (self.options.paging) {
  5681. self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping);
  5682. }
  5683. };
  5684. // Start animation and switch on flag
  5685. self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed);
  5686. },
  5687. /**
  5688. * Called on every step of the animation
  5689. *
  5690. * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only!
  5691. */
  5692. __stepThroughDeceleration: function(render) {
  5693. var self = this;
  5694. //
  5695. // COMPUTE NEXT SCROLL POSITION
  5696. //
  5697. // Add deceleration to scroll position
  5698. var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration);
  5699. var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration);
  5700. //
  5701. // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE
  5702. //
  5703. if (!self.options.bouncing) {
  5704. var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);
  5705. if (scrollLeftFixed !== scrollLeft) {
  5706. scrollLeft = scrollLeftFixed;
  5707. self.__decelerationVelocityX = 0;
  5708. }
  5709. var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);
  5710. if (scrollTopFixed !== scrollTop) {
  5711. scrollTop = scrollTopFixed;
  5712. self.__decelerationVelocityY = 0;
  5713. }
  5714. }
  5715. //
  5716. // UPDATE SCROLL POSITION
  5717. //
  5718. if (render) {
  5719. self.__publish(scrollLeft, scrollTop, self.__zoomLevel);
  5720. } else {
  5721. self.__scrollLeft = scrollLeft;
  5722. self.__scrollTop = scrollTop;
  5723. }
  5724. //
  5725. // SLOW DOWN
  5726. //
  5727. // Slow down velocity on every iteration
  5728. if (!self.options.paging) {
  5729. // This is the factor applied to every iteration of the animation
  5730. // to slow down the process. This should emulate natural behavior where
  5731. // objects slow down when the initiator of the movement is removed
  5732. var frictionFactor = self.options.deceleration;
  5733. self.__decelerationVelocityX *= frictionFactor;
  5734. self.__decelerationVelocityY *= frictionFactor;
  5735. }
  5736. //
  5737. // BOUNCING SUPPORT
  5738. //
  5739. if (self.options.bouncing) {
  5740. var scrollOutsideX = 0;
  5741. var scrollOutsideY = 0;
  5742. // This configures the amount of change applied to deceleration/acceleration when reaching boundaries
  5743. var penetrationDeceleration = self.options.penetrationDeceleration;
  5744. var penetrationAcceleration = self.options.penetrationAcceleration;
  5745. // Check limits
  5746. if (scrollLeft < self.__minDecelerationScrollLeft) {
  5747. scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;
  5748. } else if (scrollLeft > self.__maxDecelerationScrollLeft) {
  5749. scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;
  5750. }
  5751. if (scrollTop < self.__minDecelerationScrollTop) {
  5752. scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;
  5753. } else if (scrollTop > self.__maxDecelerationScrollTop) {
  5754. scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;
  5755. }
  5756. // Slow down until slow enough, then flip back to snap position
  5757. if (scrollOutsideX !== 0) {
  5758. var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft;
  5759. if (isHeadingOutwardsX) {
  5760. self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;
  5761. }
  5762. var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating;
  5763. //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
  5764. if (!isHeadingOutwardsX || isStoppedX) {
  5765. self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;
  5766. }
  5767. }
  5768. if (scrollOutsideY !== 0) {
  5769. var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop;
  5770. if (isHeadingOutwardsY) {
  5771. self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;
  5772. }
  5773. var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating;
  5774. //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds
  5775. if (!isHeadingOutwardsY || isStoppedY) {
  5776. self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;
  5777. }
  5778. }
  5779. }
  5780. },
  5781. /**
  5782. * calculate the distance between two touches
  5783. * @param {Touch} touch1
  5784. * @param {Touch} touch2
  5785. * @returns {Number} distance
  5786. */
  5787. __getDistance: function getDistance(touch1, touch2) {
  5788. var x = touch2.pageX - touch1.pageX,
  5789. y = touch2.pageY - touch1.pageY;
  5790. return Math.sqrt((x * x) + (y * y));
  5791. },
  5792. /**
  5793. * calculate the scale factor between two touchLists (fingers)
  5794. * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
  5795. * @param {Array} start
  5796. * @param {Array} end
  5797. * @returns {Number} scale
  5798. */
  5799. __getScale: function getScale(start, end) {
  5800. // need two fingers...
  5801. if (start.length >= 2 && end.length >= 2) {
  5802. return this.__getDistance(end[0], end[1]) /
  5803. this.__getDistance(start[0], start[1]);
  5804. }
  5805. return 1;
  5806. }
  5807. });
  5808. ionic.scroll = {
  5809. isScrolling: false,
  5810. lastTop: 0
  5811. };
  5812. })(ionic);
  5813. (function(ionic) {
  5814. var NOOP = function() {};
  5815. var deprecated = function(name) {
  5816. void 0;
  5817. };
  5818. ionic.views.ScrollNative = ionic.views.View.inherit({
  5819. initialize: function(options) {
  5820. var self = this;
  5821. self.__container = self.el = options.el;
  5822. self.__content = options.el.firstElementChild;
  5823. // Whether scrolling is frozen or not
  5824. self.__frozen = false;
  5825. self.isNative = true;
  5826. self.__scrollTop = self.el.scrollTop;
  5827. self.__scrollLeft = self.el.scrollLeft;
  5828. self.__clientHeight = self.__content.clientHeight;
  5829. self.__clientWidth = self.__content.clientWidth;
  5830. self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);
  5831. self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);
  5832. if(options.startY >= 0 || options.startX >= 0) {
  5833. ionic.requestAnimationFrame(function() {
  5834. self.__originalContainerHeight = self.el.getBoundingClientRect().height;
  5835. self.el.scrollTop = options.startY || 0;
  5836. self.el.scrollLeft = options.startX || 0;
  5837. self.__scrollTop = self.el.scrollTop;
  5838. self.__scrollLeft = self.el.scrollLeft;
  5839. });
  5840. }
  5841. self.options = {
  5842. freeze: false,
  5843. getContentWidth: function() {
  5844. return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);
  5845. },
  5846. getContentHeight: function() {
  5847. return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));
  5848. }
  5849. };
  5850. for (var key in options) {
  5851. self.options[key] = options[key];
  5852. }
  5853. /**
  5854. * Sets isScrolling to true, and automatically deactivates if not called again in 80ms.
  5855. */
  5856. self.onScroll = function() {
  5857. if (!ionic.scroll.isScrolling) {
  5858. ionic.scroll.isScrolling = true;
  5859. }
  5860. clearTimeout(self.scrollTimer);
  5861. self.scrollTimer = setTimeout(function() {
  5862. ionic.scroll.isScrolling = false;
  5863. }, 80);
  5864. };
  5865. self.freeze = function(shouldFreeze) {
  5866. self.__frozen = shouldFreeze;
  5867. };
  5868. // A more powerful freeze pop that dominates all other freeze pops
  5869. self.freezeShut = function(shouldFreezeShut) {
  5870. self.__frozenShut = shouldFreezeShut;
  5871. };
  5872. self.__initEventHandlers();
  5873. },
  5874. /** Methods not used in native scrolling */
  5875. __callback: function() { deprecated('__callback'); },
  5876. zoomTo: function() { deprecated('zoomTo'); },
  5877. zoomBy: function() { deprecated('zoomBy'); },
  5878. activatePullToRefresh: function() { deprecated('activatePullToRefresh'); },
  5879. /**
  5880. * Returns the scroll position and zooming values
  5881. *
  5882. * @return {Map} `left` and `top` scroll position and `zoom` level
  5883. */
  5884. resize: function(continueScrolling) {
  5885. var self = this;
  5886. if (!self.__container || !self.options) return;
  5887. // Update Scroller dimensions for changed content
  5888. // Add padding to bottom of content
  5889. self.setDimensions(
  5890. self.__container.clientWidth,
  5891. self.__container.clientHeight,
  5892. self.options.getContentWidth(),
  5893. self.options.getContentHeight(),
  5894. continueScrolling
  5895. );
  5896. },
  5897. /**
  5898. * Initialize the scrollview
  5899. * In native scrolling, this only means we need to gather size information
  5900. */
  5901. run: function() {
  5902. this.resize();
  5903. },
  5904. /**
  5905. * Returns the scroll position and zooming values
  5906. *
  5907. * @return {Map} `left` and `top` scroll position and `zoom` level
  5908. */
  5909. getValues: function() {
  5910. var self = this;
  5911. self.update();
  5912. return {
  5913. left: self.__scrollLeft,
  5914. top: self.__scrollTop,
  5915. zoom: 1
  5916. };
  5917. },
  5918. /**
  5919. * Updates the __scrollLeft and __scrollTop values to el's current value
  5920. */
  5921. update: function() {
  5922. var self = this;
  5923. self.__scrollLeft = self.el.scrollLeft;
  5924. self.__scrollTop = self.el.scrollTop;
  5925. },
  5926. /**
  5927. * Configures the dimensions of the client (outer) and content (inner) elements.
  5928. * Requires the available space for the outer element and the outer size of the inner element.
  5929. * All values which are falsy (null or zero etc.) are ignored and the old value is kept.
  5930. *
  5931. * @param clientWidth {Integer} Inner width of outer element
  5932. * @param clientHeight {Integer} Inner height of outer element
  5933. * @param contentWidth {Integer} Outer width of inner element
  5934. * @param contentHeight {Integer} Outer height of inner element
  5935. */
  5936. setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) {
  5937. var self = this;
  5938. if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {
  5939. // this scrollview isn't rendered, don't bother
  5940. return;
  5941. }
  5942. // Only update values which are defined
  5943. if (clientWidth === +clientWidth) {
  5944. self.__clientWidth = clientWidth;
  5945. }
  5946. if (clientHeight === +clientHeight) {
  5947. self.__clientHeight = clientHeight;
  5948. }
  5949. if (contentWidth === +contentWidth) {
  5950. self.__contentWidth = contentWidth;
  5951. }
  5952. if (contentHeight === +contentHeight) {
  5953. self.__contentHeight = contentHeight;
  5954. }
  5955. // Refresh maximums
  5956. self.__computeScrollMax();
  5957. },
  5958. /**
  5959. * Returns the maximum scroll values
  5960. *
  5961. * @return {Map} `left` and `top` maximum scroll values
  5962. */
  5963. getScrollMax: function() {
  5964. return {
  5965. left: this.__maxScrollLeft,
  5966. top: this.__maxScrollTop
  5967. };
  5968. },
  5969. /**
  5970. * Scrolls by the given amount in px.
  5971. *
  5972. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5973. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5974. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5975. */
  5976. scrollBy: function(left, top, animate) {
  5977. var self = this;
  5978. // update scroll vars before refferencing them
  5979. self.update();
  5980. var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;
  5981. var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;
  5982. self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);
  5983. },
  5984. /**
  5985. * Scrolls to the given position in px.
  5986. *
  5987. * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>
  5988. * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>
  5989. * @param animate {Boolean} Whether the scrolling should happen using an animation
  5990. */
  5991. scrollTo: function(left, top, animate) {
  5992. var self = this;
  5993. if (!animate) {
  5994. self.el.scrollTop = top;
  5995. self.el.scrollLeft = left;
  5996. self.resize();
  5997. return;
  5998. }
  5999. var oldOverflowX = self.el.style.overflowX;
  6000. var oldOverflowY = self.el.style.overflowY;
  6001. clearTimeout(self.__scrollToCleanupTimeout);
  6002. self.__scrollToCleanupTimeout = setTimeout(function() {
  6003. self.el.style.overflowX = oldOverflowX;
  6004. self.el.style.overflowY = oldOverflowY;
  6005. }, 500);
  6006. self.el.style.overflowY = 'hidden';
  6007. self.el.style.overflowX = 'hidden';
  6008. animateScroll(top, left);
  6009. function animateScroll(Y, X) {
  6010. // scroll animation loop w/ easing
  6011. // credit https://gist.github.com/dezinezync/5487119
  6012. var start = Date.now(),
  6013. duration = 250, //milliseconds
  6014. fromY = self.el.scrollTop,
  6015. fromX = self.el.scrollLeft;
  6016. if (fromY === Y && fromX === X) {
  6017. self.el.style.overflowX = oldOverflowX;
  6018. self.el.style.overflowY = oldOverflowY;
  6019. self.resize();
  6020. return; /* Prevent scrolling to the Y point if already there */
  6021. }
  6022. // decelerating to zero velocity
  6023. function easeOutCubic(t) {
  6024. return (--t) * t * t + 1;
  6025. }
  6026. // scroll loop
  6027. function animateScrollStep() {
  6028. var currentTime = Date.now(),
  6029. time = Math.min(1, ((currentTime - start) / duration)),
  6030. // where .5 would be 50% of time on a linear scale easedT gives a
  6031. // fraction based on the easing method
  6032. easedT = easeOutCubic(time);
  6033. if (fromY != Y) {
  6034. self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);
  6035. }
  6036. if (fromX != X) {
  6037. self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);
  6038. }
  6039. if (time < 1) {
  6040. ionic.requestAnimationFrame(animateScrollStep);
  6041. } else {
  6042. // done
  6043. ionic.tap.removeClonedInputs(self.__container, self);
  6044. self.el.style.overflowX = oldOverflowX;
  6045. self.el.style.overflowY = oldOverflowY;
  6046. self.resize();
  6047. }
  6048. }
  6049. // start scroll loop
  6050. ionic.requestAnimationFrame(animateScrollStep);
  6051. }
  6052. },
  6053. /*
  6054. ---------------------------------------------------------------------------
  6055. PRIVATE API
  6056. ---------------------------------------------------------------------------
  6057. */
  6058. /**
  6059. * If the scroll view isn't sized correctly on start, wait until we have at least some size
  6060. */
  6061. __waitForSize: function() {
  6062. var self = this;
  6063. clearTimeout(self.__sizerTimeout);
  6064. var sizer = function() {
  6065. self.resize(true);
  6066. };
  6067. sizer();
  6068. self.__sizerTimeout = setTimeout(sizer, 500);
  6069. },
  6070. /**
  6071. * Recomputes scroll minimum values based on client dimensions and content dimensions.
  6072. */
  6073. __computeScrollMax: function() {
  6074. var self = this;
  6075. self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);
  6076. self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);
  6077. if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {
  6078. self.__didWaitForSize = true;
  6079. self.__waitForSize();
  6080. }
  6081. },
  6082. __initEventHandlers: function() {
  6083. var self = this;
  6084. // Event Handler
  6085. var container = self.__container;
  6086. // save height when scroll view is shrunk so we don't need to reflow
  6087. var scrollViewOffsetHeight;
  6088. var lastKeyboardHeight;
  6089. /**
  6090. * Shrink the scroll view when the keyboard is up if necessary and if the
  6091. * focused input is below the bottom of the shrunk scroll view, scroll it
  6092. * into view.
  6093. */
  6094. self.scrollChildIntoView = function(e) {
  6095. var rect = container.getBoundingClientRect();
  6096. if(!self.__originalContainerHeight) {
  6097. self.__originalContainerHeight = rect.height;
  6098. }
  6099. // D
  6100. //var scrollBottomOffsetToTop = rect.bottom;
  6101. // D - A
  6102. scrollViewOffsetHeight = self.__originalContainerHeight;
  6103. //console.log('Scroll view offset height', scrollViewOffsetHeight);
  6104. //console.dir(container);
  6105. var alreadyShrunk = self.isShrunkForKeyboard;
  6106. var isModal = container.parentNode.classList.contains('modal');
  6107. var isPopover = container.parentNode.classList.contains('popover');
  6108. // 680px is when the media query for 60% modal width kicks in
  6109. var isInsetModal = isModal && window.innerWidth >= 680;
  6110. /*
  6111. * _______
  6112. * |---A---| <- top of scroll view
  6113. * | |
  6114. * |---B---| <- keyboard
  6115. * | C | <- input
  6116. * |---D---| <- initial bottom of scroll view
  6117. * |___E___| <- bottom of viewport
  6118. *
  6119. * All commented calculations relative to the top of the viewport (ie E
  6120. * is the viewport height, not 0)
  6121. */
  6122. var changedKeyboardHeight = lastKeyboardHeight && (lastKeyboardHeight !== e.detail.keyboardHeight);
  6123. if (!alreadyShrunk || changedKeyboardHeight) {
  6124. // shrink scrollview so we can actually scroll if the input is hidden
  6125. // if it isn't shrink so we can scroll to inputs under the keyboard
  6126. // inset modals won't shrink on Android on their own when the keyboard appears
  6127. if ( !isPopover && (ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal) ) {
  6128. // if there are things below the scroll view account for them and
  6129. // subtract them from the keyboard height when resizing
  6130. // E - D E D
  6131. //var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;
  6132. // 0 or D - B if D > B E - B E - D
  6133. //var keyboardOffset = e.detail.keyboardHeight - scrollBottomOffsetToBottom;
  6134. ionic.requestAnimationFrame(function(){
  6135. // D - A or B - A if D > B D - A max(0, D - B)
  6136. scrollViewOffsetHeight = Math.max(0, Math.min(self.__originalContainerHeight, self.__originalContainerHeight - (e.detail.keyboardHeight - 43)));//keyboardOffset >= 0 ? scrollViewOffsetHeight - keyboardOffset : scrollViewOffsetHeight + keyboardOffset;
  6137. //console.log('Old container height', self.__originalContainerHeight, 'New container height', scrollViewOffsetHeight, 'Keyboard height', e.detail.keyboardHeight);
  6138. container.style.height = scrollViewOffsetHeight + "px";
  6139. /*
  6140. if (ionic.Platform.isIOS()) {
  6141. // Force redraw to avoid disappearing content
  6142. var disp = container.style.display;
  6143. container.style.display = 'none';
  6144. var trick = container.offsetHeight;
  6145. container.style.display = disp;
  6146. }
  6147. */
  6148. container.classList.add('keyboard-up');
  6149. //update scroll view
  6150. self.resize();
  6151. });
  6152. }
  6153. self.isShrunkForKeyboard = true;
  6154. }
  6155. lastKeyboardHeight = e.detail.keyboardHeight;
  6156. /*
  6157. * _______
  6158. * |---A---| <- top of scroll view
  6159. * | * | <- where we want to scroll to
  6160. * |--B-D--| <- keyboard, bottom of scroll view
  6161. * | C | <- input
  6162. * | |
  6163. * |___E___| <- bottom of viewport
  6164. *
  6165. * All commented calculations relative to the top of the viewport (ie E
  6166. * is the viewport height, not 0)
  6167. */
  6168. // if the element is positioned under the keyboard scroll it into view
  6169. if (e.detail.isElementUnderKeyboard) {
  6170. ionic.requestAnimationFrame(function(){
  6171. var pos = ionic.DomUtil.getOffsetTop(e.detail.target);
  6172. setTimeout(function() {
  6173. if (ionic.Platform.isIOS()) {
  6174. ionic.tap.cloneFocusedInput(container, self);
  6175. }
  6176. // Scroll the input into view, with a 100px buffer
  6177. self.scrollTo(0, pos - (rect.top + 100), true);
  6178. self.onScroll();
  6179. }, 32);
  6180. /*
  6181. // update D if we shrunk
  6182. if (self.isShrunkForKeyboard && !alreadyShrunk) {
  6183. scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;
  6184. console.log('Scroll bottom', scrollBottomOffsetToTop);
  6185. }
  6186. // middle of the scrollview, this is where we want to scroll to
  6187. // (D - A) / 2
  6188. var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;
  6189. console.log('Midpoint', scrollMidpointOffset);
  6190. //console.log("container.offsetHeight: " + scrollViewOffsetHeight);
  6191. // middle of the input we want to scroll into view
  6192. // C
  6193. var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);
  6194. console.log('Input midpoint');
  6195. // distance from middle of input to the bottom of the scroll view
  6196. // C - D C D
  6197. var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;
  6198. console.log('Input midpoint offset', inputMidpointOffsetToScrollBottom);
  6199. //C - D + (D - A)/2 C - D (D - A)/ 2
  6200. var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;
  6201. console.log('Scroll top', scrollTop);
  6202. if ( scrollTop > 0) {
  6203. if (ionic.Platform.isIOS()) {
  6204. //just shrank scroll view, give it some breathing room before scrolling
  6205. setTimeout(function(){
  6206. ionic.tap.cloneFocusedInput(container, self);
  6207. self.scrollBy(0, scrollTop, true);
  6208. self.onScroll();
  6209. }, 32);
  6210. } else {
  6211. self.scrollBy(0, scrollTop, true);
  6212. self.onScroll();
  6213. }
  6214. }
  6215. */
  6216. });
  6217. }
  6218. // Only the first scrollView parent of the element that broadcasted this event
  6219. // (the active element that needs to be shown) should receive this event
  6220. e.stopPropagation();
  6221. };
  6222. self.resetScrollView = function() {
  6223. //return scrollview to original height once keyboard has hidden
  6224. if (self.isShrunkForKeyboard) {
  6225. self.isShrunkForKeyboard = false;
  6226. container.style.height = "";
  6227. /*
  6228. if (ionic.Platform.isIOS()) {
  6229. // Force redraw to avoid disappearing content
  6230. var disp = container.style.display;
  6231. container.style.display = 'none';
  6232. var trick = container.offsetHeight;
  6233. container.style.display = disp;
  6234. }
  6235. */
  6236. self.__originalContainerHeight = container.getBoundingClientRect().height;
  6237. if (ionic.Platform.isIOS()) {
  6238. ionic.requestAnimationFrame(function() {
  6239. container.classList.remove('keyboard-up');
  6240. });
  6241. }
  6242. }
  6243. self.resize();
  6244. };
  6245. self.handleTouchMove = function(e) {
  6246. if (self.__frozenShut) {
  6247. e.preventDefault();
  6248. e.stopPropagation();
  6249. return false;
  6250. } else if ( self.__frozen ){
  6251. e.preventDefault();
  6252. // let it propagate so other events such as drag events can happen,
  6253. // but don't let it actually scroll
  6254. return false;
  6255. }
  6256. return true;
  6257. };
  6258. container.addEventListener('scroll', self.onScroll);
  6259. //Broadcasted when keyboard is shown on some platforms.
  6260. //See js/utils/keyboard.js
  6261. container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);
  6262. container.addEventListener(ionic.EVENTS.touchstart, self.handleTouchMove);
  6263. container.addEventListener(ionic.EVENTS.touchmove, self.handleTouchMove);
  6264. // Listen on document because container may not have had the last
  6265. // keyboardActiveElement, for example after closing a modal with a focused
  6266. // input and returning to a previously resized scroll view in an ion-content.
  6267. // Since we can only resize scroll views that are currently visible, just resize
  6268. // the current scroll view when the keyboard is closed.
  6269. document.addEventListener('resetScrollView', self.resetScrollView);
  6270. },
  6271. __cleanup: function() {
  6272. var self = this;
  6273. var container = self.__container;
  6274. container.removeEventListener('scroll', self.onScroll);
  6275. container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);
  6276. container.removeEventListener(ionic.EVENTS.touchstart, self.handleTouchMove);
  6277. container.removeEventListener(ionic.EVENTS.touchmove, self.handleTouchMove);
  6278. document.removeEventListener('resetScrollView', self.resetScrollView);
  6279. ionic.tap.removeClonedInputs(container, self);
  6280. delete self.__container;
  6281. delete self.__content;
  6282. delete self.__indicatorX;
  6283. delete self.__indicatorY;
  6284. delete self.options.el;
  6285. self.resize = self.scrollTo = self.onScroll = self.resetScrollView = NOOP;
  6286. self.scrollChildIntoView = NOOP;
  6287. container = null;
  6288. }
  6289. });
  6290. })(ionic);
  6291. (function(ionic) {
  6292. 'use strict';
  6293. var ITEM_CLASS = 'item';
  6294. var ITEM_CONTENT_CLASS = 'item-content';
  6295. var ITEM_SLIDING_CLASS = 'item-sliding';
  6296. var ITEM_OPTIONS_CLASS = 'item-options';
  6297. var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';
  6298. var ITEM_REORDERING_CLASS = 'item-reordering';
  6299. var ITEM_REORDER_BTN_CLASS = 'item-reorder';
  6300. var DragOp = function() {};
  6301. DragOp.prototype = {
  6302. start: function(){},
  6303. drag: function(){},
  6304. end: function(){},
  6305. isSameItem: function() {
  6306. return false;
  6307. }
  6308. };
  6309. var SlideDrag = function(opts) {
  6310. this.dragThresholdX = opts.dragThresholdX || 10;
  6311. this.el = opts.el;
  6312. this.item = opts.item;
  6313. this.canSwipe = opts.canSwipe;
  6314. };
  6315. SlideDrag.prototype = new DragOp();
  6316. SlideDrag.prototype.start = function(e) {
  6317. var content, buttons, offsetX, buttonsWidth;
  6318. if (!this.canSwipe()) {
  6319. return;
  6320. }
  6321. if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {
  6322. content = e.target;
  6323. } else if (e.target.classList.contains(ITEM_CLASS)) {
  6324. content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);
  6325. } else {
  6326. content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);
  6327. }
  6328. // If we don't have a content area as one of our children (or ourselves), skip
  6329. if (!content) {
  6330. return;
  6331. }
  6332. // Make sure we aren't animating as we slide
  6333. content.classList.remove(ITEM_SLIDING_CLASS);
  6334. // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)
  6335. offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;
  6336. // Grab the buttons
  6337. buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);
  6338. if (!buttons) {
  6339. return;
  6340. }
  6341. buttons.classList.remove('invisible');
  6342. buttonsWidth = buttons.offsetWidth;
  6343. this._currentDrag = {
  6344. buttons: buttons,
  6345. buttonsWidth: buttonsWidth,
  6346. content: content,
  6347. startOffsetX: offsetX
  6348. };
  6349. };
  6350. /**
  6351. * Check if this is the same item that was previously dragged.
  6352. */
  6353. SlideDrag.prototype.isSameItem = function(op) {
  6354. if (op._lastDrag && this._currentDrag) {
  6355. return this._currentDrag.content == op._lastDrag.content;
  6356. }
  6357. return false;
  6358. };
  6359. SlideDrag.prototype.clean = function(isInstant) {
  6360. var lastDrag = this._lastDrag;
  6361. if (!lastDrag || !lastDrag.content) return;
  6362. lastDrag.content.style[ionic.CSS.TRANSITION] = '';
  6363. lastDrag.content.style[ionic.CSS.TRANSFORM] = '';
  6364. if (isInstant) {
  6365. lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';
  6366. makeInvisible();
  6367. ionic.requestAnimationFrame(function() {
  6368. lastDrag.content.style[ionic.CSS.TRANSITION] = '';
  6369. });
  6370. } else {
  6371. ionic.requestAnimationFrame(function() {
  6372. setTimeout(makeInvisible, 250);
  6373. });
  6374. }
  6375. function makeInvisible() {
  6376. lastDrag.buttons && lastDrag.buttons.classList.add('invisible');
  6377. }
  6378. };
  6379. SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
  6380. var buttonsWidth;
  6381. // We really aren't dragging
  6382. if (!this._currentDrag) {
  6383. return;
  6384. }
  6385. // Check if we should start dragging. Check if we've dragged past the threshold,
  6386. // or we are starting from the open state.
  6387. if (!this._isDragging &&
  6388. ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||
  6389. (Math.abs(this._currentDrag.startOffsetX) > 0))) {
  6390. this._isDragging = true;
  6391. }
  6392. if (this._isDragging) {
  6393. buttonsWidth = this._currentDrag.buttonsWidth;
  6394. // Grab the new X point, capping it at zero
  6395. var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);
  6396. // If the new X position is past the buttons, we need to slow down the drag (rubber band style)
  6397. if (newX < -buttonsWidth) {
  6398. // Calculate the new X position, capped at the top of the buttons
  6399. newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));
  6400. }
  6401. this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;
  6402. this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';
  6403. this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';
  6404. }
  6405. });
  6406. SlideDrag.prototype.end = function(e, doneCallback) {
  6407. var self = this;
  6408. // There is no drag, just end immediately
  6409. if (!self._currentDrag) {
  6410. doneCallback && doneCallback();
  6411. return;
  6412. }
  6413. // If we are currently dragging, we want to snap back into place
  6414. // The final resting point X will be the width of the exposed buttons
  6415. var restingPoint = -self._currentDrag.buttonsWidth;
  6416. // Check if the drag didn't clear the buttons mid-point
  6417. // and we aren't moving fast enough to swipe open
  6418. if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) {
  6419. // If we are going left but too slow, or going right, go back to resting
  6420. if (e.gesture.direction == "left" && Math.abs(e.gesture.velocityX) < 0.3) {
  6421. restingPoint = 0;
  6422. } else if (e.gesture.direction == "right") {
  6423. restingPoint = 0;
  6424. }
  6425. }
  6426. ionic.requestAnimationFrame(function() {
  6427. if (restingPoint === 0) {
  6428. self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';
  6429. var buttons = self._currentDrag.buttons;
  6430. setTimeout(function() {
  6431. buttons && buttons.classList.add('invisible');
  6432. }, 250);
  6433. } else {
  6434. self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';
  6435. }
  6436. self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';
  6437. // Kill the current drag
  6438. if (!self._lastDrag) {
  6439. self._lastDrag = {};
  6440. }
  6441. ionic.extend(self._lastDrag, self._currentDrag);
  6442. if (self._currentDrag) {
  6443. self._currentDrag.buttons = null;
  6444. self._currentDrag.content = null;
  6445. }
  6446. self._currentDrag = null;
  6447. // We are done, notify caller
  6448. doneCallback && doneCallback();
  6449. });
  6450. };
  6451. var ReorderDrag = function(opts) {
  6452. var self = this;
  6453. self.dragThresholdY = opts.dragThresholdY || 0;
  6454. self.onReorder = opts.onReorder;
  6455. self.listEl = opts.listEl;
  6456. self.el = self.item = opts.el;
  6457. self.scrollEl = opts.scrollEl;
  6458. self.scrollView = opts.scrollView;
  6459. // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html
  6460. self.listElTrueTop = 0;
  6461. if (self.listEl.offsetParent) {
  6462. var obj = self.listEl;
  6463. do {
  6464. self.listElTrueTop += obj.offsetTop;
  6465. obj = obj.offsetParent;
  6466. } while (obj);
  6467. }
  6468. };
  6469. ReorderDrag.prototype = new DragOp();
  6470. ReorderDrag.prototype._moveElement = function(e) {
  6471. var y = e.gesture.center.pageY +
  6472. this.scrollView.getValues().top -
  6473. (this._currentDrag.elementHeight / 2) -
  6474. this.listElTrueTop;
  6475. this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)';
  6476. };
  6477. ReorderDrag.prototype.deregister = function() {
  6478. this.listEl = this.el = this.scrollEl = this.scrollView = null;
  6479. };
  6480. ReorderDrag.prototype.start = function(e) {
  6481. var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());
  6482. var elementHeight = this.el.scrollHeight;
  6483. var placeholder = this.el.cloneNode(true);
  6484. placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);
  6485. this.el.parentNode.insertBefore(placeholder, this.el);
  6486. this.el.classList.add(ITEM_REORDERING_CLASS);
  6487. this._currentDrag = {
  6488. elementHeight: elementHeight,
  6489. startIndex: startIndex,
  6490. placeholder: placeholder,
  6491. scrollHeight: scroll,
  6492. list: placeholder.parentNode
  6493. };
  6494. this._moveElement(e);
  6495. };
  6496. ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {
  6497. // We really aren't dragging
  6498. var self = this;
  6499. if (!this._currentDrag) {
  6500. return;
  6501. }
  6502. var scrollY = 0;
  6503. var pageY = e.gesture.center.pageY;
  6504. var offset = this.listElTrueTop;
  6505. //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary
  6506. if (this.scrollView) {
  6507. var container = this.scrollView.__container;
  6508. scrollY = this.scrollView.getValues().top;
  6509. var containerTop = container.offsetTop;
  6510. var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2;
  6511. var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight;
  6512. if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) {
  6513. this.scrollView.scrollBy(null, -pixelsPastTop);
  6514. //Trigger another drag so the scrolling keeps going
  6515. ionic.requestAnimationFrame(function() {
  6516. self.drag(e);
  6517. });
  6518. }
  6519. if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) {
  6520. if (scrollY < this.scrollView.getScrollMax().top) {
  6521. this.scrollView.scrollBy(null, pixelsPastBottom);
  6522. //Trigger another drag so the scrolling keeps going
  6523. ionic.requestAnimationFrame(function() {
  6524. self.drag(e);
  6525. });
  6526. }
  6527. }
  6528. }
  6529. // Check if we should start dragging. Check if we've dragged past the threshold,
  6530. // or we are starting from the open state.
  6531. if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) {
  6532. this._isDragging = true;
  6533. }
  6534. if (this._isDragging) {
  6535. this._moveElement(e);
  6536. this._currentDrag.currentY = scrollY + pageY - offset;
  6537. // this._reorderItems();
  6538. }
  6539. });
  6540. // When an item is dragged, we need to reorder any items for sorting purposes
  6541. ReorderDrag.prototype._getReorderIndex = function() {
  6542. var self = this;
  6543. var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children)
  6544. .filter(function(el) {
  6545. return el.nodeName === self.el.nodeName && el !== self.el;
  6546. });
  6547. var dragOffsetTop = self._currentDrag.currentY;
  6548. var el;
  6549. for (var i = 0, len = siblings.length; i < len; i++) {
  6550. el = siblings[i];
  6551. if (i === len - 1) {
  6552. if (dragOffsetTop > el.offsetTop) {
  6553. return i;
  6554. }
  6555. } else if (i === 0) {
  6556. if (dragOffsetTop < el.offsetTop + el.offsetHeight) {
  6557. return i;
  6558. }
  6559. } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 &&
  6560. dragOffsetTop < el.offsetTop + el.offsetHeight) {
  6561. return i;
  6562. }
  6563. }
  6564. return self._currentDrag.startIndex;
  6565. };
  6566. ReorderDrag.prototype.end = function(e, doneCallback) {
  6567. if (!this._currentDrag) {
  6568. doneCallback && doneCallback();
  6569. return;
  6570. }
  6571. var placeholder = this._currentDrag.placeholder;
  6572. var finalIndex = this._getReorderIndex();
  6573. // Reposition the element
  6574. this.el.classList.remove(ITEM_REORDERING_CLASS);
  6575. this.el.style[ionic.CSS.TRANSFORM] = '';
  6576. placeholder.parentNode.insertBefore(this.el, placeholder);
  6577. placeholder.parentNode.removeChild(placeholder);
  6578. this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex);
  6579. this._currentDrag = {
  6580. placeholder: null,
  6581. content: null
  6582. };
  6583. this._currentDrag = null;
  6584. doneCallback && doneCallback();
  6585. };
  6586. /**
  6587. * The ListView handles a list of items. It will process drag animations, edit mode,
  6588. * and other operations that are common on mobile lists or table views.
  6589. */
  6590. ionic.views.ListView = ionic.views.View.inherit({
  6591. initialize: function(opts) {
  6592. var self = this;
  6593. opts = ionic.extend({
  6594. onReorder: function() {},
  6595. virtualRemoveThreshold: -200,
  6596. virtualAddThreshold: 200,
  6597. canSwipe: function() {
  6598. return true;
  6599. }
  6600. }, opts);
  6601. ionic.extend(self, opts);
  6602. if (!self.itemHeight && self.listEl) {
  6603. self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10);
  6604. }
  6605. self.onRefresh = opts.onRefresh || function() {};
  6606. self.onRefreshOpening = opts.onRefreshOpening || function() {};
  6607. self.onRefreshHolding = opts.onRefreshHolding || function() {};
  6608. var gestureOpts = {};
  6609. // don't prevent native scrolling
  6610. if (ionic.DomUtil.getParentOrSelfWithClass(self.el, 'overflow-scroll')) {
  6611. gestureOpts.prevent_default_directions = ['left', 'right'];
  6612. }
  6613. window.ionic.onGesture('release', function(e) {
  6614. self._handleEndDrag(e);
  6615. }, self.el, gestureOpts);
  6616. window.ionic.onGesture('drag', function(e) {
  6617. self._handleDrag(e);
  6618. }, self.el, gestureOpts);
  6619. // Start the drag states
  6620. self._initDrag();
  6621. },
  6622. /**
  6623. * Be sure to cleanup references.
  6624. */
  6625. deregister: function() {
  6626. this.el = this.listEl = this.scrollEl = this.scrollView = null;
  6627. // ensure no scrolls have been left frozen
  6628. if (this.isScrollFreeze) {
  6629. self.scrollView.freeze(false);
  6630. }
  6631. },
  6632. /**
  6633. * Called to tell the list to stop refreshing. This is useful
  6634. * if you are refreshing the list and are done with refreshing.
  6635. */
  6636. stopRefreshing: function() {
  6637. var refresher = this.el.querySelector('.list-refresher');
  6638. refresher.style.height = '0';
  6639. },
  6640. /**
  6641. * If we scrolled and have virtual mode enabled, compute the window
  6642. * of active elements in order to figure out the viewport to render.
  6643. */
  6644. didScroll: function(e) {
  6645. var self = this;
  6646. if (self.isVirtual) {
  6647. var itemHeight = self.itemHeight;
  6648. // Grab the total height of the list
  6649. var scrollHeight = e.target.scrollHeight;
  6650. // Get the viewport height
  6651. var viewportHeight = self.el.parentNode.offsetHeight;
  6652. // High water is the pixel position of the first element to include (everything before
  6653. // that will be removed)
  6654. var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold);
  6655. // Low water is the pixel position of the last element to include (everything after
  6656. // that will be removed)
  6657. var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold);
  6658. // Get the first and last elements in the list based on how many can fit
  6659. // between the pixel range of lowWater and highWater
  6660. var first = parseInt(Math.abs(highWater / itemHeight), 10);
  6661. var last = parseInt(Math.abs(lowWater / itemHeight), 10);
  6662. // Get the items we need to remove
  6663. self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first);
  6664. self.renderViewport && self.renderViewport(highWater, lowWater, first, last);
  6665. }
  6666. },
  6667. didStopScrolling: function() {
  6668. if (this.isVirtual) {
  6669. for (var i = 0; i < this._virtualItemsToRemove.length; i++) {
  6670. //el.parentNode.removeChild(el);
  6671. this.didHideItem && this.didHideItem(i);
  6672. }
  6673. // Once scrolling stops, check if we need to remove old items
  6674. }
  6675. },
  6676. /**
  6677. * Clear any active drag effects on the list.
  6678. */
  6679. clearDragEffects: function(isInstant) {
  6680. if (this._lastDragOp) {
  6681. this._lastDragOp.clean && this._lastDragOp.clean(isInstant);
  6682. this._lastDragOp.deregister && this._lastDragOp.deregister();
  6683. this._lastDragOp = null;
  6684. }
  6685. },
  6686. _initDrag: function() {
  6687. // Store the last one
  6688. if (this._lastDragOp) {
  6689. this._lastDragOp.deregister && this._lastDragOp.deregister();
  6690. }
  6691. this._lastDragOp = this._dragOp;
  6692. this._dragOp = null;
  6693. },
  6694. // Return the list item from the given target
  6695. _getItem: function(target) {
  6696. while (target) {
  6697. if (target.classList && target.classList.contains(ITEM_CLASS)) {
  6698. return target;
  6699. }
  6700. target = target.parentNode;
  6701. }
  6702. return null;
  6703. },
  6704. _startDrag: function(e) {
  6705. var self = this;
  6706. self._isDragging = false;
  6707. var lastDragOp = self._lastDragOp;
  6708. var item;
  6709. // If we have an open SlideDrag and we're scrolling the list. Clear it.
  6710. if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) {
  6711. lastDragOp.clean && lastDragOp.clean();
  6712. }
  6713. // Check if this is a reorder drag
  6714. if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {
  6715. item = self._getItem(e.target);
  6716. if (item) {
  6717. self._dragOp = new ReorderDrag({
  6718. listEl: self.el,
  6719. el: item,
  6720. scrollEl: self.scrollEl,
  6721. scrollView: self.scrollView,
  6722. onReorder: function(el, start, end) {
  6723. self.onReorder && self.onReorder(el, start, end);
  6724. }
  6725. });
  6726. self._dragOp.start(e);
  6727. e.preventDefault();
  6728. }
  6729. }
  6730. // Or check if this is a swipe to the side drag
  6731. else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {
  6732. // Make sure this is an item with buttons
  6733. item = self._getItem(e.target);
  6734. if (item && item.querySelector('.item-options')) {
  6735. self._dragOp = new SlideDrag({
  6736. el: self.el,
  6737. item: item,
  6738. canSwipe: self.canSwipe
  6739. });
  6740. self._dragOp.start(e);
  6741. e.preventDefault();
  6742. self.isScrollFreeze = self.scrollView.freeze(true);
  6743. }
  6744. }
  6745. // If we had a last drag operation and this is a new one on a different item, clean that last one
  6746. if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) {
  6747. lastDragOp.clean && lastDragOp.clean();
  6748. }
  6749. },
  6750. _handleEndDrag: function(e) {
  6751. var self = this;
  6752. if (self.scrollView) {
  6753. self.isScrollFreeze = self.scrollView.freeze(false);
  6754. }
  6755. self._didDragUpOrDown = false;
  6756. if (!self._dragOp) {
  6757. return;
  6758. }
  6759. self._dragOp.end(e, function() {
  6760. self._initDrag();
  6761. });
  6762. },
  6763. /**
  6764. * Process the drag event to move the item to the left or right.
  6765. */
  6766. _handleDrag: function(e) {
  6767. var self = this;
  6768. if (Math.abs(e.gesture.deltaY) > 5) {
  6769. self._didDragUpOrDown = true;
  6770. }
  6771. // If we get a drag event, make sure we aren't in another drag, then check if we should
  6772. // start one
  6773. if (!self.isDragging && !self._dragOp) {
  6774. self._startDrag(e);
  6775. }
  6776. // No drag still, pass it up
  6777. if (!self._dragOp) {
  6778. return;
  6779. }
  6780. e.gesture.srcEvent.preventDefault();
  6781. self._dragOp.drag(e);
  6782. }
  6783. });
  6784. })(ionic);
  6785. (function(ionic) {
  6786. 'use strict';
  6787. ionic.views.Modal = ionic.views.View.inherit({
  6788. initialize: function(opts) {
  6789. opts = ionic.extend({
  6790. focusFirstInput: false,
  6791. unfocusOnHide: true,
  6792. focusFirstDelay: 600,
  6793. backdropClickToClose: true,
  6794. hardwareBackButtonClose: true,
  6795. }, opts);
  6796. ionic.extend(this, opts);
  6797. this.el = opts.el;
  6798. },
  6799. show: function() {
  6800. var self = this;
  6801. if(self.focusFirstInput) {
  6802. // Let any animations run first
  6803. window.setTimeout(function() {
  6804. var input = self.el.querySelector('input, textarea');
  6805. input && input.focus && input.focus();
  6806. }, self.focusFirstDelay);
  6807. }
  6808. },
  6809. hide: function() {
  6810. // Unfocus all elements
  6811. if(this.unfocusOnHide) {
  6812. var inputs = this.el.querySelectorAll('input, textarea');
  6813. // Let any animations run first
  6814. window.setTimeout(function() {
  6815. for(var i = 0; i < inputs.length; i++) {
  6816. inputs[i].blur && inputs[i].blur();
  6817. }
  6818. });
  6819. }
  6820. }
  6821. });
  6822. })(ionic);
  6823. (function(ionic) {
  6824. 'use strict';
  6825. /**
  6826. * The side menu view handles one of the side menu's in a Side Menu Controller
  6827. * configuration.
  6828. * It takes a DOM reference to that side menu element.
  6829. */
  6830. ionic.views.SideMenu = ionic.views.View.inherit({
  6831. initialize: function(opts) {
  6832. this.el = opts.el;
  6833. this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled;
  6834. this.setWidth(opts.width);
  6835. },
  6836. getFullWidth: function() {
  6837. return this.width;
  6838. },
  6839. setWidth: function(width) {
  6840. this.width = width;
  6841. this.el.style.width = width + 'px';
  6842. },
  6843. setIsEnabled: function(isEnabled) {
  6844. this.isEnabled = isEnabled;
  6845. },
  6846. bringUp: function() {
  6847. if(this.el.style.zIndex !== '0') {
  6848. this.el.style.zIndex = '0';
  6849. }
  6850. },
  6851. pushDown: function() {
  6852. if(this.el.style.zIndex !== '-1') {
  6853. this.el.style.zIndex = '-1';
  6854. }
  6855. }
  6856. });
  6857. ionic.views.SideMenuContent = ionic.views.View.inherit({
  6858. initialize: function(opts) {
  6859. ionic.extend(this, {
  6860. animationClass: 'menu-animated',
  6861. onDrag: function() {},
  6862. onEndDrag: function() {}
  6863. }, opts);
  6864. ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);
  6865. ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);
  6866. },
  6867. _onDrag: function(e) {
  6868. this.onDrag && this.onDrag(e);
  6869. },
  6870. _onEndDrag: function(e) {
  6871. this.onEndDrag && this.onEndDrag(e);
  6872. },
  6873. disableAnimation: function() {
  6874. this.el.classList.remove(this.animationClass);
  6875. },
  6876. enableAnimation: function() {
  6877. this.el.classList.add(this.animationClass);
  6878. },
  6879. getTranslateX: function() {
  6880. return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]);
  6881. },
  6882. setTranslateX: ionic.animationFrameThrottle(function(x) {
  6883. this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)';
  6884. })
  6885. });
  6886. })(ionic);
  6887. /*
  6888. * Adapted from Swipe.js 2.0
  6889. *
  6890. * Brad Birdsall
  6891. * Copyright 2013, MIT License
  6892. *
  6893. */
  6894. (function(ionic) {
  6895. 'use strict';
  6896. ionic.views.Slider = ionic.views.View.inherit({
  6897. initialize: function (options) {
  6898. var slider = this;
  6899. var touchStartEvent, touchMoveEvent, touchEndEvent;
  6900. if (window.navigator.pointerEnabled) {
  6901. touchStartEvent = 'pointerdown';
  6902. touchMoveEvent = 'pointermove';
  6903. touchEndEvent = 'pointerup';
  6904. } else if (window.navigator.msPointerEnabled) {
  6905. touchStartEvent = 'MSPointerDown';
  6906. touchMoveEvent = 'MSPointerMove';
  6907. touchEndEvent = 'MSPointerUp';
  6908. } else {
  6909. touchStartEvent = 'touchstart';
  6910. touchMoveEvent = 'touchmove';
  6911. touchEndEvent = 'touchend';
  6912. }
  6913. var mouseStartEvent = 'mousedown';
  6914. var mouseMoveEvent = 'mousemove';
  6915. var mouseEndEvent = 'mouseup';
  6916. // utilities
  6917. var noop = function() {}; // simple no operation function
  6918. var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution
  6919. // check browser capabilities
  6920. var browser = {
  6921. addEventListener: !!window.addEventListener,
  6922. transitions: (function(temp) {
  6923. var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
  6924. for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
  6925. return false;
  6926. })(document.createElement('swipe'))
  6927. };
  6928. var container = options.el;
  6929. // quit if no root element
  6930. if (!container) return;
  6931. var element = container.children[0];
  6932. var slides, slidePos, width, length;
  6933. options = options || {};
  6934. var index = parseInt(options.startSlide, 10) || 0;
  6935. var speed = options.speed || 300;
  6936. options.continuous = options.continuous !== undefined ? options.continuous : true;
  6937. function setup() {
  6938. // do not setup if the container has no width
  6939. if (!container.offsetWidth) {
  6940. return;
  6941. }
  6942. // cache slides
  6943. slides = element.children;
  6944. length = slides.length;
  6945. // set continuous to false if only one slide
  6946. if (slides.length < 2) options.continuous = false;
  6947. //special case if two slides
  6948. if (browser.transitions && options.continuous && slides.length < 3) {
  6949. element.appendChild(slides[0].cloneNode(true));
  6950. element.appendChild(element.children[1].cloneNode(true));
  6951. slides = element.children;
  6952. }
  6953. // create an array to store current positions of each slide
  6954. slidePos = new Array(slides.length);
  6955. // determine width of each slide
  6956. width = container.offsetWidth || container.getBoundingClientRect().width;
  6957. element.style.width = (slides.length * width) + 'px';
  6958. // stack elements
  6959. var pos = slides.length;
  6960. while(pos--) {
  6961. var slide = slides[pos];
  6962. slide.style.width = width + 'px';
  6963. slide.setAttribute('data-index', pos);
  6964. if (browser.transitions) {
  6965. slide.style.left = (pos * -width) + 'px';
  6966. move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
  6967. }
  6968. }
  6969. // reposition elements before and after index
  6970. if (options.continuous && browser.transitions) {
  6971. move(circle(index - 1), -width, 0);
  6972. move(circle(index + 1), width, 0);
  6973. }
  6974. if (!browser.transitions) element.style.left = (index * -width) + 'px';
  6975. container.style.visibility = 'visible';
  6976. options.slidesChanged && options.slidesChanged();
  6977. }
  6978. function prev(slideSpeed) {
  6979. if (options.continuous) slide(index - 1, slideSpeed);
  6980. else if (index) slide(index - 1, slideSpeed);
  6981. }
  6982. function next(slideSpeed) {
  6983. if (options.continuous) slide(index + 1, slideSpeed);
  6984. else if (index < slides.length - 1) slide(index + 1, slideSpeed);
  6985. }
  6986. function circle(index) {
  6987. // a simple positive modulo using slides.length
  6988. return (slides.length + (index % slides.length)) % slides.length;
  6989. }
  6990. function slide(to, slideSpeed) {
  6991. // do nothing if already on requested slide
  6992. if (index == to) return;
  6993. if (!slides) {
  6994. index = to;
  6995. return;
  6996. }
  6997. if (browser.transitions) {
  6998. var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
  6999. // get the actual position of the slide
  7000. if (options.continuous) {
  7001. var naturalDirection = direction;
  7002. direction = -slidePos[circle(to)] / width;
  7003. // if going forward but to < index, use to = slides.length + to
  7004. // if going backward but to > index, use to = -slides.length + to
  7005. if (direction !== naturalDirection) to = -direction * slides.length + to;
  7006. }
  7007. var diff = Math.abs(index - to) - 1;
  7008. // move all the slides between index and to in the right direction
  7009. while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);
  7010. to = circle(to);
  7011. move(index, width * direction, slideSpeed || speed);
  7012. move(to, 0, slideSpeed || speed);
  7013. if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
  7014. } else {
  7015. to = circle(to);
  7016. animate(index * -width, to * -width, slideSpeed || speed);
  7017. //no fallback for a circular continuous if the browser does not accept transitions
  7018. }
  7019. index = to;
  7020. offloadFn(options.callback && options.callback(index, slides[index]));
  7021. }
  7022. function move(index, dist, speed) {
  7023. translate(index, dist, speed);
  7024. slidePos[index] = dist;
  7025. }
  7026. function translate(index, dist, speed) {
  7027. var slide = slides[index];
  7028. var style = slide && slide.style;
  7029. if (!style) return;
  7030. style.webkitTransitionDuration =
  7031. style.MozTransitionDuration =
  7032. style.msTransitionDuration =
  7033. style.OTransitionDuration =
  7034. style.transitionDuration = speed + 'ms';
  7035. style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
  7036. style.msTransform =
  7037. style.MozTransform =
  7038. style.OTransform = 'translateX(' + dist + 'px)';
  7039. }
  7040. function animate(from, to, speed) {
  7041. // if not an animation, just reposition
  7042. if (!speed) {
  7043. element.style.left = to + 'px';
  7044. return;
  7045. }
  7046. var start = +new Date();
  7047. var timer = setInterval(function() {
  7048. var timeElap = +new Date() - start;
  7049. if (timeElap > speed) {
  7050. element.style.left = to + 'px';
  7051. if (delay) begin();
  7052. options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
  7053. clearInterval(timer);
  7054. return;
  7055. }
  7056. element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';
  7057. }, 4);
  7058. }
  7059. // setup auto slideshow
  7060. var delay = options.auto || 0;
  7061. var interval;
  7062. function begin() {
  7063. interval = setTimeout(next, delay);
  7064. }
  7065. function stop() {
  7066. delay = options.auto || 0;
  7067. clearTimeout(interval);
  7068. }
  7069. // setup initial vars
  7070. var start = {};
  7071. var delta = {};
  7072. var isScrolling;
  7073. // setup event capturing
  7074. var events = {
  7075. handleEvent: function(event) {
  7076. if(!event.touches && event.pageX && event.pageY) {
  7077. event.touches = [{
  7078. pageX: event.pageX,
  7079. pageY: event.pageY
  7080. }];
  7081. }
  7082. switch (event.type) {
  7083. case touchStartEvent: this.start(event); break;
  7084. case mouseStartEvent: this.start(event); break;
  7085. case touchMoveEvent: this.touchmove(event); break;
  7086. case mouseMoveEvent: this.touchmove(event); break;
  7087. case touchEndEvent: offloadFn(this.end(event)); break;
  7088. case mouseEndEvent: offloadFn(this.end(event)); break;
  7089. case 'webkitTransitionEnd':
  7090. case 'msTransitionEnd':
  7091. case 'oTransitionEnd':
  7092. case 'otransitionend':
  7093. case 'transitionend': offloadFn(this.transitionEnd(event)); break;
  7094. case 'resize': offloadFn(setup); break;
  7095. }
  7096. if (options.stopPropagation) event.stopPropagation();
  7097. },
  7098. start: function(event) {
  7099. // prevent to start if there is no valid event
  7100. if (!event.touches) {
  7101. return;
  7102. }
  7103. var touches = event.touches[0];
  7104. // measure start values
  7105. start = {
  7106. // get initial touch coords
  7107. x: touches.pageX,
  7108. y: touches.pageY,
  7109. // store time to determine touch duration
  7110. time: +new Date()
  7111. };
  7112. // used for testing first move event
  7113. isScrolling = undefined;
  7114. // reset delta and end measurements
  7115. delta = {};
  7116. // attach touchmove and touchend listeners
  7117. element.addEventListener(touchMoveEvent, this, false);
  7118. element.addEventListener(mouseMoveEvent, this, false);
  7119. element.addEventListener(touchEndEvent, this, false);
  7120. element.addEventListener(mouseEndEvent, this, false);
  7121. document.addEventListener(touchEndEvent, this, false);
  7122. document.addEventListener(mouseEndEvent, this, false);
  7123. },
  7124. touchmove: function(event) {
  7125. // ensure there is a valid event
  7126. // ensure swiping with one touch and not pinching
  7127. // ensure sliding is enabled
  7128. if (!event.touches ||
  7129. event.touches.length > 1 ||
  7130. event.scale && event.scale !== 1 ||
  7131. slider.slideIsDisabled) {
  7132. return;
  7133. }
  7134. if (options.disableScroll) event.preventDefault();
  7135. var touches = event.touches[0];
  7136. // measure change in x and y
  7137. delta = {
  7138. x: touches.pageX - start.x,
  7139. y: touches.pageY - start.y
  7140. };
  7141. // determine if scrolling test has run - one time test
  7142. if ( typeof isScrolling == 'undefined') {
  7143. isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
  7144. }
  7145. // if user is not trying to scroll vertically
  7146. if (!isScrolling) {
  7147. // prevent native scrolling
  7148. event.preventDefault();
  7149. // stop slideshow
  7150. stop();
  7151. // increase resistance if first or last slide
  7152. if (options.continuous) { // we don't add resistance at the end
  7153. translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
  7154. translate(index, delta.x + slidePos[index], 0);
  7155. translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
  7156. } else {
  7157. // If the slider bounces, do the bounce!
  7158. if(options.bouncing) {
  7159. delta.x =
  7160. delta.x /
  7161. ( (!index && delta.x > 0 || // if first slide and sliding left
  7162. index == slides.length - 1 && // or if last slide and sliding right
  7163. delta.x < 0 // and if sliding at all
  7164. ) ?
  7165. ( Math.abs(delta.x) / width + 1 ) // determine resistance level
  7166. : 1 ); // no resistance if false
  7167. } else {
  7168. if(width * index - delta.x < 0) { //We are trying scroll past left boundary
  7169. delta.x = Math.min(delta.x, width * index); //Set delta.x so we don't go past left screen
  7170. }
  7171. if(Math.abs(delta.x) > width * (slides.length - index - 1)){ //We are trying to scroll past right bondary
  7172. delta.x = Math.max( -width * (slides.length - index - 1), delta.x); //Set delta.x so we don't go past right screen
  7173. }
  7174. }
  7175. // translate 1:1
  7176. translate(index - 1, delta.x + slidePos[index - 1], 0);
  7177. translate(index, delta.x + slidePos[index], 0);
  7178. translate(index + 1, delta.x + slidePos[index + 1], 0);
  7179. }
  7180. options.onDrag && options.onDrag();
  7181. }
  7182. },
  7183. end: function() {
  7184. // measure duration
  7185. var duration = +new Date() - start.time;
  7186. // determine if slide attempt triggers next/prev slide
  7187. var isValidSlide =
  7188. Number(duration) < 250 && // if slide duration is less than 250ms
  7189. Math.abs(delta.x) > 20 || // and if slide amt is greater than 20px
  7190. Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
  7191. // determine if slide attempt is past start and end
  7192. var isPastBounds = (!index && delta.x > 0) || // if first slide and slide amt is greater than 0
  7193. (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0
  7194. if (options.continuous) isPastBounds = false;
  7195. // determine direction of swipe (true:right, false:left)
  7196. var direction = delta.x < 0;
  7197. // if not scrolling vertically
  7198. if (!isScrolling) {
  7199. if (isValidSlide && !isPastBounds) {
  7200. if (direction) {
  7201. if (options.continuous) { // we need to get the next in this direction in place
  7202. move(circle(index - 1), -width, 0);
  7203. move(circle(index + 2), width, 0);
  7204. } else {
  7205. move(index - 1, -width, 0);
  7206. }
  7207. move(index, slidePos[index] - width, speed);
  7208. move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
  7209. index = circle(index + 1);
  7210. } else {
  7211. if (options.continuous) { // we need to get the next in this direction in place
  7212. move(circle(index + 1), width, 0);
  7213. move(circle(index - 2), -width, 0);
  7214. } else {
  7215. move(index + 1, width, 0);
  7216. }
  7217. move(index, slidePos[index] + width, speed);
  7218. move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
  7219. index = circle(index - 1);
  7220. }
  7221. options.callback && options.callback(index, slides[index]);
  7222. } else {
  7223. if (options.continuous) {
  7224. move(circle(index - 1), -width, speed);
  7225. move(index, 0, speed);
  7226. move(circle(index + 1), width, speed);
  7227. } else {
  7228. move(index - 1, -width, speed);
  7229. move(index, 0, speed);
  7230. move(index + 1, width, speed);
  7231. }
  7232. }
  7233. }
  7234. // kill touchmove and touchend event listeners until touchstart called again
  7235. element.removeEventListener(touchMoveEvent, events, false);
  7236. element.removeEventListener(mouseMoveEvent, events, false);
  7237. element.removeEventListener(touchEndEvent, events, false);
  7238. element.removeEventListener(mouseEndEvent, events, false);
  7239. document.removeEventListener(touchEndEvent, events, false);
  7240. document.removeEventListener(mouseEndEvent, events, false);
  7241. options.onDragEnd && options.onDragEnd();
  7242. },
  7243. transitionEnd: function(event) {
  7244. if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
  7245. if (delay) begin();
  7246. options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
  7247. }
  7248. }
  7249. };
  7250. // Public API
  7251. this.update = function() {
  7252. setTimeout(setup);
  7253. };
  7254. this.setup = function() {
  7255. setup();
  7256. };
  7257. this.loop = function(value) {
  7258. if (arguments.length) options.continuous = !!value;
  7259. return options.continuous;
  7260. };
  7261. this.enableSlide = function(shouldEnable) {
  7262. if (arguments.length) {
  7263. this.slideIsDisabled = !shouldEnable;
  7264. }
  7265. return !this.slideIsDisabled;
  7266. };
  7267. this.slide = this.select = function(to, speed) {
  7268. // cancel slideshow
  7269. stop();
  7270. slide(to, speed);
  7271. };
  7272. this.prev = this.previous = function() {
  7273. // cancel slideshow
  7274. stop();
  7275. prev();
  7276. };
  7277. this.next = function() {
  7278. // cancel slideshow
  7279. stop();
  7280. next();
  7281. };
  7282. this.stop = function() {
  7283. // cancel slideshow
  7284. stop();
  7285. };
  7286. this.start = function() {
  7287. begin();
  7288. };
  7289. this.autoPlay = function(newDelay) {
  7290. if (!delay || delay < 0) {
  7291. stop();
  7292. } else {
  7293. delay = newDelay;
  7294. begin();
  7295. }
  7296. };
  7297. this.currentIndex = this.selected = function() {
  7298. // return current index position
  7299. return index;
  7300. };
  7301. this.slidesCount = this.count = function() {
  7302. // return total number of slides
  7303. return length;
  7304. };
  7305. this.kill = function() {
  7306. // cancel slideshow
  7307. stop();
  7308. // reset element
  7309. element.style.width = '';
  7310. element.style.left = '';
  7311. // reset slides so no refs are held on to
  7312. slides && (slides = []);
  7313. // removed event listeners
  7314. if (browser.addEventListener) {
  7315. // remove current event listeners
  7316. element.removeEventListener(touchStartEvent, events, false);
  7317. element.removeEventListener(mouseStartEvent, events, false);
  7318. element.removeEventListener('webkitTransitionEnd', events, false);
  7319. element.removeEventListener('msTransitionEnd', events, false);
  7320. element.removeEventListener('oTransitionEnd', events, false);
  7321. element.removeEventListener('otransitionend', events, false);
  7322. element.removeEventListener('transitionend', events, false);
  7323. window.removeEventListener('resize', events, false);
  7324. }
  7325. else {
  7326. window.onresize = null;
  7327. }
  7328. };
  7329. this.load = function() {
  7330. // trigger setup
  7331. setup();
  7332. // start auto slideshow if applicable
  7333. if (delay) begin();
  7334. // add event listeners
  7335. if (browser.addEventListener) {
  7336. // set touchstart event on element
  7337. element.addEventListener(touchStartEvent, events, false);
  7338. element.addEventListener(mouseStartEvent, events, false);
  7339. if (browser.transitions) {
  7340. element.addEventListener('webkitTransitionEnd', events, false);
  7341. element.addEventListener('msTransitionEnd', events, false);
  7342. element.addEventListener('oTransitionEnd', events, false);
  7343. element.addEventListener('otransitionend', events, false);
  7344. element.addEventListener('transitionend', events, false);
  7345. }
  7346. // set resize event on window
  7347. window.addEventListener('resize', events, false);
  7348. } else {
  7349. window.onresize = function () { setup(); }; // to play nice with old IE
  7350. }
  7351. };
  7352. }
  7353. });
  7354. })(ionic);
  7355. /*eslint space-after-keywords: 0*/
  7356. /**
  7357. * Swiper 3.2.7
  7358. * Most modern mobile touch slider and framework with hardware accelerated transitions
  7359. *
  7360. * http://www.idangero.us/swiper/
  7361. *
  7362. * Copyright 2015, Vladimir Kharlampidi
  7363. * The iDangero.us
  7364. * http://www.idangero.us/
  7365. *
  7366. * Licensed under MIT
  7367. *
  7368. * Released on: December 7, 2015
  7369. */
  7370. (function () {
  7371. 'use strict';
  7372. var $;
  7373. /*===========================
  7374. Swiper
  7375. ===========================*/
  7376. var Swiper = function (container, params, _scope, $compile) {
  7377. if (!(this instanceof Swiper)) return new Swiper(container, params);
  7378. var defaults = {
  7379. direction: 'horizontal',
  7380. touchEventsTarget: 'container',
  7381. initialSlide: 0,
  7382. speed: 300,
  7383. // autoplay
  7384. autoplay: false,
  7385. autoplayDisableOnInteraction: true,
  7386. // To support iOS's swipe-to-go-back gesture (when being used in-app, with UIWebView).
  7387. iOSEdgeSwipeDetection: false,
  7388. iOSEdgeSwipeThreshold: 20,
  7389. // Free mode
  7390. freeMode: false,
  7391. freeModeMomentum: true,
  7392. freeModeMomentumRatio: 1,
  7393. freeModeMomentumBounce: true,
  7394. freeModeMomentumBounceRatio: 1,
  7395. freeModeSticky: false,
  7396. freeModeMinimumVelocity: 0.02,
  7397. // Autoheight
  7398. autoHeight: false,
  7399. // Set wrapper width
  7400. setWrapperSize: false,
  7401. // Virtual Translate
  7402. virtualTranslate: false,
  7403. // Effects
  7404. effect: 'slide', // 'slide' or 'fade' or 'cube' or 'coverflow'
  7405. coverflow: {
  7406. rotate: 50,
  7407. stretch: 0,
  7408. depth: 100,
  7409. modifier: 1,
  7410. slideShadows : true
  7411. },
  7412. cube: {
  7413. slideShadows: true,
  7414. shadow: true,
  7415. shadowOffset: 20,
  7416. shadowScale: 0.94
  7417. },
  7418. fade: {
  7419. crossFade: false
  7420. },
  7421. // Parallax
  7422. parallax: false,
  7423. // Scrollbar
  7424. scrollbar: null,
  7425. scrollbarHide: true,
  7426. scrollbarDraggable: false,
  7427. scrollbarSnapOnRelease: false,
  7428. // Keyboard Mousewheel
  7429. keyboardControl: false,
  7430. mousewheelControl: false,
  7431. mousewheelReleaseOnEdges: false,
  7432. mousewheelInvert: false,
  7433. mousewheelForceToAxis: false,
  7434. mousewheelSensitivity: 1,
  7435. // Hash Navigation
  7436. hashnav: false,
  7437. // Breakpoints
  7438. breakpoints: undefined,
  7439. // Slides grid
  7440. spaceBetween: 0,
  7441. slidesPerView: 1,
  7442. slidesPerColumn: 1,
  7443. slidesPerColumnFill: 'column',
  7444. slidesPerGroup: 1,
  7445. centeredSlides: false,
  7446. slidesOffsetBefore: 0, // in px
  7447. slidesOffsetAfter: 0, // in px
  7448. // Round length
  7449. roundLengths: false,
  7450. // Touches
  7451. touchRatio: 1,
  7452. touchAngle: 45,
  7453. simulateTouch: true,
  7454. shortSwipes: true,
  7455. longSwipes: true,
  7456. longSwipesRatio: 0.5,
  7457. longSwipesMs: 300,
  7458. followFinger: true,
  7459. onlyExternal: false,
  7460. threshold: 0,
  7461. touchMoveStopPropagation: true,
  7462. // Pagination
  7463. pagination: null,
  7464. paginationElement: 'span',
  7465. paginationClickable: false,
  7466. paginationHide: false,
  7467. paginationBulletRender: null,
  7468. // Resistance
  7469. resistance: true,
  7470. resistanceRatio: 0.85,
  7471. // Next/prev buttons
  7472. nextButton: null,
  7473. prevButton: null,
  7474. // Progress
  7475. watchSlidesProgress: false,
  7476. watchSlidesVisibility: false,
  7477. // Cursor
  7478. grabCursor: false,
  7479. // Clicks
  7480. preventClicks: true,
  7481. preventClicksPropagation: true,
  7482. slideToClickedSlide: false,
  7483. // Lazy Loading
  7484. lazyLoading: false,
  7485. lazyLoadingInPrevNext: false,
  7486. lazyLoadingOnTransitionStart: false,
  7487. // Images
  7488. preloadImages: true,
  7489. updateOnImagesReady: true,
  7490. // loop
  7491. loop: false,
  7492. loopAdditionalSlides: 0,
  7493. loopedSlides: null,
  7494. // Control
  7495. control: undefined,
  7496. controlInverse: false,
  7497. controlBy: 'slide', //or 'container'
  7498. // Swiping/no swiping
  7499. allowSwipeToPrev: true,
  7500. allowSwipeToNext: true,
  7501. swipeHandler: null, //'.swipe-handler',
  7502. noSwiping: true,
  7503. noSwipingClass: 'swiper-no-swiping',
  7504. // NS
  7505. slideClass: 'swiper-slide',
  7506. slideActiveClass: 'swiper-slide-active',
  7507. slideVisibleClass: 'swiper-slide-visible',
  7508. slideDuplicateClass: 'swiper-slide-duplicate',
  7509. slideNextClass: 'swiper-slide-next',
  7510. slidePrevClass: 'swiper-slide-prev',
  7511. wrapperClass: 'swiper-wrapper',
  7512. bulletClass: 'swiper-pagination-bullet',
  7513. bulletActiveClass: 'swiper-pagination-bullet-active',
  7514. buttonDisabledClass: 'swiper-button-disabled',
  7515. paginationHiddenClass: 'swiper-pagination-hidden',
  7516. // Observer
  7517. observer: false,
  7518. observeParents: false,
  7519. // Accessibility
  7520. a11y: false,
  7521. prevSlideMessage: 'Previous slide',
  7522. nextSlideMessage: 'Next slide',
  7523. firstSlideMessage: 'This is the first slide',
  7524. lastSlideMessage: 'This is the last slide',
  7525. paginationBulletMessage: 'Go to slide {{index}}',
  7526. // Callbacks
  7527. runCallbacksOnInit: true
  7528. /*
  7529. Callbacks:
  7530. onInit: function (swiper)
  7531. onDestroy: function (swiper)
  7532. onClick: function (swiper, e)
  7533. onTap: function (swiper, e)
  7534. onDoubleTap: function (swiper, e)
  7535. onSliderMove: function (swiper, e)
  7536. onSlideChangeStart: function (swiper)
  7537. onSlideChangeEnd: function (swiper)
  7538. onTransitionStart: function (swiper)
  7539. onTransitionEnd: function (swiper)
  7540. onImagesReady: function (swiper)
  7541. onProgress: function (swiper, progress)
  7542. onTouchStart: function (swiper, e)
  7543. onTouchMove: function (swiper, e)
  7544. onTouchMoveOpposite: function (swiper, e)
  7545. onTouchEnd: function (swiper, e)
  7546. onReachBeginning: function (swiper)
  7547. onReachEnd: function (swiper)
  7548. onSetTransition: function (swiper, duration)
  7549. onSetTranslate: function (swiper, translate)
  7550. onAutoplayStart: function (swiper)
  7551. onAutoplayStop: function (swiper),
  7552. onLazyImageLoad: function (swiper, slide, image)
  7553. onLazyImageReady: function (swiper, slide, image)
  7554. */
  7555. };
  7556. var initialVirtualTranslate = params && params.virtualTranslate;
  7557. params = params || {};
  7558. var originalParams = {};
  7559. for (var param in params) {
  7560. 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))) {
  7561. originalParams[param] = {};
  7562. for (var deepParam in params[param]) {
  7563. originalParams[param][deepParam] = params[param][deepParam];
  7564. }
  7565. }
  7566. else {
  7567. originalParams[param] = params[param];
  7568. }
  7569. }
  7570. for (var def in defaults) {
  7571. if (typeof params[def] === 'undefined') {
  7572. params[def] = defaults[def];
  7573. }
  7574. else if (typeof params[def] === 'object') {
  7575. for (var deepDef in defaults[def]) {
  7576. if (typeof params[def][deepDef] === 'undefined') {
  7577. params[def][deepDef] = defaults[def][deepDef];
  7578. }
  7579. }
  7580. }
  7581. }
  7582. // Swiper
  7583. var s = this;
  7584. // Params
  7585. s.params = params;
  7586. s.originalParams = originalParams;
  7587. // Classname
  7588. s.classNames = [];
  7589. /*=========================
  7590. Dom Library and plugins
  7591. ===========================*/
  7592. if (typeof $ !== 'undefined' && typeof Dom7 !== 'undefined'){
  7593. $ = Dom7;
  7594. }
  7595. if (typeof $ === 'undefined') {
  7596. if (typeof Dom7 === 'undefined') {
  7597. $ = window.Dom7 || window.Zepto || window.jQuery;
  7598. }
  7599. else {
  7600. $ = Dom7;
  7601. }
  7602. if (!$) return;
  7603. }
  7604. // Export it to Swiper instance
  7605. s.$ = $;
  7606. /*=========================
  7607. Breakpoints
  7608. ===========================*/
  7609. s.currentBreakpoint = undefined;
  7610. s.getActiveBreakpoint = function () {
  7611. //Get breakpoint for window width
  7612. if (!s.params.breakpoints) return false;
  7613. var breakpoint = false;
  7614. var points = [], point;
  7615. for ( point in s.params.breakpoints ) {
  7616. if (s.params.breakpoints.hasOwnProperty(point)) {
  7617. points.push(point);
  7618. }
  7619. }
  7620. points.sort(function (a, b) {
  7621. return parseInt(a, 10) > parseInt(b, 10);
  7622. });
  7623. for (var i = 0; i < points.length; i++) {
  7624. point = points[i];
  7625. if (point >= window.innerWidth && !breakpoint) {
  7626. breakpoint = point;
  7627. }
  7628. }
  7629. return breakpoint || 'max';
  7630. };
  7631. s.setBreakpoint = function () {
  7632. //Set breakpoint for window width and update parameters
  7633. var breakpoint = s.getActiveBreakpoint();
  7634. if (breakpoint && s.currentBreakpoint !== breakpoint) {
  7635. var breakPointsParams = breakpoint in s.params.breakpoints ? s.params.breakpoints[breakpoint] : s.originalParams;
  7636. for ( var param in breakPointsParams ) {
  7637. s.params[param] = breakPointsParams[param];
  7638. }
  7639. s.currentBreakpoint = breakpoint;
  7640. }
  7641. };
  7642. // Set breakpoint on load
  7643. if (s.params.breakpoints) {
  7644. s.setBreakpoint();
  7645. }
  7646. /*=========================
  7647. Preparation - Define Container, Wrapper and Pagination
  7648. ===========================*/
  7649. s.container = $(container);
  7650. if (s.container.length === 0) return;
  7651. if (s.container.length > 1) {
  7652. s.container.each(function () {
  7653. new Swiper(this, params);
  7654. });
  7655. return;
  7656. }
  7657. // Save instance in container HTML Element and in data
  7658. s.container[0].swiper = s;
  7659. s.container.data('swiper', s);
  7660. s.classNames.push('swiper-container-' + s.params.direction);
  7661. if (s.params.freeMode) {
  7662. s.classNames.push('swiper-container-free-mode');
  7663. }
  7664. if (!s.support.flexbox) {
  7665. s.classNames.push('swiper-container-no-flexbox');
  7666. s.params.slidesPerColumn = 1;
  7667. }
  7668. if (s.params.autoHeight) {
  7669. s.classNames.push('swiper-container-autoheight');
  7670. }
  7671. // Enable slides progress when required
  7672. if (s.params.parallax || s.params.watchSlidesVisibility) {
  7673. s.params.watchSlidesProgress = true;
  7674. }
  7675. // Coverflow / 3D
  7676. if (['cube', 'coverflow'].indexOf(s.params.effect) >= 0) {
  7677. if (s.support.transforms3d) {
  7678. s.params.watchSlidesProgress = true;
  7679. s.classNames.push('swiper-container-3d');
  7680. }
  7681. else {
  7682. s.params.effect = 'slide';
  7683. }
  7684. }
  7685. if (s.params.effect !== 'slide') {
  7686. s.classNames.push('swiper-container-' + s.params.effect);
  7687. }
  7688. if (s.params.effect === 'cube') {
  7689. s.params.resistanceRatio = 0;
  7690. s.params.slidesPerView = 1;
  7691. s.params.slidesPerColumn = 1;
  7692. s.params.slidesPerGroup = 1;
  7693. s.params.centeredSlides = false;
  7694. s.params.spaceBetween = 0;
  7695. s.params.virtualTranslate = true;
  7696. s.params.setWrapperSize = false;
  7697. }
  7698. if (s.params.effect === 'fade') {
  7699. s.params.slidesPerView = 1;
  7700. s.params.slidesPerColumn = 1;
  7701. s.params.slidesPerGroup = 1;
  7702. s.params.watchSlidesProgress = true;
  7703. s.params.spaceBetween = 0;
  7704. if (typeof initialVirtualTranslate === 'undefined') {
  7705. s.params.virtualTranslate = true;
  7706. }
  7707. }
  7708. // Grab Cursor
  7709. if (s.params.grabCursor && s.support.touch) {
  7710. s.params.grabCursor = false;
  7711. }
  7712. // Wrapper
  7713. s.wrapper = s.container.children('.' + s.params.wrapperClass);
  7714. // Pagination
  7715. if (s.params.pagination) {
  7716. s.paginationContainer = $(s.params.pagination);
  7717. if (s.params.paginationClickable) {
  7718. s.paginationContainer.addClass('swiper-pagination-clickable');
  7719. }
  7720. }
  7721. // Is Horizontal
  7722. function isH() {
  7723. return s.params.direction === 'horizontal';
  7724. }
  7725. // RTL
  7726. s.rtl = isH() && (s.container[0].dir.toLowerCase() === 'rtl' || s.container.css('direction') === 'rtl');
  7727. if (s.rtl) {
  7728. s.classNames.push('swiper-container-rtl');
  7729. }
  7730. // Wrong RTL support
  7731. if (s.rtl) {
  7732. s.wrongRTL = s.wrapper.css('display') === '-webkit-box';
  7733. }
  7734. // Columns
  7735. if (s.params.slidesPerColumn > 1) {
  7736. s.classNames.push('swiper-container-multirow');
  7737. }
  7738. // Check for Android
  7739. if (s.device.android) {
  7740. s.classNames.push('swiper-container-android');
  7741. }
  7742. // Add classes
  7743. s.container.addClass(s.classNames.join(' '));
  7744. // Translate
  7745. s.translate = 0;
  7746. // Progress
  7747. s.progress = 0;
  7748. // Velocity
  7749. s.velocity = 0;
  7750. /*=========================
  7751. Locks, unlocks
  7752. ===========================*/
  7753. s.lockSwipeToNext = function () {
  7754. s.params.allowSwipeToNext = false;
  7755. };
  7756. s.lockSwipeToPrev = function () {
  7757. s.params.allowSwipeToPrev = false;
  7758. };
  7759. s.lockSwipes = function () {
  7760. s.params.allowSwipeToNext = s.params.allowSwipeToPrev = false;
  7761. };
  7762. s.unlockSwipeToNext = function () {
  7763. s.params.allowSwipeToNext = true;
  7764. };
  7765. s.unlockSwipeToPrev = function () {
  7766. s.params.allowSwipeToPrev = true;
  7767. };
  7768. s.unlockSwipes = function () {
  7769. s.params.allowSwipeToNext = s.params.allowSwipeToPrev = true;
  7770. };
  7771. /*=========================
  7772. Round helper
  7773. ===========================*/
  7774. function round(a) {
  7775. return Math.floor(a);
  7776. }
  7777. /*=========================
  7778. Set grab cursor
  7779. ===========================*/
  7780. if (s.params.grabCursor) {
  7781. s.container[0].style.cursor = 'move';
  7782. s.container[0].style.cursor = '-webkit-grab';
  7783. s.container[0].style.cursor = '-moz-grab';
  7784. s.container[0].style.cursor = 'grab';
  7785. }
  7786. /*=========================
  7787. Update on Images Ready
  7788. ===========================*/
  7789. s.imagesToLoad = [];
  7790. s.imagesLoaded = 0;
  7791. s.loadImage = function (imgElement, src, srcset, checkForComplete, callback) {
  7792. var image;
  7793. function onReady () {
  7794. if (callback) callback();
  7795. }
  7796. if (!imgElement.complete || !checkForComplete) {
  7797. if (src) {
  7798. image = new window.Image();
  7799. image.onload = onReady;
  7800. image.onerror = onReady;
  7801. if (srcset) {
  7802. image.srcset = srcset;
  7803. }
  7804. if (src) {
  7805. image.src = src;
  7806. }
  7807. } else {
  7808. onReady();
  7809. }
  7810. } else {//image already loaded...
  7811. onReady();
  7812. }
  7813. };
  7814. s.preloadImages = function () {
  7815. s.imagesToLoad = s.container.find('img');
  7816. function _onReady() {
  7817. if (typeof s === 'undefined' || s === null) return;
  7818. if (s.imagesLoaded !== undefined) s.imagesLoaded++;
  7819. if (s.imagesLoaded === s.imagesToLoad.length) {
  7820. if (s.params.updateOnImagesReady) s.update();
  7821. s.emit('onImagesReady', s);
  7822. }
  7823. }
  7824. for (var i = 0; i < s.imagesToLoad.length; i++) {
  7825. 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);
  7826. }
  7827. };
  7828. /*=========================
  7829. Autoplay
  7830. ===========================*/
  7831. s.autoplayTimeoutId = undefined;
  7832. s.autoplaying = false;
  7833. s.autoplayPaused = false;
  7834. function autoplay() {
  7835. s.autoplayTimeoutId = setTimeout(function () {
  7836. if (s.params.loop) {
  7837. s.fixLoop();
  7838. s._slideNext();
  7839. }
  7840. else {
  7841. if (!s.isEnd) {
  7842. s._slideNext();
  7843. }
  7844. else {
  7845. if (!params.autoplayStopOnLast) {
  7846. s._slideTo(0);
  7847. }
  7848. else {
  7849. s.stopAutoplay();
  7850. }
  7851. }
  7852. }
  7853. }, s.params.autoplay);
  7854. }
  7855. s.startAutoplay = function () {
  7856. if (typeof s.autoplayTimeoutId !== 'undefined') return false;
  7857. if (!s.params.autoplay) return false;
  7858. if (s.autoplaying) return false;
  7859. s.autoplaying = true;
  7860. s.emit('onAutoplayStart', s);
  7861. autoplay();
  7862. };
  7863. s.stopAutoplay = function (internal) {
  7864. if (!s.autoplayTimeoutId) return;
  7865. if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId);
  7866. s.autoplaying = false;
  7867. s.autoplayTimeoutId = undefined;
  7868. s.emit('onAutoplayStop', s);
  7869. };
  7870. s.pauseAutoplay = function (speed) {
  7871. if (s.autoplayPaused) return;
  7872. if (s.autoplayTimeoutId) clearTimeout(s.autoplayTimeoutId);
  7873. s.autoplayPaused = true;
  7874. if (speed === 0) {
  7875. s.autoplayPaused = false;
  7876. autoplay();
  7877. }
  7878. else {
  7879. s.wrapper.transitionEnd(function () {
  7880. if (!s) return;
  7881. s.autoplayPaused = false;
  7882. if (!s.autoplaying) {
  7883. s.stopAutoplay();
  7884. }
  7885. else {
  7886. autoplay();
  7887. }
  7888. });
  7889. }
  7890. };
  7891. /*=========================
  7892. Min/Max Translate
  7893. ===========================*/
  7894. s.minTranslate = function () {
  7895. return (-s.snapGrid[0]);
  7896. };
  7897. s.maxTranslate = function () {
  7898. return (-s.snapGrid[s.snapGrid.length - 1]);
  7899. };
  7900. /*=========================
  7901. Slider/slides sizes
  7902. ===========================*/
  7903. s.updateAutoHeight = function () {
  7904. // Update Height
  7905. var newHeight = s.slides.eq(s.activeIndex)[0].offsetHeight;
  7906. if (newHeight) s.wrapper.css('height', s.slides.eq(s.activeIndex)[0].offsetHeight + 'px');
  7907. };
  7908. s.updateContainerSize = function () {
  7909. var width, height;
  7910. if (typeof s.params.width !== 'undefined') {
  7911. width = s.params.width;
  7912. }
  7913. else {
  7914. width = s.container[0].clientWidth;
  7915. }
  7916. if (typeof s.params.height !== 'undefined') {
  7917. height = s.params.height;
  7918. }
  7919. else {
  7920. height = s.container[0].clientHeight;
  7921. }
  7922. if (width === 0 && isH() || height === 0 && !isH()) {
  7923. return;
  7924. }
  7925. //Subtract paddings
  7926. width = width - parseInt(s.container.css('padding-left'), 10) - parseInt(s.container.css('padding-right'), 10);
  7927. height = height - parseInt(s.container.css('padding-top'), 10) - parseInt(s.container.css('padding-bottom'), 10);
  7928. // Store values
  7929. s.width = width;
  7930. s.height = height;
  7931. s.size = isH() ? s.width : s.height;
  7932. };
  7933. s.updateSlidesSize = function () {
  7934. s.slides = s.wrapper.children('.' + s.params.slideClass);
  7935. s.snapGrid = [];
  7936. s.slidesGrid = [];
  7937. s.slidesSizesGrid = [];
  7938. var spaceBetween = s.params.spaceBetween,
  7939. slidePosition = -s.params.slidesOffsetBefore,
  7940. i,
  7941. prevSlideSize = 0,
  7942. index = 0;
  7943. if (typeof spaceBetween === 'string' && spaceBetween.indexOf('%') >= 0) {
  7944. spaceBetween = parseFloat(spaceBetween.replace('%', '')) / 100 * s.size;
  7945. }
  7946. s.virtualSize = -spaceBetween;
  7947. // reset margins
  7948. if (s.rtl) s.slides.css({marginLeft: '', marginTop: ''});
  7949. else s.slides.css({marginRight: '', marginBottom: ''});
  7950. var slidesNumberEvenToRows;
  7951. if (s.params.slidesPerColumn > 1) {
  7952. if (Math.floor(s.slides.length / s.params.slidesPerColumn) === s.slides.length / s.params.slidesPerColumn) {
  7953. slidesNumberEvenToRows = s.slides.length;
  7954. }
  7955. else {
  7956. slidesNumberEvenToRows = Math.ceil(s.slides.length / s.params.slidesPerColumn) * s.params.slidesPerColumn;
  7957. }
  7958. if (s.params.slidesPerView !== 'auto' && s.params.slidesPerColumnFill === 'row') {
  7959. slidesNumberEvenToRows = Math.max(slidesNumberEvenToRows, s.params.slidesPerView * s.params.slidesPerColumn);
  7960. }
  7961. }
  7962. // Calc slides
  7963. var slideSize;
  7964. var slidesPerColumn = s.params.slidesPerColumn;
  7965. var slidesPerRow = slidesNumberEvenToRows / slidesPerColumn;
  7966. var numFullColumns = slidesPerRow - (s.params.slidesPerColumn * slidesPerRow - s.slides.length);
  7967. for (i = 0; i < s.slides.length; i++) {
  7968. slideSize = 0;
  7969. var slide = s.slides.eq(i);
  7970. if (s.params.slidesPerColumn > 1) {
  7971. // Set slides order
  7972. var newSlideOrderIndex;
  7973. var column, row;
  7974. if (s.params.slidesPerColumnFill === 'column') {
  7975. column = Math.floor(i / slidesPerColumn);
  7976. row = i - column * slidesPerColumn;
  7977. if (column > numFullColumns || (column === numFullColumns && row === slidesPerColumn-1)) {
  7978. if (++row >= slidesPerColumn) {
  7979. row = 0;
  7980. column++;
  7981. }
  7982. }
  7983. newSlideOrderIndex = column + row * slidesNumberEvenToRows / slidesPerColumn;
  7984. slide
  7985. .css({
  7986. '-webkit-box-ordinal-group': newSlideOrderIndex,
  7987. '-moz-box-ordinal-group': newSlideOrderIndex,
  7988. '-ms-flex-order': newSlideOrderIndex,
  7989. '-webkit-order': newSlideOrderIndex,
  7990. 'order': newSlideOrderIndex
  7991. });
  7992. }
  7993. else {
  7994. row = Math.floor(i / slidesPerRow);
  7995. column = i - row * slidesPerRow;
  7996. }
  7997. slide
  7998. .css({
  7999. 'margin-top': (row !== 0 && s.params.spaceBetween) && (s.params.spaceBetween + 'px')
  8000. })
  8001. .attr('data-swiper-column', column)
  8002. .attr('data-swiper-row', row);
  8003. }
  8004. if (slide.css('display') === 'none') continue;
  8005. if (s.params.slidesPerView === 'auto') {
  8006. slideSize = isH() ? slide.outerWidth(true) : slide.outerHeight(true);
  8007. if (s.params.roundLengths) slideSize = round(slideSize);
  8008. }
  8009. else {
  8010. slideSize = (s.size - (s.params.slidesPerView - 1) * spaceBetween) / s.params.slidesPerView;
  8011. if (s.params.roundLengths) slideSize = round(slideSize);
  8012. if (isH()) {
  8013. s.slides[i].style.width = slideSize + 'px';
  8014. }
  8015. else {
  8016. s.slides[i].style.height = slideSize + 'px';
  8017. }
  8018. }
  8019. s.slides[i].swiperSlideSize = slideSize;
  8020. s.slidesSizesGrid.push(slideSize);
  8021. if (s.params.centeredSlides) {
  8022. slidePosition = slidePosition + slideSize / 2 + prevSlideSize / 2 + spaceBetween;
  8023. if (i === 0) slidePosition = slidePosition - s.size / 2 - spaceBetween;
  8024. if (Math.abs(slidePosition) < 1 / 1000) slidePosition = 0;
  8025. if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition);
  8026. s.slidesGrid.push(slidePosition);
  8027. }
  8028. else {
  8029. if ((index) % s.params.slidesPerGroup === 0) s.snapGrid.push(slidePosition);
  8030. s.slidesGrid.push(slidePosition);
  8031. slidePosition = slidePosition + slideSize + spaceBetween;
  8032. }
  8033. s.virtualSize += slideSize + spaceBetween;
  8034. prevSlideSize = slideSize;
  8035. index ++;
  8036. }
  8037. s.virtualSize = Math.max(s.virtualSize, s.size) + s.params.slidesOffsetAfter;
  8038. var newSlidesGrid;
  8039. if (
  8040. s.rtl && s.wrongRTL && (s.params.effect === 'slide' || s.params.effect === 'coverflow')) {
  8041. s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8042. }
  8043. if (!s.support.flexbox || s.params.setWrapperSize) {
  8044. if (isH()) s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8045. else s.wrapper.css({height: s.virtualSize + s.params.spaceBetween + 'px'});
  8046. }
  8047. if (s.params.slidesPerColumn > 1) {
  8048. s.virtualSize = (slideSize + s.params.spaceBetween) * slidesNumberEvenToRows;
  8049. s.virtualSize = Math.ceil(s.virtualSize / s.params.slidesPerColumn) - s.params.spaceBetween;
  8050. s.wrapper.css({width: s.virtualSize + s.params.spaceBetween + 'px'});
  8051. if (s.params.centeredSlides) {
  8052. newSlidesGrid = [];
  8053. for (i = 0; i < s.snapGrid.length; i++) {
  8054. if (s.snapGrid[i] < s.virtualSize + s.snapGrid[0]) newSlidesGrid.push(s.snapGrid[i]);
  8055. }
  8056. s.snapGrid = newSlidesGrid;
  8057. }
  8058. }
  8059. // Remove last grid elements depending on width
  8060. if (!s.params.centeredSlides) {
  8061. newSlidesGrid = [];
  8062. for (i = 0; i < s.snapGrid.length; i++) {
  8063. if (s.snapGrid[i] <= s.virtualSize - s.size) {
  8064. newSlidesGrid.push(s.snapGrid[i]);
  8065. }
  8066. }
  8067. s.snapGrid = newSlidesGrid;
  8068. if (Math.floor(s.virtualSize - s.size) > Math.floor(s.snapGrid[s.snapGrid.length - 1])) {
  8069. s.snapGrid.push(s.virtualSize - s.size);
  8070. }
  8071. }
  8072. if (s.snapGrid.length === 0) s.snapGrid = [0];
  8073. if (s.params.spaceBetween !== 0) {
  8074. if (isH()) {
  8075. if (s.rtl) s.slides.css({marginLeft: spaceBetween + 'px'});
  8076. else s.slides.css({marginRight: spaceBetween + 'px'});
  8077. }
  8078. else s.slides.css({marginBottom: spaceBetween + 'px'});
  8079. }
  8080. if (s.params.watchSlidesProgress) {
  8081. s.updateSlidesOffset();
  8082. }
  8083. };
  8084. s.updateSlidesOffset = function () {
  8085. for (var i = 0; i < s.slides.length; i++) {
  8086. s.slides[i].swiperSlideOffset = isH() ? s.slides[i].offsetLeft : s.slides[i].offsetTop;
  8087. }
  8088. };
  8089. /*=========================
  8090. Slider/slides progress
  8091. ===========================*/
  8092. s.updateSlidesProgress = function (translate) {
  8093. if (typeof translate === 'undefined') {
  8094. translate = s.translate || 0;
  8095. }
  8096. if (s.slides.length === 0) return;
  8097. if (typeof s.slides[0].swiperSlideOffset === 'undefined') s.updateSlidesOffset();
  8098. var offsetCenter = -translate;
  8099. if (s.rtl) offsetCenter = translate;
  8100. // Visible Slides
  8101. s.slides.removeClass(s.params.slideVisibleClass);
  8102. for (var i = 0; i < s.slides.length; i++) {
  8103. var slide = s.slides[i];
  8104. var slideProgress = (offsetCenter - slide.swiperSlideOffset) / (slide.swiperSlideSize + s.params.spaceBetween);
  8105. if (s.params.watchSlidesVisibility) {
  8106. var slideBefore = -(offsetCenter - slide.swiperSlideOffset);
  8107. var slideAfter = slideBefore + s.slidesSizesGrid[i];
  8108. var isVisible =
  8109. (slideBefore >= 0 && slideBefore < s.size) ||
  8110. (slideAfter > 0 && slideAfter <= s.size) ||
  8111. (slideBefore <= 0 && slideAfter >= s.size);
  8112. if (isVisible) {
  8113. s.slides.eq(i).addClass(s.params.slideVisibleClass);
  8114. }
  8115. }
  8116. slide.progress = s.rtl ? -slideProgress : slideProgress;
  8117. }
  8118. };
  8119. s.updateProgress = function (translate) {
  8120. if (typeof translate === 'undefined') {
  8121. translate = s.translate || 0;
  8122. }
  8123. var translatesDiff = s.maxTranslate() - s.minTranslate();
  8124. var wasBeginning = s.isBeginning;
  8125. var wasEnd = s.isEnd;
  8126. if (translatesDiff === 0) {
  8127. s.progress = 0;
  8128. s.isBeginning = s.isEnd = true;
  8129. }
  8130. else {
  8131. s.progress = (translate - s.minTranslate()) / (translatesDiff);
  8132. s.isBeginning = s.progress <= 0;
  8133. s.isEnd = s.progress >= 1;
  8134. }
  8135. if (s.isBeginning && !wasBeginning) s.emit('onReachBeginning', s);
  8136. if (s.isEnd && !wasEnd) s.emit('onReachEnd', s);
  8137. if (s.params.watchSlidesProgress) s.updateSlidesProgress(translate);
  8138. s.emit('onProgress', s, s.progress);
  8139. };
  8140. s.updateActiveIndex = function () {
  8141. var translate = s.rtl ? s.translate : -s.translate;
  8142. var newActiveIndex, i, snapIndex;
  8143. for (i = 0; i < s.slidesGrid.length; i ++) {
  8144. if (typeof s.slidesGrid[i + 1] !== 'undefined') {
  8145. if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1] - (s.slidesGrid[i + 1] - s.slidesGrid[i]) / 2) {
  8146. newActiveIndex = i;
  8147. }
  8148. else if (translate >= s.slidesGrid[i] && translate < s.slidesGrid[i + 1]) {
  8149. newActiveIndex = i + 1;
  8150. }
  8151. }
  8152. else {
  8153. if (translate >= s.slidesGrid[i]) {
  8154. newActiveIndex = i;
  8155. }
  8156. }
  8157. }
  8158. // Normalize slideIndex
  8159. if (newActiveIndex < 0 || typeof newActiveIndex === 'undefined') newActiveIndex = 0;
  8160. // for (i = 0; i < s.slidesGrid.length; i++) {
  8161. // if (- translate >= s.slidesGrid[i]) {
  8162. // newActiveIndex = i;
  8163. // }
  8164. // }
  8165. snapIndex = Math.floor(newActiveIndex / s.params.slidesPerGroup);
  8166. if (snapIndex >= s.snapGrid.length) snapIndex = s.snapGrid.length - 1;
  8167. if (newActiveIndex === s.activeIndex) {
  8168. return;
  8169. }
  8170. s.snapIndex = snapIndex;
  8171. s.previousIndex = s.activeIndex;
  8172. s.activeIndex = newActiveIndex;
  8173. s.updateClasses();
  8174. };
  8175. /*=========================
  8176. Classes
  8177. ===========================*/
  8178. s.updateClasses = function () {
  8179. s.slides.removeClass(s.params.slideActiveClass + ' ' + s.params.slideNextClass + ' ' + s.params.slidePrevClass);
  8180. var activeSlide = s.slides.eq(s.activeIndex);
  8181. // Active classes
  8182. activeSlide.addClass(s.params.slideActiveClass);
  8183. activeSlide.next('.' + s.params.slideClass).addClass(s.params.slideNextClass);
  8184. activeSlide.prev('.' + s.params.slideClass).addClass(s.params.slidePrevClass);
  8185. // Pagination
  8186. if (s.bullets && s.bullets.length > 0) {
  8187. s.bullets.removeClass(s.params.bulletActiveClass);
  8188. var bulletIndex;
  8189. if (s.params.loop) {
  8190. bulletIndex = Math.ceil(s.activeIndex - s.loopedSlides)/s.params.slidesPerGroup;
  8191. if (bulletIndex > s.slides.length - 1 - s.loopedSlides * 2) {
  8192. bulletIndex = bulletIndex - (s.slides.length - s.loopedSlides * 2);
  8193. }
  8194. if (bulletIndex > s.bullets.length - 1) bulletIndex = bulletIndex - s.bullets.length;
  8195. }
  8196. else {
  8197. if (typeof s.snapIndex !== 'undefined') {
  8198. bulletIndex = s.snapIndex;
  8199. }
  8200. else {
  8201. bulletIndex = s.activeIndex || 0;
  8202. }
  8203. }
  8204. if (s.paginationContainer.length > 1) {
  8205. s.bullets.each(function () {
  8206. if ($(this).index() === bulletIndex) $(this).addClass(s.params.bulletActiveClass);
  8207. });
  8208. }
  8209. else {
  8210. s.bullets.eq(bulletIndex).addClass(s.params.bulletActiveClass);
  8211. }
  8212. }
  8213. // Next/active buttons
  8214. if (!s.params.loop) {
  8215. if (s.params.prevButton) {
  8216. if (s.isBeginning) {
  8217. $(s.params.prevButton).addClass(s.params.buttonDisabledClass);
  8218. if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.prevButton));
  8219. }
  8220. else {
  8221. $(s.params.prevButton).removeClass(s.params.buttonDisabledClass);
  8222. if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.prevButton));
  8223. }
  8224. }
  8225. if (s.params.nextButton) {
  8226. if (s.isEnd) {
  8227. $(s.params.nextButton).addClass(s.params.buttonDisabledClass);
  8228. if (s.params.a11y && s.a11y) s.a11y.disable($(s.params.nextButton));
  8229. }
  8230. else {
  8231. $(s.params.nextButton).removeClass(s.params.buttonDisabledClass);
  8232. if (s.params.a11y && s.a11y) s.a11y.enable($(s.params.nextButton));
  8233. }
  8234. }
  8235. }
  8236. };
  8237. /*=========================
  8238. Pagination
  8239. ===========================*/
  8240. s.updatePagination = function () {
  8241. if (!s.params.pagination) return;
  8242. if (s.paginationContainer && s.paginationContainer.length > 0) {
  8243. var bulletsHTML = '';
  8244. var numberOfBullets = s.params.loop ? Math.ceil((s.slides.length - s.loopedSlides * 2) / s.params.slidesPerGroup) : s.snapGrid.length;
  8245. for (var i = 0; i < numberOfBullets; i++) {
  8246. if (s.params.paginationBulletRender) {
  8247. bulletsHTML += s.params.paginationBulletRender(i, s.params.bulletClass);
  8248. }
  8249. else {
  8250. bulletsHTML += '<' + s.params.paginationElement+' class="' + s.params.bulletClass + '"></' + s.params.paginationElement + '>';
  8251. }
  8252. }
  8253. s.paginationContainer.html(bulletsHTML);
  8254. s.bullets = s.paginationContainer.find('.' + s.params.bulletClass);
  8255. if (s.params.paginationClickable && s.params.a11y && s.a11y) {
  8256. s.a11y.initPagination();
  8257. }
  8258. }
  8259. };
  8260. /*=========================
  8261. Common update method
  8262. ===========================*/
  8263. s.update = function (updateTranslate) {
  8264. s.updateContainerSize();
  8265. s.updateSlidesSize();
  8266. s.updateProgress();
  8267. s.updatePagination();
  8268. s.updateClasses();
  8269. if (s.params.scrollbar && s.scrollbar) {
  8270. s.scrollbar.set();
  8271. }
  8272. function forceSetTranslate() {
  8273. newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate());
  8274. s.setWrapperTranslate(newTranslate);
  8275. s.updateActiveIndex();
  8276. s.updateClasses();
  8277. }
  8278. if (updateTranslate) {
  8279. var translated, newTranslate;
  8280. if (s.controller && s.controller.spline) {
  8281. s.controller.spline = undefined;
  8282. }
  8283. if (s.params.freeMode) {
  8284. forceSetTranslate();
  8285. if (s.params.autoHeight) {
  8286. s.updateAutoHeight();
  8287. }
  8288. }
  8289. else {
  8290. if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) {
  8291. translated = s.slideTo(s.slides.length - 1, 0, false, true);
  8292. }
  8293. else {
  8294. translated = s.slideTo(s.activeIndex, 0, false, true);
  8295. }
  8296. if (!translated) {
  8297. forceSetTranslate();
  8298. }
  8299. }
  8300. }
  8301. else if (s.params.autoHeight) {
  8302. s.updateAutoHeight();
  8303. }
  8304. };
  8305. /*=========================
  8306. Resize Handler
  8307. ===========================*/
  8308. s.onResize = function (forceUpdatePagination) {
  8309. //Breakpoints
  8310. if (s.params.breakpoints) {
  8311. s.setBreakpoint();
  8312. }
  8313. // Disable locks on resize
  8314. var allowSwipeToPrev = s.params.allowSwipeToPrev;
  8315. var allowSwipeToNext = s.params.allowSwipeToNext;
  8316. s.params.allowSwipeToPrev = s.params.allowSwipeToNext = true;
  8317. s.updateContainerSize();
  8318. s.updateSlidesSize();
  8319. if (s.params.slidesPerView === 'auto' || s.params.freeMode || forceUpdatePagination) s.updatePagination();
  8320. if (s.params.scrollbar && s.scrollbar) {
  8321. s.scrollbar.set();
  8322. }
  8323. if (s.controller && s.controller.spline) {
  8324. s.controller.spline = undefined;
  8325. }
  8326. if (s.params.freeMode) {
  8327. var newTranslate = Math.min(Math.max(s.translate, s.maxTranslate()), s.minTranslate());
  8328. s.setWrapperTranslate(newTranslate);
  8329. s.updateActiveIndex();
  8330. s.updateClasses();
  8331. if (s.params.autoHeight) {
  8332. s.updateAutoHeight();
  8333. }
  8334. }
  8335. else {
  8336. s.updateClasses();
  8337. if ((s.params.slidesPerView === 'auto' || s.params.slidesPerView > 1) && s.isEnd && !s.params.centeredSlides) {
  8338. s.slideTo(s.slides.length - 1, 0, false, true);
  8339. }
  8340. else {
  8341. s.slideTo(s.activeIndex, 0, false, true);
  8342. }
  8343. }
  8344. // Return locks after resize
  8345. s.params.allowSwipeToPrev = allowSwipeToPrev;
  8346. s.params.allowSwipeToNext = allowSwipeToNext;
  8347. };
  8348. /*=========================
  8349. Events
  8350. ===========================*/
  8351. //Define Touch Events
  8352. var desktopEvents = ['mousedown', 'mousemove', 'mouseup'];
  8353. if (window.navigator.pointerEnabled) desktopEvents = ['pointerdown', 'pointermove', 'pointerup'];
  8354. else if (window.navigator.msPointerEnabled) desktopEvents = ['MSPointerDown', 'MSPointerMove', 'MSPointerUp'];
  8355. s.touchEvents = {
  8356. start : s.support.touch || !s.params.simulateTouch ? 'touchstart' : desktopEvents[0],
  8357. move : s.support.touch || !s.params.simulateTouch ? 'touchmove' : desktopEvents[1],
  8358. end : s.support.touch || !s.params.simulateTouch ? 'touchend' : desktopEvents[2]
  8359. };
  8360. // WP8 Touch Events Fix
  8361. if (window.navigator.pointerEnabled || window.navigator.msPointerEnabled) {
  8362. (s.params.touchEventsTarget === 'container' ? s.container : s.wrapper).addClass('swiper-wp8-' + s.params.direction);
  8363. }
  8364. // Attach/detach events
  8365. s.initEvents = function (detach) {
  8366. var actionDom = detach ? 'off' : 'on';
  8367. var action = detach ? 'removeEventListener' : 'addEventListener';
  8368. var touchEventsTarget = s.params.touchEventsTarget === 'container' ? s.container[0] : s.wrapper[0];
  8369. var target = s.support.touch ? touchEventsTarget : document;
  8370. var moveCapture = s.params.nested ? true : false;
  8371. //Touch Events
  8372. if (s.browser.ie) {
  8373. touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false);
  8374. target[action](s.touchEvents.move, s.onTouchMove, moveCapture);
  8375. target[action](s.touchEvents.end, s.onTouchEnd, false);
  8376. }
  8377. else {
  8378. if (s.support.touch) {
  8379. touchEventsTarget[action](s.touchEvents.start, s.onTouchStart, false);
  8380. touchEventsTarget[action](s.touchEvents.move, s.onTouchMove, moveCapture);
  8381. touchEventsTarget[action](s.touchEvents.end, s.onTouchEnd, false);
  8382. }
  8383. if (params.simulateTouch && !s.device.ios && !s.device.android) {
  8384. touchEventsTarget[action]('mousedown', s.onTouchStart, false);
  8385. document[action]('mousemove', s.onTouchMove, moveCapture);
  8386. document[action]('mouseup', s.onTouchEnd, false);
  8387. }
  8388. }
  8389. window[action]('resize', s.onResize);
  8390. // Next, Prev, Index
  8391. if (s.params.nextButton) {
  8392. $(s.params.nextButton)[actionDom]('click', s.onClickNext);
  8393. if (s.params.a11y && s.a11y) $(s.params.nextButton)[actionDom]('keydown', s.a11y.onEnterKey);
  8394. }
  8395. if (s.params.prevButton) {
  8396. $(s.params.prevButton)[actionDom]('click', s.onClickPrev);
  8397. if (s.params.a11y && s.a11y) $(s.params.prevButton)[actionDom]('keydown', s.a11y.onEnterKey);
  8398. }
  8399. if (s.params.pagination && s.params.paginationClickable) {
  8400. $(s.paginationContainer)[actionDom]('click', '.' + s.params.bulletClass, s.onClickIndex);
  8401. if (s.params.a11y && s.a11y) $(s.paginationContainer)[actionDom]('keydown', '.' + s.params.bulletClass, s.a11y.onEnterKey);
  8402. }
  8403. // Prevent Links Clicks
  8404. if (s.params.preventClicks || s.params.preventClicksPropagation) touchEventsTarget[action]('click', s.preventClicks, true);
  8405. };
  8406. s.attachEvents = function (detach) {
  8407. s.initEvents();
  8408. };
  8409. s.detachEvents = function () {
  8410. s.initEvents(true);
  8411. };
  8412. /*=========================
  8413. Handle Clicks
  8414. ===========================*/
  8415. // Prevent Clicks
  8416. s.allowClick = true;
  8417. s.preventClicks = function (e) {
  8418. if (!s.allowClick) {
  8419. if (s.params.preventClicks) e.preventDefault();
  8420. if (s.params.preventClicksPropagation && s.animating) {
  8421. e.stopPropagation();
  8422. e.stopImmediatePropagation();
  8423. }
  8424. }
  8425. };
  8426. // Clicks
  8427. s.onClickNext = function (e) {
  8428. e.preventDefault();
  8429. if (s.isEnd && !s.params.loop) return;
  8430. s.slideNext();
  8431. };
  8432. s.onClickPrev = function (e) {
  8433. e.preventDefault();
  8434. if (s.isBeginning && !s.params.loop) return;
  8435. s.slidePrev();
  8436. };
  8437. s.onClickIndex = function (e) {
  8438. e.preventDefault();
  8439. var index = $(this).index() * s.params.slidesPerGroup;
  8440. if (s.params.loop) index = index + s.loopedSlides;
  8441. s.slideTo(index);
  8442. };
  8443. /*=========================
  8444. Handle Touches
  8445. ===========================*/
  8446. function findElementInEvent(e, selector) {
  8447. var el = $(e.target);
  8448. if (!el.is(selector)) {
  8449. if (typeof selector === 'string') {
  8450. el = el.parents(selector);
  8451. }
  8452. else if (selector.nodeType) {
  8453. var found;
  8454. el.parents().each(function (index, _el) {
  8455. if (_el === selector) found = selector;
  8456. });
  8457. if (!found) return undefined;
  8458. else return selector;
  8459. }
  8460. }
  8461. if (el.length === 0) {
  8462. return undefined;
  8463. }
  8464. return el[0];
  8465. }
  8466. s.updateClickedSlide = function (e) {
  8467. var slide = findElementInEvent(e, '.' + s.params.slideClass);
  8468. var slideFound = false;
  8469. if (slide) {
  8470. for (var i = 0; i < s.slides.length; i++) {
  8471. if (s.slides[i] === slide) slideFound = true;
  8472. }
  8473. }
  8474. if (slide && slideFound) {
  8475. s.clickedSlide = slide;
  8476. s.clickedIndex = $(slide).index();
  8477. }
  8478. else {
  8479. s.clickedSlide = undefined;
  8480. s.clickedIndex = undefined;
  8481. return;
  8482. }
  8483. if (s.params.slideToClickedSlide && s.clickedIndex !== undefined && s.clickedIndex !== s.activeIndex) {
  8484. var slideToIndex = s.clickedIndex,
  8485. realIndex,
  8486. duplicatedSlides;
  8487. if (s.params.loop) {
  8488. if (s.animating) return;
  8489. realIndex = $(s.clickedSlide).attr('data-swiper-slide-index');
  8490. if (s.params.centeredSlides) {
  8491. if ((slideToIndex < s.loopedSlides - s.params.slidesPerView/2) || (slideToIndex > s.slides.length - s.loopedSlides + s.params.slidesPerView/2)) {
  8492. s.fixLoop();
  8493. slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index();
  8494. setTimeout(function () {
  8495. s.slideTo(slideToIndex);
  8496. }, 0);
  8497. }
  8498. else {
  8499. s.slideTo(slideToIndex);
  8500. }
  8501. }
  8502. else {
  8503. if (slideToIndex > s.slides.length - s.params.slidesPerView) {
  8504. s.fixLoop();
  8505. slideToIndex = s.wrapper.children('.' + s.params.slideClass + '[data-swiper-slide-index="' + realIndex + '"]:not(.swiper-slide-duplicate)').eq(0).index();
  8506. setTimeout(function () {
  8507. s.slideTo(slideToIndex);
  8508. }, 0);
  8509. }
  8510. else {
  8511. s.slideTo(slideToIndex);
  8512. }
  8513. }
  8514. }
  8515. else {
  8516. s.slideTo(slideToIndex);
  8517. }
  8518. }
  8519. };
  8520. var isTouched,
  8521. isMoved,
  8522. allowTouchCallbacks,
  8523. touchStartTime,
  8524. isScrolling,
  8525. currentTranslate,
  8526. startTranslate,
  8527. allowThresholdMove,
  8528. // Form elements to match
  8529. formElements = 'input, select, textarea, button',
  8530. // Last click time
  8531. lastClickTime = Date.now(), clickTimeout,
  8532. //Velocities
  8533. velocities = [],
  8534. allowMomentumBounce;
  8535. // Animating Flag
  8536. s.animating = false;
  8537. // Touches information
  8538. s.touches = {
  8539. startX: 0,
  8540. startY: 0,
  8541. currentX: 0,
  8542. currentY: 0,
  8543. diff: 0
  8544. };
  8545. // Touch handlers
  8546. var isTouchEvent, startMoving;
  8547. s.onTouchStart = function (e) {
  8548. if (e.originalEvent) e = e.originalEvent;
  8549. isTouchEvent = e.type === 'touchstart';
  8550. if (!isTouchEvent && 'which' in e && e.which === 3) return;
  8551. if (s.params.noSwiping && findElementInEvent(e, '.' + s.params.noSwipingClass)) {
  8552. s.allowClick = true;
  8553. return;
  8554. }
  8555. if (s.params.swipeHandler) {
  8556. if (!findElementInEvent(e, s.params.swipeHandler)) return;
  8557. }
  8558. var startX = s.touches.currentX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
  8559. var startY = s.touches.currentY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
  8560. // Do NOT start if iOS edge swipe is detected. Otherwise iOS app (UIWebView) cannot swipe-to-go-back anymore
  8561. if(s.device.ios && s.params.iOSEdgeSwipeDetection && startX <= s.params.iOSEdgeSwipeThreshold) {
  8562. return;
  8563. }
  8564. isTouched = true;
  8565. isMoved = false;
  8566. allowTouchCallbacks = true;
  8567. isScrolling = undefined;
  8568. startMoving = undefined;
  8569. s.touches.startX = startX;
  8570. s.touches.startY = startY;
  8571. touchStartTime = Date.now();
  8572. s.allowClick = true;
  8573. s.updateContainerSize();
  8574. s.swipeDirection = undefined;
  8575. if (s.params.threshold > 0) allowThresholdMove = false;
  8576. if (e.type !== 'touchstart') {
  8577. var preventDefault = true;
  8578. if ($(e.target).is(formElements)) preventDefault = false;
  8579. if (document.activeElement && $(document.activeElement).is(formElements)) {
  8580. document.activeElement.blur();
  8581. }
  8582. if (preventDefault) {
  8583. e.preventDefault();
  8584. }
  8585. }
  8586. s.emit('onTouchStart', s, e);
  8587. };
  8588. s.onTouchMove = function (e) {
  8589. if (e.originalEvent) e = e.originalEvent;
  8590. if (isTouchEvent && e.type === 'mousemove') return;
  8591. if (e.preventedByNestedSwiper) return;
  8592. if (s.params.onlyExternal) {
  8593. // isMoved = true;
  8594. s.allowClick = false;
  8595. if (isTouched) {
  8596. s.touches.startX = s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
  8597. s.touches.startY = s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
  8598. touchStartTime = Date.now();
  8599. }
  8600. return;
  8601. }
  8602. if (isTouchEvent && document.activeElement) {
  8603. if (e.target === document.activeElement && $(e.target).is(formElements)) {
  8604. isMoved = true;
  8605. s.allowClick = false;
  8606. return;
  8607. }
  8608. }
  8609. if (allowTouchCallbacks) {
  8610. s.emit('onTouchMove', s, e);
  8611. }
  8612. if (e.targetTouches && e.targetTouches.length > 1) return;
  8613. s.touches.currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
  8614. s.touches.currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
  8615. if (typeof isScrolling === 'undefined') {
  8616. var touchAngle = Math.atan2(Math.abs(s.touches.currentY - s.touches.startY), Math.abs(s.touches.currentX - s.touches.startX)) * 180 / Math.PI;
  8617. isScrolling = isH() ? touchAngle > s.params.touchAngle : (90 - touchAngle > s.params.touchAngle);
  8618. }
  8619. if (isScrolling) {
  8620. s.emit('onTouchMoveOpposite', s, e);
  8621. }
  8622. if (typeof startMoving === 'undefined' && s.browser.ieTouch) {
  8623. if (s.touches.currentX !== s.touches.startX || s.touches.currentY !== s.touches.startY) {
  8624. startMoving = true;
  8625. }
  8626. }
  8627. if (!isTouched) return;
  8628. if (isScrolling) {
  8629. isTouched = false;
  8630. return;
  8631. }
  8632. if (!startMoving && s.browser.ieTouch) {
  8633. return;
  8634. }
  8635. s.allowClick = false;
  8636. s.emit('onSliderMove', s, e);
  8637. e.preventDefault();
  8638. if (s.params.touchMoveStopPropagation && !s.params.nested) {
  8639. e.stopPropagation();
  8640. }
  8641. if (!isMoved) {
  8642. if (params.loop) {
  8643. s.fixLoop();
  8644. }
  8645. startTranslate = s.getWrapperTranslate();
  8646. s.setWrapperTransition(0);
  8647. if (s.animating) {
  8648. s.wrapper.trigger('webkitTransitionEnd transitionend oTransitionEnd MSTransitionEnd msTransitionEnd');
  8649. }
  8650. if (s.params.autoplay && s.autoplaying) {
  8651. if (s.params.autoplayDisableOnInteraction) {
  8652. s.stopAutoplay();
  8653. }
  8654. else {
  8655. s.pauseAutoplay();
  8656. }
  8657. }
  8658. allowMomentumBounce = false;
  8659. //Grab Cursor
  8660. if (s.params.grabCursor) {
  8661. s.container[0].style.cursor = 'move';
  8662. s.container[0].style.cursor = '-webkit-grabbing';
  8663. s.container[0].style.cursor = '-moz-grabbin';
  8664. s.container[0].style.cursor = 'grabbing';
  8665. }
  8666. }
  8667. isMoved = true;
  8668. var diff = s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY;
  8669. diff = diff * s.params.touchRatio;
  8670. if (s.rtl) diff = -diff;
  8671. s.swipeDirection = diff > 0 ? 'prev' : 'next';
  8672. currentTranslate = diff + startTranslate;
  8673. var disableParentSwiper = true;
  8674. if ((diff > 0 && currentTranslate > s.minTranslate())) {
  8675. disableParentSwiper = false;
  8676. if (s.params.resistance) currentTranslate = s.minTranslate() - 1 + Math.pow(-s.minTranslate() + startTranslate + diff, s.params.resistanceRatio);
  8677. }
  8678. else if (diff < 0 && currentTranslate < s.maxTranslate()) {
  8679. disableParentSwiper = false;
  8680. if (s.params.resistance) currentTranslate = s.maxTranslate() + 1 - Math.pow(s.maxTranslate() - startTranslate - diff, s.params.resistanceRatio);
  8681. }
  8682. if (disableParentSwiper) {
  8683. e.preventedByNestedSwiper = true;
  8684. }
  8685. // Directions locks
  8686. if (!s.params.allowSwipeToNext && s.swipeDirection === 'next' && currentTranslate < startTranslate) {
  8687. currentTranslate = startTranslate;
  8688. }
  8689. if (!s.params.allowSwipeToPrev && s.swipeDirection === 'prev' && currentTranslate > startTranslate) {
  8690. currentTranslate = startTranslate;
  8691. }
  8692. if (!s.params.followFinger) return;
  8693. // Threshold
  8694. if (s.params.threshold > 0) {
  8695. if (Math.abs(diff) > s.params.threshold || allowThresholdMove) {
  8696. if (!allowThresholdMove) {
  8697. allowThresholdMove = true;
  8698. s.touches.startX = s.touches.currentX;
  8699. s.touches.startY = s.touches.currentY;
  8700. currentTranslate = startTranslate;
  8701. s.touches.diff = isH() ? s.touches.currentX - s.touches.startX : s.touches.currentY - s.touches.startY;
  8702. return;
  8703. }
  8704. }
  8705. else {
  8706. currentTranslate = startTranslate;
  8707. return;
  8708. }
  8709. }
  8710. // Update active index in free mode
  8711. if (s.params.freeMode || s.params.watchSlidesProgress) {
  8712. s.updateActiveIndex();
  8713. }
  8714. if (s.params.freeMode) {
  8715. //Velocity
  8716. if (velocities.length === 0) {
  8717. velocities.push({
  8718. position: s.touches[isH() ? 'startX' : 'startY'],
  8719. time: touchStartTime
  8720. });
  8721. }
  8722. velocities.push({
  8723. position: s.touches[isH() ? 'currentX' : 'currentY'],
  8724. time: (new window.Date()).getTime()
  8725. });
  8726. }
  8727. // Update progress
  8728. s.updateProgress(currentTranslate);
  8729. // Update translate
  8730. s.setWrapperTranslate(currentTranslate);
  8731. };
  8732. s.onTouchEnd = function (e) {
  8733. if (e.originalEvent) e = e.originalEvent;
  8734. if (allowTouchCallbacks) {
  8735. s.emit('onTouchEnd', s, e);
  8736. }
  8737. allowTouchCallbacks = false;
  8738. if (!isTouched) return;
  8739. //Return Grab Cursor
  8740. if (s.params.grabCursor && isMoved && isTouched) {
  8741. s.container[0].style.cursor = 'move';
  8742. s.container[0].style.cursor = '-webkit-grab';
  8743. s.container[0].style.cursor = '-moz-grab';
  8744. s.container[0].style.cursor = 'grab';
  8745. }
  8746. // Time diff
  8747. var touchEndTime = Date.now();
  8748. var timeDiff = touchEndTime - touchStartTime;
  8749. // Tap, doubleTap, Click
  8750. if (s.allowClick) {
  8751. s.updateClickedSlide(e);
  8752. s.emit('onTap', s, e);
  8753. if (timeDiff < 300 && (touchEndTime - lastClickTime) > 300) {
  8754. if (clickTimeout) clearTimeout(clickTimeout);
  8755. clickTimeout = setTimeout(function () {
  8756. if (!s) return;
  8757. if (s.params.paginationHide && s.paginationContainer.length > 0 && !$(e.target).hasClass(s.params.bulletClass)) {
  8758. s.paginationContainer.toggleClass(s.params.paginationHiddenClass);
  8759. }
  8760. s.emit('onClick', s, e);
  8761. }, 300);
  8762. }
  8763. if (timeDiff < 300 && (touchEndTime - lastClickTime) < 300) {
  8764. if (clickTimeout) clearTimeout(clickTimeout);
  8765. s.emit('onDoubleTap', s, e);
  8766. }
  8767. }
  8768. lastClickTime = Date.now();
  8769. setTimeout(function () {
  8770. if (s) s.allowClick = true;
  8771. }, 0);
  8772. if (!isTouched || !isMoved || !s.swipeDirection || s.touches.diff === 0 || currentTranslate === startTranslate) {
  8773. isTouched = isMoved = false;
  8774. return;
  8775. }
  8776. isTouched = isMoved = false;
  8777. var currentPos;
  8778. if (s.params.followFinger) {
  8779. currentPos = s.rtl ? s.translate : -s.translate;
  8780. }
  8781. else {
  8782. currentPos = -currentTranslate;
  8783. }
  8784. if (s.params.freeMode) {
  8785. if (currentPos < -s.minTranslate()) {
  8786. s.slideTo(s.activeIndex);
  8787. return;
  8788. }
  8789. else if (currentPos > -s.maxTranslate()) {
  8790. if (s.slides.length < s.snapGrid.length) {
  8791. s.slideTo(s.snapGrid.length - 1);
  8792. }
  8793. else {
  8794. s.slideTo(s.slides.length - 1);
  8795. }
  8796. return;
  8797. }
  8798. if (s.params.freeModeMomentum) {
  8799. if (velocities.length > 1) {
  8800. var lastMoveEvent = velocities.pop(), velocityEvent = velocities.pop();
  8801. var distance = lastMoveEvent.position - velocityEvent.position;
  8802. var time = lastMoveEvent.time - velocityEvent.time;
  8803. s.velocity = distance / time;
  8804. s.velocity = s.velocity / 2;
  8805. if (Math.abs(s.velocity) < s.params.freeModeMinimumVelocity) {
  8806. s.velocity = 0;
  8807. }
  8808. // this implies that the user stopped moving a finger then released.
  8809. // There would be no events with distance zero, so the last event is stale.
  8810. if (time > 150 || (new window.Date().getTime() - lastMoveEvent.time) > 300) {
  8811. s.velocity = 0;
  8812. }
  8813. } else {
  8814. s.velocity = 0;
  8815. }
  8816. velocities.length = 0;
  8817. var momentumDuration = 1000 * s.params.freeModeMomentumRatio;
  8818. var momentumDistance = s.velocity * momentumDuration;
  8819. var newPosition = s.translate + momentumDistance;
  8820. if (s.rtl) newPosition = - newPosition;
  8821. var doBounce = false;
  8822. var afterBouncePosition;
  8823. var bounceAmount = Math.abs(s.velocity) * 20 * s.params.freeModeMomentumBounceRatio;
  8824. if (newPosition < s.maxTranslate()) {
  8825. if (s.params.freeModeMomentumBounce) {
  8826. if (newPosition + s.maxTranslate() < -bounceAmount) {
  8827. newPosition = s.maxTranslate() - bounceAmount;
  8828. }
  8829. afterBouncePosition = s.maxTranslate();
  8830. doBounce = true;
  8831. allowMomentumBounce = true;
  8832. }
  8833. else {
  8834. newPosition = s.maxTranslate();
  8835. }
  8836. }
  8837. else if (newPosition > s.minTranslate()) {
  8838. if (s.params.freeModeMomentumBounce) {
  8839. if (newPosition - s.minTranslate() > bounceAmount) {
  8840. newPosition = s.minTranslate() + bounceAmount;
  8841. }
  8842. afterBouncePosition = s.minTranslate();
  8843. doBounce = true;
  8844. allowMomentumBounce = true;
  8845. }
  8846. else {
  8847. newPosition = s.minTranslate();
  8848. }
  8849. }
  8850. else if (s.params.freeModeSticky) {
  8851. var j = 0,
  8852. nextSlide;
  8853. for (j = 0; j < s.snapGrid.length; j += 1) {
  8854. if (s.snapGrid[j] > -newPosition) {
  8855. nextSlide = j;
  8856. break;
  8857. }
  8858. }
  8859. if (Math.abs(s.snapGrid[nextSlide] - newPosition) < Math.abs(s.snapGrid[nextSlide - 1] - newPosition) || s.swipeDirection === 'next') {
  8860. newPosition = s.snapGrid[nextSlide];
  8861. } else {
  8862. newPosition = s.snapGrid[nextSlide - 1];
  8863. }
  8864. if (!s.rtl) newPosition = - newPosition;
  8865. }
  8866. //Fix duration
  8867. if (s.velocity !== 0) {
  8868. if (s.rtl) {
  8869. momentumDuration = Math.abs((-newPosition - s.translate) / s.velocity);
  8870. }
  8871. else {
  8872. momentumDuration = Math.abs((newPosition - s.translate) / s.velocity);
  8873. }
  8874. }
  8875. else if (s.params.freeModeSticky) {
  8876. s.slideReset();
  8877. return;
  8878. }
  8879. if (s.params.freeModeMomentumBounce && doBounce) {
  8880. s.updateProgress(afterBouncePosition);
  8881. s.setWrapperTransition(momentumDuration);
  8882. s.setWrapperTranslate(newPosition);
  8883. s.onTransitionStart();
  8884. s.animating = true;
  8885. s.wrapper.transitionEnd(function () {
  8886. if (!s || !allowMomentumBounce) return;
  8887. s.emit('onMomentumBounce', s);
  8888. s.setWrapperTransition(s.params.speed);
  8889. s.setWrapperTranslate(afterBouncePosition);
  8890. s.wrapper.transitionEnd(function () {
  8891. if (!s) return;
  8892. s.onTransitionEnd();
  8893. });
  8894. });
  8895. } else if (s.velocity) {
  8896. s.updateProgress(newPosition);
  8897. s.setWrapperTransition(momentumDuration);
  8898. s.setWrapperTranslate(newPosition);
  8899. s.onTransitionStart();
  8900. if (!s.animating) {
  8901. s.animating = true;
  8902. s.wrapper.transitionEnd(function () {
  8903. if (!s) return;
  8904. s.onTransitionEnd();
  8905. });
  8906. }
  8907. } else {
  8908. s.updateProgress(newPosition);
  8909. }
  8910. s.updateActiveIndex();
  8911. }
  8912. if (!s.params.freeModeMomentum || timeDiff >= s.params.longSwipesMs) {
  8913. s.updateProgress();
  8914. s.updateActiveIndex();
  8915. }
  8916. return;
  8917. }
  8918. // Find current slide
  8919. var i, stopIndex = 0, groupSize = s.slidesSizesGrid[0];
  8920. for (i = 0; i < s.slidesGrid.length; i += s.params.slidesPerGroup) {
  8921. if (typeof s.slidesGrid[i + s.params.slidesPerGroup] !== 'undefined') {
  8922. if (currentPos >= s.slidesGrid[i] && currentPos < s.slidesGrid[i + s.params.slidesPerGroup]) {
  8923. stopIndex = i;
  8924. groupSize = s.slidesGrid[i + s.params.slidesPerGroup] - s.slidesGrid[i];
  8925. }
  8926. }
  8927. else {
  8928. if (currentPos >= s.slidesGrid[i]) {
  8929. stopIndex = i;
  8930. groupSize = s.slidesGrid[s.slidesGrid.length - 1] - s.slidesGrid[s.slidesGrid.length - 2];
  8931. }
  8932. }
  8933. }
  8934. // Find current slide size
  8935. var ratio = (currentPos - s.slidesGrid[stopIndex]) / groupSize;
  8936. if (timeDiff > s.params.longSwipesMs) {
  8937. // Long touches
  8938. if (!s.params.longSwipes) {
  8939. s.slideTo(s.activeIndex);
  8940. return;
  8941. }
  8942. if (s.swipeDirection === 'next') {
  8943. if (ratio >= s.params.longSwipesRatio) s.slideTo(stopIndex + s.params.slidesPerGroup);
  8944. else s.slideTo(stopIndex);
  8945. }
  8946. if (s.swipeDirection === 'prev') {
  8947. if (ratio > (1 - s.params.longSwipesRatio)) s.slideTo(stopIndex + s.params.slidesPerGroup);
  8948. else s.slideTo(stopIndex);
  8949. }
  8950. }
  8951. else {
  8952. // Short swipes
  8953. if (!s.params.shortSwipes) {
  8954. s.slideTo(s.activeIndex);
  8955. return;
  8956. }
  8957. if (s.swipeDirection === 'next') {
  8958. s.slideTo(stopIndex + s.params.slidesPerGroup);
  8959. }
  8960. if (s.swipeDirection === 'prev') {
  8961. s.slideTo(stopIndex);
  8962. }
  8963. }
  8964. };
  8965. /*=========================
  8966. Transitions
  8967. ===========================*/
  8968. s._slideTo = function (slideIndex, speed) {
  8969. return s.slideTo(slideIndex, speed, true, true);
  8970. };
  8971. s.slideTo = function (slideIndex, speed, runCallbacks, internal) {
  8972. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  8973. if (typeof slideIndex === 'undefined') slideIndex = 0;
  8974. if (slideIndex < 0) slideIndex = 0;
  8975. s.snapIndex = Math.floor(slideIndex / s.params.slidesPerGroup);
  8976. if (s.snapIndex >= s.snapGrid.length) s.snapIndex = s.snapGrid.length - 1;
  8977. var translate = - s.snapGrid[s.snapIndex];
  8978. // Stop autoplay
  8979. if (s.params.autoplay && s.autoplaying) {
  8980. if (internal || !s.params.autoplayDisableOnInteraction) {
  8981. s.pauseAutoplay(speed);
  8982. }
  8983. else {
  8984. s.stopAutoplay();
  8985. }
  8986. }
  8987. // Update progress
  8988. s.updateProgress(translate);
  8989. // Normalize slideIndex
  8990. for (var i = 0; i < s.slidesGrid.length; i++) {
  8991. if (- Math.floor(translate * 100) >= Math.floor(s.slidesGrid[i] * 100)) {
  8992. slideIndex = i;
  8993. }
  8994. }
  8995. // Directions locks
  8996. if (!s.params.allowSwipeToNext && translate < s.translate && translate < s.minTranslate()) {
  8997. return false;
  8998. }
  8999. if (!s.params.allowSwipeToPrev && translate > s.translate && translate > s.maxTranslate()) {
  9000. if ((s.activeIndex || 0) !== slideIndex ) return false;
  9001. }
  9002. // Update Index
  9003. if (typeof speed === 'undefined') speed = s.params.speed;
  9004. s.previousIndex = s.activeIndex || 0;
  9005. s.activeIndex = slideIndex;
  9006. if ((s.rtl && -translate === s.translate) || (!s.rtl && translate === s.translate)) {
  9007. // Update Height
  9008. if (s.params.autoHeight) {
  9009. s.updateAutoHeight();
  9010. }
  9011. s.updateClasses();
  9012. if (s.params.effect !== 'slide') {
  9013. s.setWrapperTranslate(translate);
  9014. }
  9015. return false;
  9016. }
  9017. s.updateClasses();
  9018. s.onTransitionStart(runCallbacks);
  9019. if (speed === 0) {
  9020. s.setWrapperTranslate(translate);
  9021. s.setWrapperTransition(0);
  9022. s.onTransitionEnd(runCallbacks);
  9023. }
  9024. else {
  9025. s.setWrapperTranslate(translate);
  9026. s.setWrapperTransition(speed);
  9027. if (!s.animating) {
  9028. s.animating = true;
  9029. s.wrapper.transitionEnd(function () {
  9030. if (!s) return;
  9031. s.onTransitionEnd(runCallbacks);
  9032. });
  9033. }
  9034. }
  9035. return true;
  9036. };
  9037. s.onTransitionStart = function (runCallbacks) {
  9038. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  9039. if (s.params.autoHeight) {
  9040. s.updateAutoHeight();
  9041. }
  9042. if (s.lazy) s.lazy.onTransitionStart();
  9043. if (runCallbacks) {
  9044. s.emit('onTransitionStart', s);
  9045. if (s.activeIndex !== s.previousIndex) {
  9046. s.emit('onSlideChangeStart', s);
  9047. _scope.$emit("$ionicSlides.slideChangeStart", {
  9048. slider: s,
  9049. activeIndex: s.getSlideDataIndex(s.activeIndex),
  9050. previousIndex: s.getSlideDataIndex(s.previousIndex)
  9051. });
  9052. if (s.activeIndex > s.previousIndex) {
  9053. s.emit('onSlideNextStart', s);
  9054. }
  9055. else {
  9056. s.emit('onSlidePrevStart', s);
  9057. }
  9058. }
  9059. }
  9060. };
  9061. s.onTransitionEnd = function (runCallbacks) {
  9062. s.animating = false;
  9063. s.setWrapperTransition(0);
  9064. if (typeof runCallbacks === 'undefined') runCallbacks = true;
  9065. if (s.lazy) s.lazy.onTransitionEnd();
  9066. if (runCallbacks) {
  9067. s.emit('onTransitionEnd', s);
  9068. if (s.activeIndex !== s.previousIndex) {
  9069. s.emit('onSlideChangeEnd', s);
  9070. _scope.$emit("$ionicSlides.slideChangeEnd", {
  9071. slider: s,
  9072. activeIndex: s.getSlideDataIndex(s.activeIndex),
  9073. previousIndex: s.getSlideDataIndex(s.previousIndex)
  9074. });
  9075. if (s.activeIndex > s.previousIndex) {
  9076. s.emit('onSlideNextEnd', s);
  9077. }
  9078. else {
  9079. s.emit('onSlidePrevEnd', s);
  9080. }
  9081. }
  9082. }
  9083. if (s.params.hashnav && s.hashnav) {
  9084. s.hashnav.setHash();
  9085. }
  9086. };
  9087. s.slideNext = function (runCallbacks, speed, internal) {
  9088. if (s.params.loop) {
  9089. if (s.animating) return false;
  9090. s.fixLoop();
  9091. var clientLeft = s.container[0].clientLeft;
  9092. return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal);
  9093. }
  9094. else return s.slideTo(s.activeIndex + s.params.slidesPerGroup, speed, runCallbacks, internal);
  9095. };
  9096. s._slideNext = function (speed) {
  9097. return s.slideNext(true, speed, true);
  9098. };
  9099. s.slidePrev = function (runCallbacks, speed, internal) {
  9100. if (s.params.loop) {
  9101. if (s.animating) return false;
  9102. s.fixLoop();
  9103. var clientLeft = s.container[0].clientLeft;
  9104. return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal);
  9105. }
  9106. else return s.slideTo(s.activeIndex - 1, speed, runCallbacks, internal);
  9107. };
  9108. s._slidePrev = function (speed) {
  9109. return s.slidePrev(true, speed, true);
  9110. };
  9111. s.slideReset = function (runCallbacks, speed, internal) {
  9112. return s.slideTo(s.activeIndex, speed, runCallbacks);
  9113. };
  9114. /*=========================
  9115. Translate/transition helpers
  9116. ===========================*/
  9117. s.setWrapperTransition = function (duration, byController) {
  9118. s.wrapper.transition(duration);
  9119. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  9120. s.effects[s.params.effect].setTransition(duration);
  9121. }
  9122. if (s.params.parallax && s.parallax) {
  9123. s.parallax.setTransition(duration);
  9124. }
  9125. if (s.params.scrollbar && s.scrollbar) {
  9126. s.scrollbar.setTransition(duration);
  9127. }
  9128. if (s.params.control && s.controller) {
  9129. s.controller.setTransition(duration, byController);
  9130. }
  9131. s.emit('onSetTransition', s, duration);
  9132. };
  9133. s.setWrapperTranslate = function (translate, updateActiveIndex, byController) {
  9134. var x = 0, y = 0, z = 0;
  9135. if (isH()) {
  9136. x = s.rtl ? -translate : translate;
  9137. }
  9138. else {
  9139. y = translate;
  9140. }
  9141. if (s.params.roundLengths) {
  9142. x = round(x);
  9143. y = round(y);
  9144. }
  9145. if (!s.params.virtualTranslate) {
  9146. if (s.support.transforms3d) s.wrapper.transform('translate3d(' + x + 'px, ' + y + 'px, ' + z + 'px)');
  9147. else s.wrapper.transform('translate(' + x + 'px, ' + y + 'px)');
  9148. }
  9149. s.translate = isH() ? x : y;
  9150. // Check if we need to update progress
  9151. var progress;
  9152. var translatesDiff = s.maxTranslate() - s.minTranslate();
  9153. if (translatesDiff === 0) {
  9154. progress = 0;
  9155. }
  9156. else {
  9157. progress = (translate - s.minTranslate()) / (translatesDiff);
  9158. }
  9159. if (progress !== s.progress) {
  9160. s.updateProgress(translate);
  9161. }
  9162. if (updateActiveIndex) s.updateActiveIndex();
  9163. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  9164. s.effects[s.params.effect].setTranslate(s.translate);
  9165. }
  9166. if (s.params.parallax && s.parallax) {
  9167. s.parallax.setTranslate(s.translate);
  9168. }
  9169. if (s.params.scrollbar && s.scrollbar) {
  9170. s.scrollbar.setTranslate(s.translate);
  9171. }
  9172. if (s.params.control && s.controller) {
  9173. s.controller.setTranslate(s.translate, byController);
  9174. }
  9175. s.emit('onSetTranslate', s, s.translate);
  9176. };
  9177. s.getTranslate = function (el, axis) {
  9178. var matrix, curTransform, curStyle, transformMatrix;
  9179. // automatic axis detection
  9180. if (typeof axis === 'undefined') {
  9181. axis = 'x';
  9182. }
  9183. if (s.params.virtualTranslate) {
  9184. return s.rtl ? -s.translate : s.translate;
  9185. }
  9186. curStyle = window.getComputedStyle(el, null);
  9187. if (window.WebKitCSSMatrix) {
  9188. curTransform = curStyle.transform || curStyle.webkitTransform;
  9189. if (curTransform.split(',').length > 6) {
  9190. curTransform = curTransform.split(', ').map(function(a){
  9191. return a.replace(',','.');
  9192. }).join(', ');
  9193. }
  9194. // Some old versions of Webkit choke when 'none' is passed; pass
  9195. // empty string instead in this case
  9196. transformMatrix = new window.WebKitCSSMatrix(curTransform === 'none' ? '' : curTransform);
  9197. }
  9198. else {
  9199. transformMatrix = curStyle.MozTransform || curStyle.OTransform || curStyle.MsTransform || curStyle.msTransform || curStyle.transform || curStyle.getPropertyValue('transform').replace('translate(', 'matrix(1, 0, 0, 1,');
  9200. matrix = transformMatrix.toString().split(',');
  9201. }
  9202. if (axis === 'x') {
  9203. //Latest Chrome and webkits Fix
  9204. if (window.WebKitCSSMatrix)
  9205. curTransform = transformMatrix.m41;
  9206. //Crazy IE10 Matrix
  9207. else if (matrix.length === 16)
  9208. curTransform = parseFloat(matrix[12]);
  9209. //Normal Browsers
  9210. else
  9211. curTransform = parseFloat(matrix[4]);
  9212. }
  9213. if (axis === 'y') {
  9214. //Latest Chrome and webkits Fix
  9215. if (window.WebKitCSSMatrix)
  9216. curTransform = transformMatrix.m42;
  9217. //Crazy IE10 Matrix
  9218. else if (matrix.length === 16)
  9219. curTransform = parseFloat(matrix[13]);
  9220. //Normal Browsers
  9221. else
  9222. curTransform = parseFloat(matrix[5]);
  9223. }
  9224. if (s.rtl && curTransform) curTransform = -curTransform;
  9225. return curTransform || 0;
  9226. };
  9227. s.getWrapperTranslate = function (axis) {
  9228. if (typeof axis === 'undefined') {
  9229. axis = isH() ? 'x' : 'y';
  9230. }
  9231. return s.getTranslate(s.wrapper[0], axis);
  9232. };
  9233. /*=========================
  9234. Observer
  9235. ===========================*/
  9236. s.observers = [];
  9237. function initObserver(target, options) {
  9238. options = options || {};
  9239. // create an observer instance
  9240. var ObserverFunc = window.MutationObserver || window.WebkitMutationObserver;
  9241. var observer = new ObserverFunc(function (mutations) {
  9242. mutations.forEach(function (mutation) {
  9243. s.onResize(true);
  9244. s.emit('onObserverUpdate', s, mutation);
  9245. });
  9246. });
  9247. observer.observe(target, {
  9248. attributes: typeof options.attributes === 'undefined' ? true : options.attributes,
  9249. childList: typeof options.childList === 'undefined' ? true : options.childList,
  9250. characterData: typeof options.characterData === 'undefined' ? true : options.characterData
  9251. });
  9252. s.observers.push(observer);
  9253. }
  9254. s.initObservers = function () {
  9255. if (s.params.observeParents) {
  9256. var containerParents = s.container.parents();
  9257. for (var i = 0; i < containerParents.length; i++) {
  9258. initObserver(containerParents[i]);
  9259. }
  9260. }
  9261. // Observe container
  9262. initObserver(s.container[0], {childList: false});
  9263. // Observe wrapper
  9264. initObserver(s.wrapper[0], {attributes: false});
  9265. };
  9266. s.disconnectObservers = function () {
  9267. for (var i = 0; i < s.observers.length; i++) {
  9268. s.observers[i].disconnect();
  9269. }
  9270. s.observers = [];
  9271. };
  9272. s.updateLoop = function(){
  9273. var currentSlide = s.slides.eq(s.activeIndex);
  9274. if ( angular.element(currentSlide).hasClass(s.params.slideDuplicateClass) ){
  9275. // we're on a duplicate, so slide to the non-duplicate
  9276. var swiperSlideIndex = angular.element(currentSlide).attr("data-swiper-slide-index");
  9277. var slides = s.wrapper.children('.' + s.params.slideClass);
  9278. for ( var i = 0; i < slides.length; i++ ){
  9279. if ( !angular.element(slides[i]).hasClass(s.params.slideDuplicateClass) && angular.element(slides[i]).attr("data-swiper-slide-index") === swiperSlideIndex ){
  9280. s.slideTo(i, 0, false, true);
  9281. break;
  9282. }
  9283. }
  9284. // if we needed to switch slides, we did that. So, now call the createLoop function internally
  9285. setTimeout(function(){
  9286. s.createLoop();
  9287. }, 50);
  9288. }
  9289. }
  9290. s.getSlideDataIndex = function(slideIndex){
  9291. // this is an Ionic custom function
  9292. // Swiper loops utilize duplicate DOM elements for slides when in a loop
  9293. // which means that we cannot rely on the actual slide index for our events
  9294. // because index 0 does not necessarily point to index 0
  9295. // and index n+1 does not necessarily point to the expected piece of data
  9296. // therefore, rather than using the actual slide index we should
  9297. // use the data index that swiper includes as an attribute on the dom elements
  9298. // because this is what will be meaningful to the consumer of our events
  9299. var slide = s.slides.eq(slideIndex);
  9300. var attributeIndex = angular.element(slide).attr("data-swiper-slide-index");
  9301. return parseInt(attributeIndex);
  9302. }
  9303. /*=========================
  9304. Loop
  9305. ===========================*/
  9306. // Create looped slides
  9307. s.createLoop = function () {
  9308. //console.log("Slider create loop method");
  9309. //var toRemove = s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass);
  9310. //angular.element(toRemove).remove();
  9311. s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass).remove();
  9312. var slides = s.wrapper.children('.' + s.params.slideClass);
  9313. if(s.params.slidesPerView === 'auto' && !s.params.loopedSlides) s.params.loopedSlides = slides.length;
  9314. s.loopedSlides = parseInt(s.params.loopedSlides || s.params.slidesPerView, 10);
  9315. s.loopedSlides = s.loopedSlides + s.params.loopAdditionalSlides;
  9316. if (s.loopedSlides > slides.length) {
  9317. s.loopedSlides = slides.length;
  9318. }
  9319. var prependSlides = [], appendSlides = [], i, scope, newNode;
  9320. slides.each(function (index, el) {
  9321. var slide = $(this);
  9322. if (index < s.loopedSlides) appendSlides.push(el);
  9323. if (index < slides.length && index >= slides.length - s.loopedSlides) prependSlides.push(el);
  9324. slide.attr('data-swiper-slide-index', index);
  9325. });
  9326. for (i = 0; i < appendSlides.length; i++) {
  9327. newNode = angular.element(appendSlides[i]).clone().addClass(s.params.slideDuplicateClass);
  9328. newNode.removeAttr('ng-transclude');
  9329. newNode.removeAttr('ng-repeat');
  9330. scope = angular.element(appendSlides[i]).scope();
  9331. newNode = $compile(newNode)(scope);
  9332. angular.element(s.wrapper).append(newNode);
  9333. //s.wrapper.append($(appendSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));
  9334. }
  9335. for (i = prependSlides.length - 1; i >= 0; i--) {
  9336. //s.wrapper.prepend($(prependSlides[i].cloneNode(true)).addClass(s.params.slideDuplicateClass));
  9337. newNode = angular.element(prependSlides[i]).clone().addClass(s.params.slideDuplicateClass);
  9338. newNode.removeAttr('ng-transclude');
  9339. newNode.removeAttr('ng-repeat');
  9340. scope = angular.element(prependSlides[i]).scope();
  9341. newNode = $compile(newNode)(scope);
  9342. angular.element(s.wrapper).prepend(newNode);
  9343. }
  9344. };
  9345. s.destroyLoop = function () {
  9346. s.wrapper.children('.' + s.params.slideClass + '.' + s.params.slideDuplicateClass).remove();
  9347. s.slides.removeAttr('data-swiper-slide-index');
  9348. };
  9349. s.fixLoop = function () {
  9350. var newIndex;
  9351. //Fix For Negative Oversliding
  9352. if (s.activeIndex < s.loopedSlides) {
  9353. newIndex = s.slides.length - s.loopedSlides * 3 + s.activeIndex;
  9354. newIndex = newIndex + s.loopedSlides;
  9355. s.slideTo(newIndex, 0, false, true);
  9356. }
  9357. //Fix For Positive Oversliding
  9358. else if ((s.params.slidesPerView === 'auto' && s.activeIndex >= s.loopedSlides * 2) || (s.activeIndex > s.slides.length - s.params.slidesPerView * 2)) {
  9359. newIndex = -s.slides.length + s.activeIndex + s.loopedSlides;
  9360. newIndex = newIndex + s.loopedSlides;
  9361. s.slideTo(newIndex, 0, false, true);
  9362. }
  9363. };
  9364. /*=========================
  9365. Append/Prepend/Remove Slides
  9366. ===========================*/
  9367. s.appendSlide = function (slides) {
  9368. if (s.params.loop) {
  9369. s.destroyLoop();
  9370. }
  9371. if (typeof slides === 'object' && slides.length) {
  9372. for (var i = 0; i < slides.length; i++) {
  9373. if (slides[i]) s.wrapper.append(slides[i]);
  9374. }
  9375. }
  9376. else {
  9377. s.wrapper.append(slides);
  9378. }
  9379. if (s.params.loop) {
  9380. s.createLoop();
  9381. }
  9382. if (!(s.params.observer && s.support.observer)) {
  9383. s.update(true);
  9384. }
  9385. };
  9386. s.prependSlide = function (slides) {
  9387. if (s.params.loop) {
  9388. s.destroyLoop();
  9389. }
  9390. var newActiveIndex = s.activeIndex + 1;
  9391. if (typeof slides === 'object' && slides.length) {
  9392. for (var i = 0; i < slides.length; i++) {
  9393. if (slides[i]) s.wrapper.prepend(slides[i]);
  9394. }
  9395. newActiveIndex = s.activeIndex + slides.length;
  9396. }
  9397. else {
  9398. s.wrapper.prepend(slides);
  9399. }
  9400. if (s.params.loop) {
  9401. s.createLoop();
  9402. }
  9403. if (!(s.params.observer && s.support.observer)) {
  9404. s.update(true);
  9405. }
  9406. s.slideTo(newActiveIndex, 0, false);
  9407. };
  9408. s.removeSlide = function (slidesIndexes) {
  9409. if (s.params.loop) {
  9410. s.destroyLoop();
  9411. s.slides = s.wrapper.children('.' + s.params.slideClass);
  9412. }
  9413. var newActiveIndex = s.activeIndex,
  9414. indexToRemove;
  9415. if (typeof slidesIndexes === 'object' && slidesIndexes.length) {
  9416. for (var i = 0; i < slidesIndexes.length; i++) {
  9417. indexToRemove = slidesIndexes[i];
  9418. if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove();
  9419. if (indexToRemove < newActiveIndex) newActiveIndex--;
  9420. }
  9421. newActiveIndex = Math.max(newActiveIndex, 0);
  9422. }
  9423. else {
  9424. indexToRemove = slidesIndexes;
  9425. if (s.slides[indexToRemove]) s.slides.eq(indexToRemove).remove();
  9426. if (indexToRemove < newActiveIndex) newActiveIndex--;
  9427. newActiveIndex = Math.max(newActiveIndex, 0);
  9428. }
  9429. if (s.params.loop) {
  9430. s.createLoop();
  9431. }
  9432. if (!(s.params.observer && s.support.observer)) {
  9433. s.update(true);
  9434. }
  9435. if (s.params.loop) {
  9436. s.slideTo(newActiveIndex + s.loopedSlides, 0, false);
  9437. }
  9438. else {
  9439. s.slideTo(newActiveIndex, 0, false);
  9440. }
  9441. };
  9442. s.removeAllSlides = function () {
  9443. var slidesIndexes = [];
  9444. for (var i = 0; i < s.slides.length; i++) {
  9445. slidesIndexes.push(i);
  9446. }
  9447. s.removeSlide(slidesIndexes);
  9448. };
  9449. /*=========================
  9450. Effects
  9451. ===========================*/
  9452. s.effects = {
  9453. fade: {
  9454. setTranslate: function () {
  9455. for (var i = 0; i < s.slides.length; i++) {
  9456. var slide = s.slides.eq(i);
  9457. var offset = slide[0].swiperSlideOffset;
  9458. var tx = -offset;
  9459. if (!s.params.virtualTranslate) tx = tx - s.translate;
  9460. var ty = 0;
  9461. if (!isH()) {
  9462. ty = tx;
  9463. tx = 0;
  9464. }
  9465. var slideOpacity = s.params.fade.crossFade ?
  9466. Math.max(1 - Math.abs(slide[0].progress), 0) :
  9467. 1 + Math.min(Math.max(slide[0].progress, -1), 0);
  9468. slide
  9469. .css({
  9470. opacity: slideOpacity
  9471. })
  9472. .transform('translate3d(' + tx + 'px, ' + ty + 'px, 0px)');
  9473. }
  9474. },
  9475. setTransition: function (duration) {
  9476. s.slides.transition(duration);
  9477. if (s.params.virtualTranslate && duration !== 0) {
  9478. var eventTriggered = false;
  9479. s.slides.transitionEnd(function () {
  9480. if (eventTriggered) return;
  9481. if (!s) return;
  9482. eventTriggered = true;
  9483. s.animating = false;
  9484. var triggerEvents = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
  9485. for (var i = 0; i < triggerEvents.length; i++) {
  9486. s.wrapper.trigger(triggerEvents[i]);
  9487. }
  9488. });
  9489. }
  9490. }
  9491. },
  9492. cube: {
  9493. setTranslate: function () {
  9494. var wrapperRotate = 0, cubeShadow;
  9495. if (s.params.cube.shadow) {
  9496. if (isH()) {
  9497. cubeShadow = s.wrapper.find('.swiper-cube-shadow');
  9498. if (cubeShadow.length === 0) {
  9499. cubeShadow = $('<div class="swiper-cube-shadow"></div>');
  9500. s.wrapper.append(cubeShadow);
  9501. }
  9502. cubeShadow.css({height: s.width + 'px'});
  9503. }
  9504. else {
  9505. cubeShadow = s.container.find('.swiper-cube-shadow');
  9506. if (cubeShadow.length === 0) {
  9507. cubeShadow = $('<div class="swiper-cube-shadow"></div>');
  9508. s.container.append(cubeShadow);
  9509. }
  9510. }
  9511. }
  9512. for (var i = 0; i < s.slides.length; i++) {
  9513. var slide = s.slides.eq(i);
  9514. var slideAngle = i * 90;
  9515. var round = Math.floor(slideAngle / 360);
  9516. if (s.rtl) {
  9517. slideAngle = -slideAngle;
  9518. round = Math.floor(-slideAngle / 360);
  9519. }
  9520. var progress = Math.max(Math.min(slide[0].progress, 1), -1);
  9521. var tx = 0, ty = 0, tz = 0;
  9522. if (i % 4 === 0) {
  9523. tx = - round * 4 * s.size;
  9524. tz = 0;
  9525. }
  9526. else if ((i - 1) % 4 === 0) {
  9527. tx = 0;
  9528. tz = - round * 4 * s.size;
  9529. }
  9530. else if ((i - 2) % 4 === 0) {
  9531. tx = s.size + round * 4 * s.size;
  9532. tz = s.size;
  9533. }
  9534. else if ((i - 3) % 4 === 0) {
  9535. tx = - s.size;
  9536. tz = 3 * s.size + s.size * 4 * round;
  9537. }
  9538. if (s.rtl) {
  9539. tx = -tx;
  9540. }
  9541. if (!isH()) {
  9542. ty = tx;
  9543. tx = 0;
  9544. }
  9545. var transform = 'rotateX(' + (isH() ? 0 : -slideAngle) + 'deg) rotateY(' + (isH() ? slideAngle : 0) + 'deg) translate3d(' + tx + 'px, ' + ty + 'px, ' + tz + 'px)';
  9546. if (progress <= 1 && progress > -1) {
  9547. wrapperRotate = i * 90 + progress * 90;
  9548. if (s.rtl) wrapperRotate = -i * 90 - progress * 90;
  9549. }
  9550. slide.transform(transform);
  9551. if (s.params.cube.slideShadows) {
  9552. //Set shadows
  9553. var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top');
  9554. var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom');
  9555. if (shadowBefore.length === 0) {
  9556. shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>');
  9557. slide.append(shadowBefore);
  9558. }
  9559. if (shadowAfter.length === 0) {
  9560. shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>');
  9561. slide.append(shadowAfter);
  9562. }
  9563. var shadowOpacity = slide[0].progress;
  9564. if (shadowBefore.length) shadowBefore[0].style.opacity = -slide[0].progress;
  9565. if (shadowAfter.length) shadowAfter[0].style.opacity = slide[0].progress;
  9566. }
  9567. }
  9568. s.wrapper.css({
  9569. '-webkit-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9570. '-moz-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9571. '-ms-transform-origin': '50% 50% -' + (s.size / 2) + 'px',
  9572. 'transform-origin': '50% 50% -' + (s.size / 2) + 'px'
  9573. });
  9574. if (s.params.cube.shadow) {
  9575. if (isH()) {
  9576. 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) + ')');
  9577. }
  9578. else {
  9579. var shadowAngle = Math.abs(wrapperRotate) - Math.floor(Math.abs(wrapperRotate) / 90) * 90;
  9580. var multiplier = 1.5 - (Math.sin(shadowAngle * 2 * Math.PI / 360) / 2 + Math.cos(shadowAngle * 2 * Math.PI / 360) / 2);
  9581. var scale1 = s.params.cube.shadowScale,
  9582. scale2 = s.params.cube.shadowScale / multiplier,
  9583. offset = s.params.cube.shadowOffset;
  9584. cubeShadow.transform('scale3d(' + scale1 + ', 1, ' + scale2 + ') translate3d(0px, ' + (s.height / 2 + offset) + 'px, ' + (-s.height / 2 / scale2) + 'px) rotateX(-90deg)');
  9585. }
  9586. }
  9587. var zFactor = (s.isSafari || s.isUiWebView) ? (-s.size / 2) : 0;
  9588. s.wrapper.transform('translate3d(0px,0,' + zFactor + 'px) rotateX(' + (isH() ? 0 : wrapperRotate) + 'deg) rotateY(' + (isH() ? -wrapperRotate : 0) + 'deg)');
  9589. },
  9590. setTransition: function (duration) {
  9591. s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);
  9592. if (s.params.cube.shadow && !isH()) {
  9593. s.container.find('.swiper-cube-shadow').transition(duration);
  9594. }
  9595. }
  9596. },
  9597. coverflow: {
  9598. setTranslate: function () {
  9599. var transform = s.translate;
  9600. var center = isH() ? -transform + s.width / 2 : -transform + s.height / 2;
  9601. var rotate = isH() ? s.params.coverflow.rotate: -s.params.coverflow.rotate;
  9602. var translate = s.params.coverflow.depth;
  9603. //Each slide offset from center
  9604. for (var i = 0, length = s.slides.length; i < length; i++) {
  9605. var slide = s.slides.eq(i);
  9606. var slideSize = s.slidesSizesGrid[i];
  9607. var slideOffset = slide[0].swiperSlideOffset;
  9608. var offsetMultiplier = (center - slideOffset - slideSize / 2) / slideSize * s.params.coverflow.modifier;
  9609. var rotateY = isH() ? rotate * offsetMultiplier : 0;
  9610. var rotateX = isH() ? 0 : rotate * offsetMultiplier;
  9611. // var rotateZ = 0
  9612. var translateZ = -translate * Math.abs(offsetMultiplier);
  9613. var translateY = isH() ? 0 : s.params.coverflow.stretch * (offsetMultiplier);
  9614. var translateX = isH() ? s.params.coverflow.stretch * (offsetMultiplier) : 0;
  9615. //Fix for ultra small values
  9616. if (Math.abs(translateX) < 0.001) translateX = 0;
  9617. if (Math.abs(translateY) < 0.001) translateY = 0;
  9618. if (Math.abs(translateZ) < 0.001) translateZ = 0;
  9619. if (Math.abs(rotateY) < 0.001) rotateY = 0;
  9620. if (Math.abs(rotateX) < 0.001) rotateX = 0;
  9621. var slideTransform = 'translate3d(' + translateX + 'px,' + translateY + 'px,' + translateZ + 'px) rotateX(' + rotateX + 'deg) rotateY(' + rotateY + 'deg)';
  9622. slide.transform(slideTransform);
  9623. slide[0].style.zIndex = -Math.abs(Math.round(offsetMultiplier)) + 1;
  9624. if (s.params.coverflow.slideShadows) {
  9625. //Set shadows
  9626. var shadowBefore = isH() ? slide.find('.swiper-slide-shadow-left') : slide.find('.swiper-slide-shadow-top');
  9627. var shadowAfter = isH() ? slide.find('.swiper-slide-shadow-right') : slide.find('.swiper-slide-shadow-bottom');
  9628. if (shadowBefore.length === 0) {
  9629. shadowBefore = $('<div class="swiper-slide-shadow-' + (isH() ? 'left' : 'top') + '"></div>');
  9630. slide.append(shadowBefore);
  9631. }
  9632. if (shadowAfter.length === 0) {
  9633. shadowAfter = $('<div class="swiper-slide-shadow-' + (isH() ? 'right' : 'bottom') + '"></div>');
  9634. slide.append(shadowAfter);
  9635. }
  9636. if (shadowBefore.length) shadowBefore[0].style.opacity = offsetMultiplier > 0 ? offsetMultiplier : 0;
  9637. if (shadowAfter.length) shadowAfter[0].style.opacity = (-offsetMultiplier) > 0 ? -offsetMultiplier : 0;
  9638. }
  9639. }
  9640. //Set correct perspective for IE10
  9641. if (s.browser.ie) {
  9642. var ws = s.wrapper[0].style;
  9643. ws.perspectiveOrigin = center + 'px 50%';
  9644. }
  9645. },
  9646. setTransition: function (duration) {
  9647. s.slides.transition(duration).find('.swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left').transition(duration);
  9648. }
  9649. }
  9650. };
  9651. /*=========================
  9652. Images Lazy Loading
  9653. ===========================*/
  9654. s.lazy = {
  9655. initialImageLoaded: false,
  9656. loadImageInSlide: function (index, loadInDuplicate) {
  9657. if (typeof index === 'undefined') return;
  9658. if (typeof loadInDuplicate === 'undefined') loadInDuplicate = true;
  9659. if (s.slides.length === 0) return;
  9660. var slide = s.slides.eq(index);
  9661. var img = slide.find('.swiper-lazy:not(.swiper-lazy-loaded):not(.swiper-lazy-loading)');
  9662. if (slide.hasClass('swiper-lazy') && !slide.hasClass('swiper-lazy-loaded') && !slide.hasClass('swiper-lazy-loading')) {
  9663. img = img.add(slide[0]);
  9664. }
  9665. if (img.length === 0) return;
  9666. img.each(function () {
  9667. var _img = $(this);
  9668. _img.addClass('swiper-lazy-loading');
  9669. var background = _img.attr('data-background');
  9670. var src = _img.attr('data-src'),
  9671. srcset = _img.attr('data-srcset');
  9672. s.loadImage(_img[0], (src || background), srcset, false, function () {
  9673. if (background) {
  9674. _img.css('background-image', 'url(' + background + ')');
  9675. _img.removeAttr('data-background');
  9676. }
  9677. else {
  9678. if (srcset) {
  9679. _img.attr('srcset', srcset);
  9680. _img.removeAttr('data-srcset');
  9681. }
  9682. if (src) {
  9683. _img.attr('src', src);
  9684. _img.removeAttr('data-src');
  9685. }
  9686. }
  9687. _img.addClass('swiper-lazy-loaded').removeClass('swiper-lazy-loading');
  9688. slide.find('.swiper-lazy-preloader, .preloader').remove();
  9689. if (s.params.loop && loadInDuplicate) {
  9690. var slideOriginalIndex = slide.attr('data-swiper-slide-index');
  9691. if (slide.hasClass(s.params.slideDuplicateClass)) {
  9692. var originalSlide = s.wrapper.children('[data-swiper-slide-index="' + slideOriginalIndex + '"]:not(.' + s.params.slideDuplicateClass + ')');
  9693. s.lazy.loadImageInSlide(originalSlide.index(), false);
  9694. }
  9695. else {
  9696. var duplicatedSlide = s.wrapper.children('.' + s.params.slideDuplicateClass + '[data-swiper-slide-index="' + slideOriginalIndex + '"]');
  9697. s.lazy.loadImageInSlide(duplicatedSlide.index(), false);
  9698. }
  9699. }
  9700. s.emit('onLazyImageReady', s, slide[0], _img[0]);
  9701. });
  9702. s.emit('onLazyImageLoad', s, slide[0], _img[0]);
  9703. });
  9704. },
  9705. load: function () {
  9706. var i;
  9707. if (s.params.watchSlidesVisibility) {
  9708. s.wrapper.children('.' + s.params.slideVisibleClass).each(function () {
  9709. s.lazy.loadImageInSlide($(this).index());
  9710. });
  9711. }
  9712. else {
  9713. if (s.params.slidesPerView > 1) {
  9714. for (i = s.activeIndex; i < s.activeIndex + s.params.slidesPerView ; i++) {
  9715. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9716. }
  9717. }
  9718. else {
  9719. s.lazy.loadImageInSlide(s.activeIndex);
  9720. }
  9721. }
  9722. if (s.params.lazyLoadingInPrevNext) {
  9723. if (s.params.slidesPerView > 1) {
  9724. // Next Slides
  9725. for (i = s.activeIndex + s.params.slidesPerView; i < s.activeIndex + s.params.slidesPerView + s.params.slidesPerView; i++) {
  9726. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9727. }
  9728. // Prev Slides
  9729. for (i = s.activeIndex - s.params.slidesPerView; i < s.activeIndex ; i++) {
  9730. if (s.slides[i]) s.lazy.loadImageInSlide(i);
  9731. }
  9732. }
  9733. else {
  9734. var nextSlide = s.wrapper.children('.' + s.params.slideNextClass);
  9735. if (nextSlide.length > 0) s.lazy.loadImageInSlide(nextSlide.index());
  9736. var prevSlide = s.wrapper.children('.' + s.params.slidePrevClass);
  9737. if (prevSlide.length > 0) s.lazy.loadImageInSlide(prevSlide.index());
  9738. }
  9739. }
  9740. },
  9741. onTransitionStart: function () {
  9742. if (s.params.lazyLoading) {
  9743. if (s.params.lazyLoadingOnTransitionStart || (!s.params.lazyLoadingOnTransitionStart && !s.lazy.initialImageLoaded)) {
  9744. s.lazy.load();
  9745. }
  9746. }
  9747. },
  9748. onTransitionEnd: function () {
  9749. if (s.params.lazyLoading && !s.params.lazyLoadingOnTransitionStart) {
  9750. s.lazy.load();
  9751. }
  9752. }
  9753. };
  9754. /*=========================
  9755. Scrollbar
  9756. ===========================*/
  9757. s.scrollbar = {
  9758. isTouched: false,
  9759. setDragPosition: function (e) {
  9760. var sb = s.scrollbar;
  9761. var x = 0, y = 0;
  9762. var translate;
  9763. var pointerPosition = isH() ?
  9764. ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageX : e.pageX || e.clientX) :
  9765. ((e.type === 'touchstart' || e.type === 'touchmove') ? e.targetTouches[0].pageY : e.pageY || e.clientY) ;
  9766. var position = (pointerPosition) - sb.track.offset()[isH() ? 'left' : 'top'] - sb.dragSize / 2;
  9767. var positionMin = -s.minTranslate() * sb.moveDivider;
  9768. var positionMax = -s.maxTranslate() * sb.moveDivider;
  9769. if (position < positionMin) {
  9770. position = positionMin;
  9771. }
  9772. else if (position > positionMax) {
  9773. position = positionMax;
  9774. }
  9775. position = -position / sb.moveDivider;
  9776. s.updateProgress(position);
  9777. s.setWrapperTranslate(position, true);
  9778. },
  9779. dragStart: function (e) {
  9780. var sb = s.scrollbar;
  9781. sb.isTouched = true;
  9782. e.preventDefault();
  9783. e.stopPropagation();
  9784. sb.setDragPosition(e);
  9785. clearTimeout(sb.dragTimeout);
  9786. sb.track.transition(0);
  9787. if (s.params.scrollbarHide) {
  9788. sb.track.css('opacity', 1);
  9789. }
  9790. s.wrapper.transition(100);
  9791. sb.drag.transition(100);
  9792. s.emit('onScrollbarDragStart', s);
  9793. },
  9794. dragMove: function (e) {
  9795. var sb = s.scrollbar;
  9796. if (!sb.isTouched) return;
  9797. if (e.preventDefault) e.preventDefault();
  9798. else e.returnValue = false;
  9799. sb.setDragPosition(e);
  9800. s.wrapper.transition(0);
  9801. sb.track.transition(0);
  9802. sb.drag.transition(0);
  9803. s.emit('onScrollbarDragMove', s);
  9804. },
  9805. dragEnd: function (e) {
  9806. var sb = s.scrollbar;
  9807. if (!sb.isTouched) return;
  9808. sb.isTouched = false;
  9809. if (s.params.scrollbarHide) {
  9810. clearTimeout(sb.dragTimeout);
  9811. sb.dragTimeout = setTimeout(function () {
  9812. sb.track.css('opacity', 0);
  9813. sb.track.transition(400);
  9814. }, 1000);
  9815. }
  9816. s.emit('onScrollbarDragEnd', s);
  9817. if (s.params.scrollbarSnapOnRelease) {
  9818. s.slideReset();
  9819. }
  9820. },
  9821. enableDraggable: function () {
  9822. var sb = s.scrollbar;
  9823. var target = s.support.touch ? sb.track : document;
  9824. $(sb.track).on(s.touchEvents.start, sb.dragStart);
  9825. $(target).on(s.touchEvents.move, sb.dragMove);
  9826. $(target).on(s.touchEvents.end, sb.dragEnd);
  9827. },
  9828. disableDraggable: function () {
  9829. var sb = s.scrollbar;
  9830. var target = s.support.touch ? sb.track : document;
  9831. $(sb.track).off(s.touchEvents.start, sb.dragStart);
  9832. $(target).off(s.touchEvents.move, sb.dragMove);
  9833. $(target).off(s.touchEvents.end, sb.dragEnd);
  9834. },
  9835. set: function () {
  9836. if (!s.params.scrollbar) return;
  9837. var sb = s.scrollbar;
  9838. sb.track = $(s.params.scrollbar);
  9839. sb.drag = sb.track.find('.swiper-scrollbar-drag');
  9840. if (sb.drag.length === 0) {
  9841. sb.drag = $('<div class="swiper-scrollbar-drag"></div>');
  9842. sb.track.append(sb.drag);
  9843. }
  9844. sb.drag[0].style.width = '';
  9845. sb.drag[0].style.height = '';
  9846. sb.trackSize = isH() ? sb.track[0].offsetWidth : sb.track[0].offsetHeight;
  9847. sb.divider = s.size / s.virtualSize;
  9848. sb.moveDivider = sb.divider * (sb.trackSize / s.size);
  9849. sb.dragSize = sb.trackSize * sb.divider;
  9850. if (isH()) {
  9851. sb.drag[0].style.width = sb.dragSize + 'px';
  9852. }
  9853. else {
  9854. sb.drag[0].style.height = sb.dragSize + 'px';
  9855. }
  9856. if (sb.divider >= 1) {
  9857. sb.track[0].style.display = 'none';
  9858. }
  9859. else {
  9860. sb.track[0].style.display = '';
  9861. }
  9862. if (s.params.scrollbarHide) {
  9863. sb.track[0].style.opacity = 0;
  9864. }
  9865. },
  9866. setTranslate: function () {
  9867. if (!s.params.scrollbar) return;
  9868. var diff;
  9869. var sb = s.scrollbar;
  9870. var translate = s.translate || 0;
  9871. var newPos;
  9872. var newSize = sb.dragSize;
  9873. newPos = (sb.trackSize - sb.dragSize) * s.progress;
  9874. if (s.rtl && isH()) {
  9875. newPos = -newPos;
  9876. if (newPos > 0) {
  9877. newSize = sb.dragSize - newPos;
  9878. newPos = 0;
  9879. }
  9880. else if (-newPos + sb.dragSize > sb.trackSize) {
  9881. newSize = sb.trackSize + newPos;
  9882. }
  9883. }
  9884. else {
  9885. if (newPos < 0) {
  9886. newSize = sb.dragSize + newPos;
  9887. newPos = 0;
  9888. }
  9889. else if (newPos + sb.dragSize > sb.trackSize) {
  9890. newSize = sb.trackSize - newPos;
  9891. }
  9892. }
  9893. if (isH()) {
  9894. if (s.support.transforms3d) {
  9895. sb.drag.transform('translate3d(' + (newPos) + 'px, 0, 0)');
  9896. }
  9897. else {
  9898. sb.drag.transform('translateX(' + (newPos) + 'px)');
  9899. }
  9900. sb.drag[0].style.width = newSize + 'px';
  9901. }
  9902. else {
  9903. if (s.support.transforms3d) {
  9904. sb.drag.transform('translate3d(0px, ' + (newPos) + 'px, 0)');
  9905. }
  9906. else {
  9907. sb.drag.transform('translateY(' + (newPos) + 'px)');
  9908. }
  9909. sb.drag[0].style.height = newSize + 'px';
  9910. }
  9911. if (s.params.scrollbarHide) {
  9912. clearTimeout(sb.timeout);
  9913. sb.track[0].style.opacity = 1;
  9914. sb.timeout = setTimeout(function () {
  9915. sb.track[0].style.opacity = 0;
  9916. sb.track.transition(400);
  9917. }, 1000);
  9918. }
  9919. },
  9920. setTransition: function (duration) {
  9921. if (!s.params.scrollbar) return;
  9922. s.scrollbar.drag.transition(duration);
  9923. }
  9924. };
  9925. /*=========================
  9926. Controller
  9927. ===========================*/
  9928. s.controller = {
  9929. LinearSpline: function (x, y) {
  9930. this.x = x;
  9931. this.y = y;
  9932. this.lastIndex = x.length - 1;
  9933. // Given an x value (x2), return the expected y2 value:
  9934. // (x1,y1) is the known point before given value,
  9935. // (x3,y3) is the known point after given value.
  9936. var i1, i3;
  9937. var l = this.x.length;
  9938. this.interpolate = function (x2) {
  9939. if (!x2) return 0;
  9940. // Get the indexes of x1 and x3 (the array indexes before and after given x2):
  9941. i3 = binarySearch(this.x, x2);
  9942. i1 = i3 - 1;
  9943. // We have our indexes i1 & i3, so we can calculate already:
  9944. // y2 := ((x2−x1) × (y3−y1)) ÷ (x3−x1) + y1
  9945. return ((x2 - this.x[i1]) * (this.y[i3] - this.y[i1])) / (this.x[i3] - this.x[i1]) + this.y[i1];
  9946. };
  9947. var binarySearch = (function() {
  9948. var maxIndex, minIndex, guess;
  9949. return function(array, val) {
  9950. minIndex = -1;
  9951. maxIndex = array.length;
  9952. while (maxIndex - minIndex > 1)
  9953. if (array[guess = maxIndex + minIndex >> 1] <= val) {
  9954. minIndex = guess;
  9955. } else {
  9956. maxIndex = guess;
  9957. }
  9958. return maxIndex;
  9959. };
  9960. })();
  9961. },
  9962. //xxx: for now i will just save one spline function to to
  9963. getInterpolateFunction: function(c){
  9964. if(!s.controller.spline) s.controller.spline = s.params.loop ?
  9965. new s.controller.LinearSpline(s.slidesGrid, c.slidesGrid) :
  9966. new s.controller.LinearSpline(s.snapGrid, c.snapGrid);
  9967. },
  9968. setTranslate: function (translate, byController) {
  9969. var controlled = s.params.control;
  9970. var multiplier, controlledTranslate;
  9971. function setControlledTranslate(c) {
  9972. // this will create an Interpolate function based on the snapGrids
  9973. // x is the Grid of the scrolled scroller and y will be the controlled scroller
  9974. // it makes sense to create this only once and recall it for the interpolation
  9975. // the function does a lot of value caching for performance
  9976. translate = c.rtl && c.params.direction === 'horizontal' ? -s.translate : s.translate;
  9977. if (s.params.controlBy === 'slide') {
  9978. s.controller.getInterpolateFunction(c);
  9979. // i am not sure why the values have to be multiplicated this way, tried to invert the snapGrid
  9980. // but it did not work out
  9981. controlledTranslate = -s.controller.spline.interpolate(-translate);
  9982. }
  9983. if(!controlledTranslate || s.params.controlBy === 'container'){
  9984. multiplier = (c.maxTranslate() - c.minTranslate()) / (s.maxTranslate() - s.minTranslate());
  9985. controlledTranslate = (translate - s.minTranslate()) * multiplier + c.minTranslate();
  9986. }
  9987. if (s.params.controlInverse) {
  9988. controlledTranslate = c.maxTranslate() - controlledTranslate;
  9989. }
  9990. c.updateProgress(controlledTranslate);
  9991. c.setWrapperTranslate(controlledTranslate, false, s);
  9992. c.updateActiveIndex();
  9993. }
  9994. if (s.isArray(controlled)) {
  9995. for (var i = 0; i < controlled.length; i++) {
  9996. if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
  9997. setControlledTranslate(controlled[i]);
  9998. }
  9999. }
  10000. }
  10001. else if (controlled instanceof Swiper && byController !== controlled) {
  10002. setControlledTranslate(controlled);
  10003. }
  10004. },
  10005. setTransition: function (duration, byController) {
  10006. var controlled = s.params.control;
  10007. var i;
  10008. function setControlledTransition(c) {
  10009. c.setWrapperTransition(duration, s);
  10010. if (duration !== 0) {
  10011. c.onTransitionStart();
  10012. c.wrapper.transitionEnd(function(){
  10013. if (!controlled) return;
  10014. if (c.params.loop && s.params.controlBy === 'slide') {
  10015. c.fixLoop();
  10016. }
  10017. c.onTransitionEnd();
  10018. });
  10019. }
  10020. }
  10021. if (s.isArray(controlled)) {
  10022. for (i = 0; i < controlled.length; i++) {
  10023. if (controlled[i] !== byController && controlled[i] instanceof Swiper) {
  10024. setControlledTransition(controlled[i]);
  10025. }
  10026. }
  10027. }
  10028. else if (controlled instanceof Swiper && byController !== controlled) {
  10029. setControlledTransition(controlled);
  10030. }
  10031. }
  10032. };
  10033. /*=========================
  10034. Hash Navigation
  10035. ===========================*/
  10036. s.hashnav = {
  10037. init: function () {
  10038. if (!s.params.hashnav) return;
  10039. s.hashnav.initialized = true;
  10040. var hash = document.location.hash.replace('#', '');
  10041. if (!hash) return;
  10042. var speed = 0;
  10043. for (var i = 0, length = s.slides.length; i < length; i++) {
  10044. var slide = s.slides.eq(i);
  10045. var slideHash = slide.attr('data-hash');
  10046. if (slideHash === hash && !slide.hasClass(s.params.slideDuplicateClass)) {
  10047. var index = slide.index();
  10048. s.slideTo(index, speed, s.params.runCallbacksOnInit, true);
  10049. }
  10050. }
  10051. },
  10052. setHash: function () {
  10053. if (!s.hashnav.initialized || !s.params.hashnav) return;
  10054. document.location.hash = s.slides.eq(s.activeIndex).attr('data-hash') || '';
  10055. }
  10056. };
  10057. /*=========================
  10058. Keyboard Control
  10059. ===========================*/
  10060. function handleKeyboard(e) {
  10061. if (e.originalEvent) e = e.originalEvent; //jquery fix
  10062. var kc = e.keyCode || e.charCode;
  10063. // Directions locks
  10064. if (!s.params.allowSwipeToNext && (isH() && kc === 39 || !isH() && kc === 40)) {
  10065. return false;
  10066. }
  10067. if (!s.params.allowSwipeToPrev && (isH() && kc === 37 || !isH() && kc === 38)) {
  10068. return false;
  10069. }
  10070. if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) {
  10071. return;
  10072. }
  10073. if (document.activeElement && document.activeElement.nodeName && (document.activeElement.nodeName.toLowerCase() === 'input' || document.activeElement.nodeName.toLowerCase() === 'textarea')) {
  10074. return;
  10075. }
  10076. if (kc === 37 || kc === 39 || kc === 38 || kc === 40) {
  10077. var inView = false;
  10078. //Check that swiper should be inside of visible area of window
  10079. if (s.container.parents('.swiper-slide').length > 0 && s.container.parents('.swiper-slide-active').length === 0) {
  10080. return;
  10081. }
  10082. var windowScroll = {
  10083. left: window.pageXOffset,
  10084. top: window.pageYOffset
  10085. };
  10086. var windowWidth = window.innerWidth;
  10087. var windowHeight = window.innerHeight;
  10088. var swiperOffset = s.container.offset();
  10089. if (s.rtl) swiperOffset.left = swiperOffset.left - s.container[0].scrollLeft;
  10090. var swiperCoord = [
  10091. [swiperOffset.left, swiperOffset.top],
  10092. [swiperOffset.left + s.width, swiperOffset.top],
  10093. [swiperOffset.left, swiperOffset.top + s.height],
  10094. [swiperOffset.left + s.width, swiperOffset.top + s.height]
  10095. ];
  10096. for (var i = 0; i < swiperCoord.length; i++) {
  10097. var point = swiperCoord[i];
  10098. if (
  10099. point[0] >= windowScroll.left && point[0] <= windowScroll.left + windowWidth &&
  10100. point[1] >= windowScroll.top && point[1] <= windowScroll.top + windowHeight
  10101. ) {
  10102. inView = true;
  10103. }
  10104. }
  10105. if (!inView) return;
  10106. }
  10107. if (isH()) {
  10108. if (kc === 37 || kc === 39) {
  10109. if (e.preventDefault) e.preventDefault();
  10110. else e.returnValue = false;
  10111. }
  10112. if ((kc === 39 && !s.rtl) || (kc === 37 && s.rtl)) s.slideNext();
  10113. if ((kc === 37 && !s.rtl) || (kc === 39 && s.rtl)) s.slidePrev();
  10114. }
  10115. else {
  10116. if (kc === 38 || kc === 40) {
  10117. if (e.preventDefault) e.preventDefault();
  10118. else e.returnValue = false;
  10119. }
  10120. if (kc === 40) s.slideNext();
  10121. if (kc === 38) s.slidePrev();
  10122. }
  10123. }
  10124. s.disableKeyboardControl = function () {
  10125. s.params.keyboardControl = false;
  10126. $(document).off('keydown', handleKeyboard);
  10127. };
  10128. s.enableKeyboardControl = function () {
  10129. s.params.keyboardControl = true;
  10130. $(document).on('keydown', handleKeyboard);
  10131. };
  10132. /*=========================
  10133. Mousewheel Control
  10134. ===========================*/
  10135. s.mousewheel = {
  10136. event: false,
  10137. lastScrollTime: (new window.Date()).getTime()
  10138. };
  10139. if (s.params.mousewheelControl) {
  10140. try {
  10141. new window.WheelEvent('wheel');
  10142. s.mousewheel.event = 'wheel';
  10143. } catch (e) {}
  10144. if (!s.mousewheel.event && document.onmousewheel !== undefined) {
  10145. s.mousewheel.event = 'mousewheel';
  10146. }
  10147. if (!s.mousewheel.event) {
  10148. s.mousewheel.event = 'DOMMouseScroll';
  10149. }
  10150. }
  10151. function handleMousewheel(e) {
  10152. if (e.originalEvent) e = e.originalEvent; //jquery fix
  10153. var we = s.mousewheel.event;
  10154. var delta = 0;
  10155. var rtlFactor = s.rtl ? -1 : 1;
  10156. //Opera & IE
  10157. if (e.detail) delta = -e.detail;
  10158. //WebKits
  10159. else if (we === 'mousewheel') {
  10160. if (s.params.mousewheelForceToAxis) {
  10161. if (isH()) {
  10162. if (Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY)) delta = e.wheelDeltaX * rtlFactor;
  10163. else return;
  10164. }
  10165. else {
  10166. if (Math.abs(e.wheelDeltaY) > Math.abs(e.wheelDeltaX)) delta = e.wheelDeltaY;
  10167. else return;
  10168. }
  10169. }
  10170. else {
  10171. delta = Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY) ? - e.wheelDeltaX * rtlFactor : - e.wheelDeltaY;
  10172. }
  10173. }
  10174. //Old FireFox
  10175. else if (we === 'DOMMouseScroll') delta = -e.detail;
  10176. //New FireFox
  10177. else if (we === 'wheel') {
  10178. if (s.params.mousewheelForceToAxis) {
  10179. if (isH()) {
  10180. if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) delta = -e.deltaX * rtlFactor;
  10181. else return;
  10182. }
  10183. else {
  10184. if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) delta = -e.deltaY;
  10185. else return;
  10186. }
  10187. }
  10188. else {
  10189. delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? - e.deltaX * rtlFactor : - e.deltaY;
  10190. }
  10191. }
  10192. if (delta === 0) return;
  10193. if (s.params.mousewheelInvert) delta = -delta;
  10194. if (!s.params.freeMode) {
  10195. if ((new window.Date()).getTime() - s.mousewheel.lastScrollTime > 60) {
  10196. if (delta < 0) {
  10197. if ((!s.isEnd || s.params.loop) && !s.animating) s.slideNext();
  10198. else if (s.params.mousewheelReleaseOnEdges) return true;
  10199. }
  10200. else {
  10201. if ((!s.isBeginning || s.params.loop) && !s.animating) s.slidePrev();
  10202. else if (s.params.mousewheelReleaseOnEdges) return true;
  10203. }
  10204. }
  10205. s.mousewheel.lastScrollTime = (new window.Date()).getTime();
  10206. }
  10207. else {
  10208. //Freemode or scrollContainer:
  10209. var position = s.getWrapperTranslate() + delta * s.params.mousewheelSensitivity;
  10210. var wasBeginning = s.isBeginning,
  10211. wasEnd = s.isEnd;
  10212. if (position >= s.minTranslate()) position = s.minTranslate();
  10213. if (position <= s.maxTranslate()) position = s.maxTranslate();
  10214. s.setWrapperTransition(0);
  10215. s.setWrapperTranslate(position);
  10216. s.updateProgress();
  10217. s.updateActiveIndex();
  10218. if (!wasBeginning && s.isBeginning || !wasEnd && s.isEnd) {
  10219. s.updateClasses();
  10220. }
  10221. if (s.params.freeModeSticky) {
  10222. clearTimeout(s.mousewheel.timeout);
  10223. s.mousewheel.timeout = setTimeout(function () {
  10224. s.slideReset();
  10225. }, 300);
  10226. }
  10227. // Return page scroll on edge positions
  10228. if (position === 0 || position === s.maxTranslate()) return;
  10229. }
  10230. if (s.params.autoplay) s.stopAutoplay();
  10231. if (e.preventDefault) e.preventDefault();
  10232. else e.returnValue = false;
  10233. return false;
  10234. }
  10235. s.disableMousewheelControl = function () {
  10236. if (!s.mousewheel.event) return false;
  10237. s.container.off(s.mousewheel.event, handleMousewheel);
  10238. return true;
  10239. };
  10240. s.enableMousewheelControl = function () {
  10241. if (!s.mousewheel.event) return false;
  10242. s.container.on(s.mousewheel.event, handleMousewheel);
  10243. return true;
  10244. };
  10245. /*=========================
  10246. Parallax
  10247. ===========================*/
  10248. function setParallaxTransform(el, progress) {
  10249. el = $(el);
  10250. var p, pX, pY;
  10251. var rtlFactor = s.rtl ? -1 : 1;
  10252. p = el.attr('data-swiper-parallax') || '0';
  10253. pX = el.attr('data-swiper-parallax-x');
  10254. pY = el.attr('data-swiper-parallax-y');
  10255. if (pX || pY) {
  10256. pX = pX || '0';
  10257. pY = pY || '0';
  10258. }
  10259. else {
  10260. if (isH()) {
  10261. pX = p;
  10262. pY = '0';
  10263. }
  10264. else {
  10265. pY = p;
  10266. pX = '0';
  10267. }
  10268. }
  10269. if ((pX).indexOf('%') >= 0) {
  10270. pX = parseInt(pX, 10) * progress * rtlFactor + '%';
  10271. }
  10272. else {
  10273. pX = pX * progress * rtlFactor + 'px' ;
  10274. }
  10275. if ((pY).indexOf('%') >= 0) {
  10276. pY = parseInt(pY, 10) * progress + '%';
  10277. }
  10278. else {
  10279. pY = pY * progress + 'px' ;
  10280. }
  10281. el.transform('translate3d(' + pX + ', ' + pY + ',0px)');
  10282. }
  10283. s.parallax = {
  10284. setTranslate: function () {
  10285. s.container.children('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){
  10286. setParallaxTransform(this, s.progress);
  10287. });
  10288. s.slides.each(function () {
  10289. var slide = $(this);
  10290. slide.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function () {
  10291. var progress = Math.min(Math.max(slide[0].progress, -1), 1);
  10292. setParallaxTransform(this, progress);
  10293. });
  10294. });
  10295. },
  10296. setTransition: function (duration) {
  10297. if (typeof duration === 'undefined') duration = s.params.speed;
  10298. s.container.find('[data-swiper-parallax], [data-swiper-parallax-x], [data-swiper-parallax-y]').each(function(){
  10299. var el = $(this);
  10300. var parallaxDuration = parseInt(el.attr('data-swiper-parallax-duration'), 10) || duration;
  10301. if (duration === 0) parallaxDuration = 0;
  10302. el.transition(parallaxDuration);
  10303. });
  10304. }
  10305. };
  10306. /*=========================
  10307. Plugins API. Collect all and init all plugins
  10308. ===========================*/
  10309. s._plugins = [];
  10310. for (var plugin in s.plugins) {
  10311. var p = s.plugins[plugin](s, s.params[plugin]);
  10312. if (p) s._plugins.push(p);
  10313. }
  10314. // Method to call all plugins event/method
  10315. s.callPlugins = function (eventName) {
  10316. for (var i = 0; i < s._plugins.length; i++) {
  10317. if (eventName in s._plugins[i]) {
  10318. s._plugins[i][eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10319. }
  10320. }
  10321. };
  10322. /*=========================
  10323. Events/Callbacks/Plugins Emitter
  10324. ===========================*/
  10325. function normalizeEventName (eventName) {
  10326. if (eventName.indexOf('on') !== 0) {
  10327. if (eventName[0] !== eventName[0].toUpperCase()) {
  10328. eventName = 'on' + eventName[0].toUpperCase() + eventName.substring(1);
  10329. }
  10330. else {
  10331. eventName = 'on' + eventName;
  10332. }
  10333. }
  10334. return eventName;
  10335. }
  10336. s.emitterEventListeners = {
  10337. };
  10338. s.emit = function (eventName) {
  10339. // Trigger callbacks
  10340. if (s.params[eventName]) {
  10341. s.params[eventName](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10342. }
  10343. var i;
  10344. // Trigger events
  10345. if (s.emitterEventListeners[eventName]) {
  10346. for (i = 0; i < s.emitterEventListeners[eventName].length; i++) {
  10347. s.emitterEventListeners[eventName][i](arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10348. }
  10349. }
  10350. // Trigger plugins
  10351. if (s.callPlugins) s.callPlugins(eventName, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5]);
  10352. };
  10353. s.on = function (eventName, handler) {
  10354. eventName = normalizeEventName(eventName);
  10355. if (!s.emitterEventListeners[eventName]) s.emitterEventListeners[eventName] = [];
  10356. s.emitterEventListeners[eventName].push(handler);
  10357. return s;
  10358. };
  10359. s.off = function (eventName, handler) {
  10360. var i;
  10361. eventName = normalizeEventName(eventName);
  10362. if (typeof handler === 'undefined') {
  10363. // Remove all handlers for such event
  10364. s.emitterEventListeners[eventName] = [];
  10365. return s;
  10366. }
  10367. if (!s.emitterEventListeners[eventName] || s.emitterEventListeners[eventName].length === 0) return;
  10368. for (i = 0; i < s.emitterEventListeners[eventName].length; i++) {
  10369. if(s.emitterEventListeners[eventName][i] === handler) s.emitterEventListeners[eventName].splice(i, 1);
  10370. }
  10371. return s;
  10372. };
  10373. s.once = function (eventName, handler) {
  10374. eventName = normalizeEventName(eventName);
  10375. var _handler = function () {
  10376. handler(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
  10377. s.off(eventName, _handler);
  10378. };
  10379. s.on(eventName, _handler);
  10380. return s;
  10381. };
  10382. // Accessibility tools
  10383. s.a11y = {
  10384. makeFocusable: function ($el) {
  10385. $el.attr('tabIndex', '0');
  10386. return $el;
  10387. },
  10388. addRole: function ($el, role) {
  10389. $el.attr('role', role);
  10390. return $el;
  10391. },
  10392. addLabel: function ($el, label) {
  10393. $el.attr('aria-label', label);
  10394. return $el;
  10395. },
  10396. disable: function ($el) {
  10397. $el.attr('aria-disabled', true);
  10398. return $el;
  10399. },
  10400. enable: function ($el) {
  10401. $el.attr('aria-disabled', false);
  10402. return $el;
  10403. },
  10404. onEnterKey: function (event) {
  10405. if (event.keyCode !== 13) return;
  10406. if ($(event.target).is(s.params.nextButton)) {
  10407. s.onClickNext(event);
  10408. if (s.isEnd) {
  10409. s.a11y.notify(s.params.lastSlideMessage);
  10410. }
  10411. else {
  10412. s.a11y.notify(s.params.nextSlideMessage);
  10413. }
  10414. }
  10415. else if ($(event.target).is(s.params.prevButton)) {
  10416. s.onClickPrev(event);
  10417. if (s.isBeginning) {
  10418. s.a11y.notify(s.params.firstSlideMessage);
  10419. }
  10420. else {
  10421. s.a11y.notify(s.params.prevSlideMessage);
  10422. }
  10423. }
  10424. if ($(event.target).is('.' + s.params.bulletClass)) {
  10425. $(event.target)[0].click();
  10426. }
  10427. },
  10428. liveRegion: $('<span class="swiper-notification" aria-live="assertive" aria-atomic="true"></span>'),
  10429. notify: function (message) {
  10430. var notification = s.a11y.liveRegion;
  10431. if (notification.length === 0) return;
  10432. notification.html('');
  10433. notification.html(message);
  10434. },
  10435. init: function () {
  10436. // Setup accessibility
  10437. if (s.params.nextButton) {
  10438. var nextButton = $(s.params.nextButton);
  10439. s.a11y.makeFocusable(nextButton);
  10440. s.a11y.addRole(nextButton, 'button');
  10441. s.a11y.addLabel(nextButton, s.params.nextSlideMessage);
  10442. }
  10443. if (s.params.prevButton) {
  10444. var prevButton = $(s.params.prevButton);
  10445. s.a11y.makeFocusable(prevButton);
  10446. s.a11y.addRole(prevButton, 'button');
  10447. s.a11y.addLabel(prevButton, s.params.prevSlideMessage);
  10448. }
  10449. $(s.container).append(s.a11y.liveRegion);
  10450. },
  10451. initPagination: function () {
  10452. if (s.params.pagination && s.params.paginationClickable && s.bullets && s.bullets.length) {
  10453. s.bullets.each(function () {
  10454. var bullet = $(this);
  10455. s.a11y.makeFocusable(bullet);
  10456. s.a11y.addRole(bullet, 'button');
  10457. s.a11y.addLabel(bullet, s.params.paginationBulletMessage.replace(/{{index}}/, bullet.index() + 1));
  10458. });
  10459. }
  10460. },
  10461. destroy: function () {
  10462. if (s.a11y.liveRegion && s.a11y.liveRegion.length > 0) s.a11y.liveRegion.remove();
  10463. }
  10464. };
  10465. /*=========================
  10466. Init/Destroy
  10467. ===========================*/
  10468. s.init = function () {
  10469. if (s.params.loop) s.createLoop();
  10470. s.updateContainerSize();
  10471. s.updateSlidesSize();
  10472. s.updatePagination();
  10473. if (s.params.scrollbar && s.scrollbar) {
  10474. s.scrollbar.set();
  10475. if (s.params.scrollbarDraggable) {
  10476. s.scrollbar.enableDraggable();
  10477. }
  10478. }
  10479. if (s.params.effect !== 'slide' && s.effects[s.params.effect]) {
  10480. if (!s.params.loop) s.updateProgress();
  10481. s.effects[s.params.effect].setTranslate();
  10482. }
  10483. if (s.params.loop) {
  10484. s.slideTo(s.params.initialSlide + s.loopedSlides, 0, s.params.runCallbacksOnInit);
  10485. }
  10486. else {
  10487. s.slideTo(s.params.initialSlide, 0, s.params.runCallbacksOnInit);
  10488. if (s.params.initialSlide === 0) {
  10489. if (s.parallax && s.params.parallax) s.parallax.setTranslate();
  10490. if (s.lazy && s.params.lazyLoading) {
  10491. s.lazy.load();
  10492. s.lazy.initialImageLoaded = true;
  10493. }
  10494. }
  10495. }
  10496. s.attachEvents();
  10497. if (s.params.observer && s.support.observer) {
  10498. s.initObservers();
  10499. }
  10500. if (s.params.preloadImages && !s.params.lazyLoading) {
  10501. s.preloadImages();
  10502. }
  10503. if (s.params.autoplay) {
  10504. s.startAutoplay();
  10505. }
  10506. if (s.params.keyboardControl) {
  10507. if (s.enableKeyboardControl) s.enableKeyboardControl();
  10508. }
  10509. if (s.params.mousewheelControl) {
  10510. if (s.enableMousewheelControl) s.enableMousewheelControl();
  10511. }
  10512. if (s.params.hashnav) {
  10513. if (s.hashnav) s.hashnav.init();
  10514. }
  10515. if (s.params.a11y && s.a11y) s.a11y.init();
  10516. s.emit('onInit', s);
  10517. };
  10518. // Cleanup dynamic styles
  10519. s.cleanupStyles = function () {
  10520. // Container
  10521. s.container.removeClass(s.classNames.join(' ')).removeAttr('style');
  10522. // Wrapper
  10523. s.wrapper.removeAttr('style');
  10524. // Slides
  10525. if (s.slides && s.slides.length) {
  10526. s.slides
  10527. .removeClass([
  10528. s.params.slideVisibleClass,
  10529. s.params.slideActiveClass,
  10530. s.params.slideNextClass,
  10531. s.params.slidePrevClass
  10532. ].join(' '))
  10533. .removeAttr('style')
  10534. .removeAttr('data-swiper-column')
  10535. .removeAttr('data-swiper-row');
  10536. }
  10537. // Pagination/Bullets
  10538. if (s.paginationContainer && s.paginationContainer.length) {
  10539. s.paginationContainer.removeClass(s.params.paginationHiddenClass);
  10540. }
  10541. if (s.bullets && s.bullets.length) {
  10542. s.bullets.removeClass(s.params.bulletActiveClass);
  10543. }
  10544. // Buttons
  10545. if (s.params.prevButton) $(s.params.prevButton).removeClass(s.params.buttonDisabledClass);
  10546. if (s.params.nextButton) $(s.params.nextButton).removeClass(s.params.buttonDisabledClass);
  10547. // Scrollbar
  10548. if (s.params.scrollbar && s.scrollbar) {
  10549. if (s.scrollbar.track && s.scrollbar.track.length) s.scrollbar.track.removeAttr('style');
  10550. if (s.scrollbar.drag && s.scrollbar.drag.length) s.scrollbar.drag.removeAttr('style');
  10551. }
  10552. };
  10553. // Destroy
  10554. s.destroy = function (deleteInstance, cleanupStyles) {
  10555. // Detach evebts
  10556. s.detachEvents();
  10557. // Stop autoplay
  10558. s.stopAutoplay();
  10559. // Disable draggable
  10560. if (s.params.scrollbar && s.scrollbar) {
  10561. if (s.params.scrollbarDraggable) {
  10562. s.scrollbar.disableDraggable();
  10563. }
  10564. }
  10565. // Destroy loop
  10566. if (s.params.loop) {
  10567. s.destroyLoop();
  10568. }
  10569. // Cleanup styles
  10570. if (cleanupStyles) {
  10571. s.cleanupStyles();
  10572. }
  10573. // Disconnect observer
  10574. s.disconnectObservers();
  10575. // Disable keyboard/mousewheel
  10576. if (s.params.keyboardControl) {
  10577. if (s.disableKeyboardControl) s.disableKeyboardControl();
  10578. }
  10579. if (s.params.mousewheelControl) {
  10580. if (s.disableMousewheelControl) s.disableMousewheelControl();
  10581. }
  10582. // Disable a11y
  10583. if (s.params.a11y && s.a11y) s.a11y.destroy();
  10584. // Destroy callback
  10585. s.emit('onDestroy');
  10586. // Delete instance
  10587. if (deleteInstance !== false) s = null;
  10588. };
  10589. s.init();
  10590. // Return swiper instance
  10591. return s;
  10592. };
  10593. /*==================================================
  10594. Prototype
  10595. ====================================================*/
  10596. Swiper.prototype = {
  10597. isSafari: (function () {
  10598. var ua = navigator.userAgent.toLowerCase();
  10599. return (ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0 && ua.indexOf('android') < 0);
  10600. })(),
  10601. isUiWebView: /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent),
  10602. isArray: function (arr) {
  10603. return Object.prototype.toString.apply(arr) === '[object Array]';
  10604. },
  10605. /*==================================================
  10606. Browser
  10607. ====================================================*/
  10608. browser: {
  10609. ie: window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
  10610. ieTouch: (window.navigator.msPointerEnabled && window.navigator.msMaxTouchPoints > 1) || (window.navigator.pointerEnabled && window.navigator.maxTouchPoints > 1)
  10611. },
  10612. /*==================================================
  10613. Devices
  10614. ====================================================*/
  10615. device: (function () {
  10616. var ua = navigator.userAgent;
  10617. var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  10618. var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  10619. var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  10620. var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  10621. return {
  10622. ios: ipad || iphone || ipod,
  10623. android: android
  10624. };
  10625. })(),
  10626. /*==================================================
  10627. Feature Detection
  10628. ====================================================*/
  10629. support: {
  10630. touch : (window.Modernizr && Modernizr.touch === true) || (function () {
  10631. return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
  10632. })(),
  10633. transforms3d : (window.Modernizr && Modernizr.csstransforms3d === true) || (function () {
  10634. var div = document.createElement('div').style;
  10635. return ('webkitPerspective' in div || 'MozPerspective' in div || 'OPerspective' in div || 'MsPerspective' in div || 'perspective' in div);
  10636. })(),
  10637. flexbox: (function () {
  10638. var div = document.createElement('div').style;
  10639. var styles = ('alignItems webkitAlignItems webkitBoxAlign msFlexAlign mozBoxAlign webkitFlexDirection msFlexDirection mozBoxDirection mozBoxOrient webkitBoxDirection webkitBoxOrient').split(' ');
  10640. for (var i = 0; i < styles.length; i++) {
  10641. if (styles[i] in div) return true;
  10642. }
  10643. })(),
  10644. observer: (function () {
  10645. return ('MutationObserver' in window || 'WebkitMutationObserver' in window);
  10646. })()
  10647. },
  10648. /*==================================================
  10649. Plugins
  10650. ====================================================*/
  10651. plugins: {}
  10652. };
  10653. /*===========================
  10654. Dom7 Library
  10655. ===========================*/
  10656. var Dom7 = (function () {
  10657. var Dom7 = function (arr) {
  10658. var _this = this, i = 0;
  10659. // Create array-like object
  10660. for (i = 0; i < arr.length; i++) {
  10661. _this[i] = arr[i];
  10662. }
  10663. _this.length = arr.length;
  10664. // Return collection with methods
  10665. return this;
  10666. };
  10667. var $ = function (selector, context) {
  10668. var arr = [], i = 0;
  10669. if (selector && !context) {
  10670. if (selector instanceof Dom7) {
  10671. return selector;
  10672. }
  10673. }
  10674. if (selector) {
  10675. // String
  10676. if (typeof selector === 'string') {
  10677. var els, tempParent, html = selector.trim();
  10678. if (html.indexOf('<') >= 0 && html.indexOf('>') >= 0) {
  10679. var toCreate = 'div';
  10680. if (html.indexOf('<li') === 0) toCreate = 'ul';
  10681. if (html.indexOf('<tr') === 0) toCreate = 'tbody';
  10682. if (html.indexOf('<td') === 0 || html.indexOf('<th') === 0) toCreate = 'tr';
  10683. if (html.indexOf('<tbody') === 0) toCreate = 'table';
  10684. if (html.indexOf('<option') === 0) toCreate = 'select';
  10685. tempParent = document.createElement(toCreate);
  10686. tempParent.innerHTML = selector;
  10687. for (i = 0; i < tempParent.childNodes.length; i++) {
  10688. arr.push(tempParent.childNodes[i]);
  10689. }
  10690. }
  10691. else {
  10692. if (!context && selector[0] === '#' && !selector.match(/[ .<>:~]/)) {
  10693. // Pure ID selector
  10694. els = [document.getElementById(selector.split('#')[1])];
  10695. }
  10696. else {
  10697. // Other selectors
  10698. els = (context || document).querySelectorAll(selector);
  10699. }
  10700. for (i = 0; i < els.length; i++) {
  10701. if (els[i]) arr.push(els[i]);
  10702. }
  10703. }
  10704. }
  10705. // Node/element
  10706. else if (selector.nodeType || selector === window || selector === document) {
  10707. arr.push(selector);
  10708. }
  10709. //Array of elements or instance of Dom
  10710. else if (selector.length > 0 && selector[0].nodeType) {
  10711. for (i = 0; i < selector.length; i++) {
  10712. arr.push(selector[i]);
  10713. }
  10714. }
  10715. }
  10716. return new Dom7(arr);
  10717. };
  10718. Dom7.prototype = {
  10719. // Classes and attriutes
  10720. addClass: function (className) {
  10721. if (typeof className === 'undefined') {
  10722. return this;
  10723. }
  10724. var classes = className.split(' ');
  10725. for (var i = 0; i < classes.length; i++) {
  10726. for (var j = 0; j < this.length; j++) {
  10727. this[j].classList.add(classes[i]);
  10728. }
  10729. }
  10730. return this;
  10731. },
  10732. removeClass: function (className) {
  10733. var classes = className.split(' ');
  10734. for (var i = 0; i < classes.length; i++) {
  10735. for (var j = 0; j < this.length; j++) {
  10736. this[j].classList.remove(classes[i]);
  10737. }
  10738. }
  10739. return this;
  10740. },
  10741. hasClass: function (className) {
  10742. if (!this[0]) return false;
  10743. else return this[0].classList.contains(className);
  10744. },
  10745. toggleClass: function (className) {
  10746. var classes = className.split(' ');
  10747. for (var i = 0; i < classes.length; i++) {
  10748. for (var j = 0; j < this.length; j++) {
  10749. this[j].classList.toggle(classes[i]);
  10750. }
  10751. }
  10752. return this;
  10753. },
  10754. attr: function (attrs, value) {
  10755. if (arguments.length === 1 && typeof attrs === 'string') {
  10756. // Get attr
  10757. if (this[0]) return this[0].getAttribute(attrs);
  10758. else return undefined;
  10759. }
  10760. else {
  10761. // Set attrs
  10762. for (var i = 0; i < this.length; i++) {
  10763. if (arguments.length === 2) {
  10764. // String
  10765. this[i].setAttribute(attrs, value);
  10766. }
  10767. else {
  10768. // Object
  10769. for (var attrName in attrs) {
  10770. this[i][attrName] = attrs[attrName];
  10771. this[i].setAttribute(attrName, attrs[attrName]);
  10772. }
  10773. }
  10774. }
  10775. return this;
  10776. }
  10777. },
  10778. removeAttr: function (attr) {
  10779. for (var i = 0; i < this.length; i++) {
  10780. this[i].removeAttribute(attr);
  10781. }
  10782. return this;
  10783. },
  10784. data: function (key, value) {
  10785. if (typeof value === 'undefined') {
  10786. // Get value
  10787. if (this[0]) {
  10788. var dataKey = this[0].getAttribute('data-' + key);
  10789. if (dataKey) return dataKey;
  10790. else if (this[0].dom7ElementDataStorage && (key in this[0].dom7ElementDataStorage)) return this[0].dom7ElementDataStorage[key];
  10791. else return undefined;
  10792. }
  10793. else return undefined;
  10794. }
  10795. else {
  10796. // Set value
  10797. for (var i = 0; i < this.length; i++) {
  10798. var el = this[i];
  10799. if (!el.dom7ElementDataStorage) el.dom7ElementDataStorage = {};
  10800. el.dom7ElementDataStorage[key] = value;
  10801. }
  10802. return this;
  10803. }
  10804. },
  10805. // Transforms
  10806. transform : function (transform) {
  10807. for (var i = 0; i < this.length; i++) {
  10808. var elStyle = this[i].style;
  10809. elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
  10810. }
  10811. return this;
  10812. },
  10813. transition: function (duration) {
  10814. if (typeof duration !== 'string') {
  10815. duration = duration + 'ms';
  10816. }
  10817. for (var i = 0; i < this.length; i++) {
  10818. var elStyle = this[i].style;
  10819. elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
  10820. }
  10821. return this;
  10822. },
  10823. //Events
  10824. on: function (eventName, targetSelector, listener, capture) {
  10825. function handleLiveEvent(e) {
  10826. var target = e.target;
  10827. if ($(target).is(targetSelector)) listener.call(target, e);
  10828. else {
  10829. var parents = $(target).parents();
  10830. for (var k = 0; k < parents.length; k++) {
  10831. if ($(parents[k]).is(targetSelector)) listener.call(parents[k], e);
  10832. }
  10833. }
  10834. }
  10835. var events = eventName.split(' ');
  10836. var i, j;
  10837. for (i = 0; i < this.length; i++) {
  10838. if (typeof targetSelector === 'function' || targetSelector === false) {
  10839. // Usual events
  10840. if (typeof targetSelector === 'function') {
  10841. listener = arguments[1];
  10842. capture = arguments[2] || false;
  10843. }
  10844. for (j = 0; j < events.length; j++) {
  10845. this[i].addEventListener(events[j], listener, capture);
  10846. }
  10847. }
  10848. else {
  10849. //Live events
  10850. for (j = 0; j < events.length; j++) {
  10851. if (!this[i].dom7LiveListeners) this[i].dom7LiveListeners = [];
  10852. this[i].dom7LiveListeners.push({listener: listener, liveListener: handleLiveEvent});
  10853. this[i].addEventListener(events[j], handleLiveEvent, capture);
  10854. }
  10855. }
  10856. }
  10857. return this;
  10858. },
  10859. off: function (eventName, targetSelector, listener, capture) {
  10860. var events = eventName.split(' ');
  10861. for (var i = 0; i < events.length; i++) {
  10862. for (var j = 0; j < this.length; j++) {
  10863. if (typeof targetSelector === 'function' || targetSelector === false) {
  10864. // Usual events
  10865. if (typeof targetSelector === 'function') {
  10866. listener = arguments[1];
  10867. capture = arguments[2] || false;
  10868. }
  10869. this[j].removeEventListener(events[i], listener, capture);
  10870. }
  10871. else {
  10872. // Live event
  10873. if (this[j].dom7LiveListeners) {
  10874. for (var k = 0; k < this[j].dom7LiveListeners.length; k++) {
  10875. if (this[j].dom7LiveListeners[k].listener === listener) {
  10876. this[j].removeEventListener(events[i], this[j].dom7LiveListeners[k].liveListener, capture);
  10877. }
  10878. }
  10879. }
  10880. }
  10881. }
  10882. }
  10883. return this;
  10884. },
  10885. once: function (eventName, targetSelector, listener, capture) {
  10886. var dom = this;
  10887. if (typeof targetSelector === 'function') {
  10888. targetSelector = false;
  10889. listener = arguments[1];
  10890. capture = arguments[2];
  10891. }
  10892. function proxy(e) {
  10893. listener(e);
  10894. dom.off(eventName, targetSelector, proxy, capture);
  10895. }
  10896. dom.on(eventName, targetSelector, proxy, capture);
  10897. },
  10898. trigger: function (eventName, eventData) {
  10899. for (var i = 0; i < this.length; i++) {
  10900. var evt;
  10901. try {
  10902. evt = new window.CustomEvent(eventName, {detail: eventData, bubbles: true, cancelable: true});
  10903. }
  10904. catch (e) {
  10905. evt = document.createEvent('Event');
  10906. evt.initEvent(eventName, true, true);
  10907. evt.detail = eventData;
  10908. }
  10909. this[i].dispatchEvent(evt);
  10910. }
  10911. return this;
  10912. },
  10913. transitionEnd: function (callback) {
  10914. var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
  10915. i, j, dom = this;
  10916. function fireCallBack(e) {
  10917. /*jshint validthis:true */
  10918. if (e.target !== this) return;
  10919. callback.call(this, e);
  10920. for (i = 0; i < events.length; i++) {
  10921. dom.off(events[i], fireCallBack);
  10922. }
  10923. }
  10924. if (callback) {
  10925. for (i = 0; i < events.length; i++) {
  10926. dom.on(events[i], fireCallBack);
  10927. }
  10928. }
  10929. return this;
  10930. },
  10931. // Sizing/Styles
  10932. width: function () {
  10933. if (this[0] === window) {
  10934. return window.innerWidth;
  10935. }
  10936. else {
  10937. if (this.length > 0) {
  10938. return parseFloat(this.css('width'));
  10939. }
  10940. else {
  10941. return null;
  10942. }
  10943. }
  10944. },
  10945. outerWidth: function (includeMargins) {
  10946. if (this.length > 0) {
  10947. if (includeMargins)
  10948. return this[0].offsetWidth + parseFloat(this.css('margin-right')) + parseFloat(this.css('margin-left'));
  10949. else
  10950. return this[0].offsetWidth;
  10951. }
  10952. else return null;
  10953. },
  10954. height: function () {
  10955. if (this[0] === window) {
  10956. return window.innerHeight;
  10957. }
  10958. else {
  10959. if (this.length > 0) {
  10960. return parseFloat(this.css('height'));
  10961. }
  10962. else {
  10963. return null;
  10964. }
  10965. }
  10966. },
  10967. outerHeight: function (includeMargins) {
  10968. if (this.length > 0) {
  10969. if (includeMargins)
  10970. return this[0].offsetHeight + parseFloat(this.css('margin-top')) + parseFloat(this.css('margin-bottom'));
  10971. else
  10972. return this[0].offsetHeight;
  10973. }
  10974. else return null;
  10975. },
  10976. offset: function () {
  10977. if (this.length > 0) {
  10978. var el = this[0];
  10979. var box = el.getBoundingClientRect();
  10980. var body = document.body;
  10981. var clientTop = el.clientTop || body.clientTop || 0;
  10982. var clientLeft = el.clientLeft || body.clientLeft || 0;
  10983. var scrollTop = window.pageYOffset || el.scrollTop;
  10984. var scrollLeft = window.pageXOffset || el.scrollLeft;
  10985. return {
  10986. top: box.top + scrollTop - clientTop,
  10987. left: box.left + scrollLeft - clientLeft
  10988. };
  10989. }
  10990. else {
  10991. return null;
  10992. }
  10993. },
  10994. css: function (props, value) {
  10995. var i;
  10996. if (arguments.length === 1) {
  10997. if (typeof props === 'string') {
  10998. if (this[0]) return window.getComputedStyle(this[0], null).getPropertyValue(props);
  10999. }
  11000. else {
  11001. for (i = 0; i < this.length; i++) {
  11002. for (var prop in props) {
  11003. this[i].style[prop] = props[prop];
  11004. }
  11005. }
  11006. return this;
  11007. }
  11008. }
  11009. if (arguments.length === 2 && typeof props === 'string') {
  11010. for (i = 0; i < this.length; i++) {
  11011. this[i].style[props] = value;
  11012. }
  11013. return this;
  11014. }
  11015. return this;
  11016. },
  11017. //Dom manipulation
  11018. each: function (callback) {
  11019. for (var i = 0; i < this.length; i++) {
  11020. callback.call(this[i], i, this[i]);
  11021. }
  11022. return this;
  11023. },
  11024. html: function (html) {
  11025. if (typeof html === 'undefined') {
  11026. return this[0] ? this[0].innerHTML : undefined;
  11027. }
  11028. else {
  11029. for (var i = 0; i < this.length; i++) {
  11030. this[i].innerHTML = html;
  11031. }
  11032. return this;
  11033. }
  11034. },
  11035. is: function (selector) {
  11036. if (!this[0]) return false;
  11037. var compareWith, i;
  11038. if (typeof selector === 'string') {
  11039. var el = this[0];
  11040. if (el === document) return selector === document;
  11041. if (el === window) return selector === window;
  11042. if (el.matches) return el.matches(selector);
  11043. else if (el.webkitMatchesSelector) return el.webkitMatchesSelector(selector);
  11044. else if (el.mozMatchesSelector) return el.mozMatchesSelector(selector);
  11045. else if (el.msMatchesSelector) return el.msMatchesSelector(selector);
  11046. else {
  11047. compareWith = $(selector);
  11048. for (i = 0; i < compareWith.length; i++) {
  11049. if (compareWith[i] === this[0]) return true;
  11050. }
  11051. return false;
  11052. }
  11053. }
  11054. else if (selector === document) return this[0] === document;
  11055. else if (selector === window) return this[0] === window;
  11056. else {
  11057. if (selector.nodeType || selector instanceof Dom7) {
  11058. compareWith = selector.nodeType ? [selector] : selector;
  11059. for (i = 0; i < compareWith.length; i++) {
  11060. if (compareWith[i] === this[0]) return true;
  11061. }
  11062. return false;
  11063. }
  11064. return false;
  11065. }
  11066. },
  11067. index: function () {
  11068. if (this[0]) {
  11069. var child = this[0];
  11070. var i = 0;
  11071. while ((child = child.previousSibling) !== null) {
  11072. if (child.nodeType === 1) i++;
  11073. }
  11074. return i;
  11075. }
  11076. else return undefined;
  11077. },
  11078. eq: function (index) {
  11079. if (typeof index === 'undefined') return this;
  11080. var length = this.length;
  11081. var returnIndex;
  11082. if (index > length - 1) {
  11083. return new Dom7([]);
  11084. }
  11085. if (index < 0) {
  11086. returnIndex = length + index;
  11087. if (returnIndex < 0) return new Dom7([]);
  11088. else return new Dom7([this[returnIndex]]);
  11089. }
  11090. return new Dom7([this[index]]);
  11091. },
  11092. append: function (newChild) {
  11093. var i, j;
  11094. for (i = 0; i < this.length; i++) {
  11095. if (typeof newChild === 'string') {
  11096. var tempDiv = document.createElement('div');
  11097. tempDiv.innerHTML = newChild;
  11098. while (tempDiv.firstChild) {
  11099. this[i].appendChild(tempDiv.firstChild);
  11100. }
  11101. }
  11102. else if (newChild instanceof Dom7) {
  11103. for (j = 0; j < newChild.length; j++) {
  11104. this[i].appendChild(newChild[j]);
  11105. }
  11106. }
  11107. else {
  11108. this[i].appendChild(newChild);
  11109. }
  11110. }
  11111. return this;
  11112. },
  11113. prepend: function (newChild) {
  11114. var i, j;
  11115. for (i = 0; i < this.length; i++) {
  11116. if (typeof newChild === 'string') {
  11117. var tempDiv = document.createElement('div');
  11118. tempDiv.innerHTML = newChild;
  11119. for (j = tempDiv.childNodes.length - 1; j >= 0; j--) {
  11120. this[i].insertBefore(tempDiv.childNodes[j], this[i].childNodes[0]);
  11121. }
  11122. // this[i].insertAdjacentHTML('afterbegin', newChild);
  11123. }
  11124. else if (newChild instanceof Dom7) {
  11125. for (j = 0; j < newChild.length; j++) {
  11126. this[i].insertBefore(newChild[j], this[i].childNodes[0]);
  11127. }
  11128. }
  11129. else {
  11130. this[i].insertBefore(newChild, this[i].childNodes[0]);
  11131. }
  11132. }
  11133. return this;
  11134. },
  11135. insertBefore: function (selector) {
  11136. var before = $(selector);
  11137. for (var i = 0; i < this.length; i++) {
  11138. if (before.length === 1) {
  11139. before[0].parentNode.insertBefore(this[i], before[0]);
  11140. }
  11141. else if (before.length > 1) {
  11142. for (var j = 0; j < before.length; j++) {
  11143. before[j].parentNode.insertBefore(this[i].cloneNode(true), before[j]);
  11144. }
  11145. }
  11146. }
  11147. },
  11148. insertAfter: function (selector) {
  11149. var after = $(selector);
  11150. for (var i = 0; i < this.length; i++) {
  11151. if (after.length === 1) {
  11152. after[0].parentNode.insertBefore(this[i], after[0].nextSibling);
  11153. }
  11154. else if (after.length > 1) {
  11155. for (var j = 0; j < after.length; j++) {
  11156. after[j].parentNode.insertBefore(this[i].cloneNode(true), after[j].nextSibling);
  11157. }
  11158. }
  11159. }
  11160. },
  11161. next: function (selector) {
  11162. if (this.length > 0) {
  11163. if (selector) {
  11164. if (this[0].nextElementSibling && $(this[0].nextElementSibling).is(selector)) return new Dom7([this[0].nextElementSibling]);
  11165. else return new Dom7([]);
  11166. }
  11167. else {
  11168. if (this[0].nextElementSibling) return new Dom7([this[0].nextElementSibling]);
  11169. else return new Dom7([]);
  11170. }
  11171. }
  11172. else return new Dom7([]);
  11173. },
  11174. nextAll: function (selector) {
  11175. var nextEls = [];
  11176. var el = this[0];
  11177. if (!el) return new Dom7([]);
  11178. while (el.nextElementSibling) {
  11179. var next = el.nextElementSibling;
  11180. if (selector) {
  11181. if($(next).is(selector)) nextEls.push(next);
  11182. }
  11183. else nextEls.push(next);
  11184. el = next;
  11185. }
  11186. return new Dom7(nextEls);
  11187. },
  11188. prev: function (selector) {
  11189. if (this.length > 0) {
  11190. if (selector) {
  11191. if (this[0].previousElementSibling && $(this[0].previousElementSibling).is(selector)) return new Dom7([this[0].previousElementSibling]);
  11192. else return new Dom7([]);
  11193. }
  11194. else {
  11195. if (this[0].previousElementSibling) return new Dom7([this[0].previousElementSibling]);
  11196. else return new Dom7([]);
  11197. }
  11198. }
  11199. else return new Dom7([]);
  11200. },
  11201. prevAll: function (selector) {
  11202. var prevEls = [];
  11203. var el = this[0];
  11204. if (!el) return new Dom7([]);
  11205. while (el.previousElementSibling) {
  11206. var prev = el.previousElementSibling;
  11207. if (selector) {
  11208. if($(prev).is(selector)) prevEls.push(prev);
  11209. }
  11210. else prevEls.push(prev);
  11211. el = prev;
  11212. }
  11213. return new Dom7(prevEls);
  11214. },
  11215. parent: function (selector) {
  11216. var parents = [];
  11217. for (var i = 0; i < this.length; i++) {
  11218. if (selector) {
  11219. if ($(this[i].parentNode).is(selector)) parents.push(this[i].parentNode);
  11220. }
  11221. else {
  11222. parents.push(this[i].parentNode);
  11223. }
  11224. }
  11225. return $($.unique(parents));
  11226. },
  11227. parents: function (selector) {
  11228. var parents = [];
  11229. for (var i = 0; i < this.length; i++) {
  11230. var parent = this[i].parentNode;
  11231. while (parent) {
  11232. if (selector) {
  11233. if ($(parent).is(selector)) parents.push(parent);
  11234. }
  11235. else {
  11236. parents.push(parent);
  11237. }
  11238. parent = parent.parentNode;
  11239. }
  11240. }
  11241. return $($.unique(parents));
  11242. },
  11243. find : function (selector) {
  11244. var foundElements = [];
  11245. for (var i = 0; i < this.length; i++) {
  11246. var found = this[i].querySelectorAll(selector);
  11247. for (var j = 0; j < found.length; j++) {
  11248. foundElements.push(found[j]);
  11249. }
  11250. }
  11251. return new Dom7(foundElements);
  11252. },
  11253. children: function (selector) {
  11254. var children = [];
  11255. for (var i = 0; i < this.length; i++) {
  11256. var childNodes = this[i].childNodes;
  11257. for (var j = 0; j < childNodes.length; j++) {
  11258. if (!selector) {
  11259. if (childNodes[j].nodeType === 1) children.push(childNodes[j]);
  11260. }
  11261. else {
  11262. if (childNodes[j].nodeType === 1 && $(childNodes[j]).is(selector)) children.push(childNodes[j]);
  11263. }
  11264. }
  11265. }
  11266. return new Dom7($.unique(children));
  11267. },
  11268. remove: function () {
  11269. for (var i = 0; i < this.length; i++) {
  11270. if (this[i].parentNode) this[i].parentNode.removeChild(this[i]);
  11271. }
  11272. return this;
  11273. },
  11274. add: function () {
  11275. var dom = this;
  11276. var i, j;
  11277. for (i = 0; i < arguments.length; i++) {
  11278. var toAdd = $(arguments[i]);
  11279. for (j = 0; j < toAdd.length; j++) {
  11280. dom[dom.length] = toAdd[j];
  11281. dom.length++;
  11282. }
  11283. }
  11284. return dom;
  11285. }
  11286. };
  11287. $.fn = Dom7.prototype;
  11288. $.unique = function (arr) {
  11289. var unique = [];
  11290. for (var i = 0; i < arr.length; i++) {
  11291. if (unique.indexOf(arr[i]) === -1) unique.push(arr[i]);
  11292. }
  11293. return unique;
  11294. };
  11295. return $;
  11296. })();
  11297. /*===========================
  11298. Get Dom libraries
  11299. ===========================*/
  11300. var swiperDomPlugins = ['jQuery', 'Zepto', 'Dom7'];
  11301. for (var i = 0; i < swiperDomPlugins.length; i++) {
  11302. if (window[swiperDomPlugins[i]]) {
  11303. addLibraryPlugin(window[swiperDomPlugins[i]]);
  11304. }
  11305. }
  11306. // Required DOM Plugins
  11307. var domLib;
  11308. if (typeof Dom7 === 'undefined') {
  11309. domLib = window.Dom7 || window.Zepto || window.jQuery;
  11310. }
  11311. else {
  11312. domLib = Dom7;
  11313. }
  11314. /*===========================
  11315. Add .swiper plugin from Dom libraries
  11316. ===========================*/
  11317. function addLibraryPlugin(lib) {
  11318. lib.fn.swiper = function (params) {
  11319. var firstInstance;
  11320. lib(this).each(function () {
  11321. var s = new Swiper(this, params);
  11322. if (!firstInstance) firstInstance = s;
  11323. });
  11324. return firstInstance;
  11325. };
  11326. }
  11327. if (domLib) {
  11328. if (!('transitionEnd' in domLib.fn)) {
  11329. domLib.fn.transitionEnd = function (callback) {
  11330. var events = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'],
  11331. i, j, dom = this;
  11332. function fireCallBack(e) {
  11333. /*jshint validthis:true */
  11334. if (e.target !== this) return;
  11335. callback.call(this, e);
  11336. for (i = 0; i < events.length; i++) {
  11337. dom.off(events[i], fireCallBack);
  11338. }
  11339. }
  11340. if (callback) {
  11341. for (i = 0; i < events.length; i++) {
  11342. dom.on(events[i], fireCallBack);
  11343. }
  11344. }
  11345. return this;
  11346. };
  11347. }
  11348. if (!('transform' in domLib.fn)) {
  11349. domLib.fn.transform = function (transform) {
  11350. for (var i = 0; i < this.length; i++) {
  11351. var elStyle = this[i].style;
  11352. elStyle.webkitTransform = elStyle.MsTransform = elStyle.msTransform = elStyle.MozTransform = elStyle.OTransform = elStyle.transform = transform;
  11353. }
  11354. return this;
  11355. };
  11356. }
  11357. if (!('transition' in domLib.fn)) {
  11358. domLib.fn.transition = function (duration) {
  11359. if (typeof duration !== 'string') {
  11360. duration = duration + 'ms';
  11361. }
  11362. for (var i = 0; i < this.length; i++) {
  11363. var elStyle = this[i].style;
  11364. elStyle.webkitTransitionDuration = elStyle.MsTransitionDuration = elStyle.msTransitionDuration = elStyle.MozTransitionDuration = elStyle.OTransitionDuration = elStyle.transitionDuration = duration;
  11365. }
  11366. return this;
  11367. };
  11368. }
  11369. }
  11370. ionic.views.Swiper = Swiper;
  11371. })();
  11372. (function(ionic) {
  11373. 'use strict';
  11374. ionic.views.Toggle = ionic.views.View.inherit({
  11375. initialize: function(opts) {
  11376. var self = this;
  11377. this.el = opts.el;
  11378. this.checkbox = opts.checkbox;
  11379. this.track = opts.track;
  11380. this.handle = opts.handle;
  11381. this.openPercent = -1;
  11382. this.onChange = opts.onChange || function() {};
  11383. this.triggerThreshold = opts.triggerThreshold || 20;
  11384. this.dragStartHandler = function(e) {
  11385. self.dragStart(e);
  11386. };
  11387. this.dragHandler = function(e) {
  11388. self.drag(e);
  11389. };
  11390. this.holdHandler = function(e) {
  11391. self.hold(e);
  11392. };
  11393. this.releaseHandler = function(e) {
  11394. self.release(e);
  11395. };
  11396. this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el);
  11397. this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el);
  11398. this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el);
  11399. this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el);
  11400. },
  11401. destroy: function() {
  11402. ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture);
  11403. ionic.offGesture(this.dragGesture, 'drag', this.dragGesture);
  11404. ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler);
  11405. ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler);
  11406. },
  11407. tap: function() {
  11408. if(this.el.getAttribute('disabled') !== 'disabled') {
  11409. this.val( !this.checkbox.checked );
  11410. }
  11411. },
  11412. dragStart: function(e) {
  11413. if(this.checkbox.disabled) return;
  11414. this._dragInfo = {
  11415. width: this.el.offsetWidth,
  11416. left: this.el.offsetLeft,
  11417. right: this.el.offsetLeft + this.el.offsetWidth,
  11418. triggerX: this.el.offsetWidth / 2,
  11419. initialState: this.checkbox.checked
  11420. };
  11421. // Stop any parent dragging
  11422. e.gesture.srcEvent.preventDefault();
  11423. // Trigger hold styles
  11424. this.hold(e);
  11425. },
  11426. drag: function(e) {
  11427. var self = this;
  11428. if(!this._dragInfo) { return; }
  11429. // Stop any parent dragging
  11430. e.gesture.srcEvent.preventDefault();
  11431. ionic.requestAnimationFrame(function () {
  11432. if (!self._dragInfo) { return; }
  11433. var px = e.gesture.touches[0].pageX - self._dragInfo.left;
  11434. var mx = self._dragInfo.width - self.triggerThreshold;
  11435. // The initial state was on, so "tend towards" on
  11436. if(self._dragInfo.initialState) {
  11437. if(px < self.triggerThreshold) {
  11438. self.setOpenPercent(0);
  11439. } else if(px > self._dragInfo.triggerX) {
  11440. self.setOpenPercent(100);
  11441. }
  11442. } else {
  11443. // The initial state was off, so "tend towards" off
  11444. if(px < self._dragInfo.triggerX) {
  11445. self.setOpenPercent(0);
  11446. } else if(px > mx) {
  11447. self.setOpenPercent(100);
  11448. }
  11449. }
  11450. });
  11451. },
  11452. endDrag: function() {
  11453. this._dragInfo = null;
  11454. },
  11455. hold: function() {
  11456. this.el.classList.add('dragging');
  11457. },
  11458. release: function(e) {
  11459. this.el.classList.remove('dragging');
  11460. this.endDrag(e);
  11461. },
  11462. setOpenPercent: function(openPercent) {
  11463. // only make a change if the new open percent has changed
  11464. if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) {
  11465. this.openPercent = openPercent;
  11466. if(openPercent === 0) {
  11467. this.val(false);
  11468. } else if(openPercent === 100) {
  11469. this.val(true);
  11470. } else {
  11471. var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) );
  11472. openPixel = (openPixel < 1 ? 0 : openPixel);
  11473. this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)';
  11474. }
  11475. }
  11476. },
  11477. val: function(value) {
  11478. if(value === true || value === false) {
  11479. if(this.handle.style[ionic.CSS.TRANSFORM] !== "") {
  11480. this.handle.style[ionic.CSS.TRANSFORM] = "";
  11481. }
  11482. this.checkbox.checked = value;
  11483. this.openPercent = (value ? 100 : 0);
  11484. this.onChange && this.onChange();
  11485. }
  11486. return this.checkbox.checked;
  11487. }
  11488. });
  11489. })(ionic);
  11490. })();
  11491. /*!
  11492. * ionic.bundle.js is a concatenation of:
  11493. * ionic.js, angular.js, angular-animate.js,
  11494. * angular-sanitize.js, angular-ui-router.js,
  11495. * and ionic-angular.js
  11496. */
  11497. /**
  11498. * @license AngularJS v1.5.3
  11499. * (c) 2010-2016 Google, Inc. http://angularjs.org
  11500. * License: MIT
  11501. */
  11502. (function(window, document, undefined) {'use strict';
  11503. /**
  11504. * @description
  11505. *
  11506. * This object provides a utility for producing rich Error messages within
  11507. * Angular. It can be called as follows:
  11508. *
  11509. * var exampleMinErr = minErr('example');
  11510. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  11511. *
  11512. * The above creates an instance of minErr in the example namespace. The
  11513. * resulting error will have a namespaced error code of example.one. The
  11514. * resulting error will replace {0} with the value of foo, and {1} with the
  11515. * value of bar. The object is not restricted in the number of arguments it can
  11516. * take.
  11517. *
  11518. * If fewer arguments are specified than necessary for interpolation, the extra
  11519. * interpolation markers will be preserved in the final string.
  11520. *
  11521. * Since data will be parsed statically during a build step, some restrictions
  11522. * are applied with respect to how minErr instances are created and called.
  11523. * Instances should have names of the form namespaceMinErr for a minErr created
  11524. * using minErr('namespace') . Error codes, namespaces and template strings
  11525. * should all be static strings, not variables or general expressions.
  11526. *
  11527. * @param {string} module The namespace to use for the new minErr instance.
  11528. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  11529. * error from returned function, for cases when a particular type of error is useful.
  11530. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  11531. */
  11532. function minErr(module, ErrorConstructor) {
  11533. ErrorConstructor = ErrorConstructor || Error;
  11534. return function() {
  11535. var SKIP_INDEXES = 2;
  11536. var templateArgs = arguments,
  11537. code = templateArgs[0],
  11538. message = '[' + (module ? module + ':' : '') + code + '] ',
  11539. template = templateArgs[1],
  11540. paramPrefix, i;
  11541. message += template.replace(/\{\d+\}/g, function(match) {
  11542. var index = +match.slice(1, -1),
  11543. shiftedIndex = index + SKIP_INDEXES;
  11544. if (shiftedIndex < templateArgs.length) {
  11545. return toDebugString(templateArgs[shiftedIndex]);
  11546. }
  11547. return match;
  11548. });
  11549. message += '\nhttp://errors.angularjs.org/1.5.3/' +
  11550. (module ? module + '/' : '') + code;
  11551. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  11552. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  11553. encodeURIComponent(toDebugString(templateArgs[i]));
  11554. }
  11555. return new ErrorConstructor(message);
  11556. };
  11557. }
  11558. /* We need to tell jshint what variables are being exported */
  11559. /* global angular: true,
  11560. msie: true,
  11561. jqLite: true,
  11562. jQuery: true,
  11563. slice: true,
  11564. splice: true,
  11565. push: true,
  11566. toString: true,
  11567. ngMinErr: true,
  11568. angularModule: true,
  11569. uid: true,
  11570. REGEX_STRING_REGEXP: true,
  11571. VALIDITY_STATE_PROPERTY: true,
  11572. lowercase: true,
  11573. uppercase: true,
  11574. manualLowercase: true,
  11575. manualUppercase: true,
  11576. nodeName_: true,
  11577. isArrayLike: true,
  11578. forEach: true,
  11579. forEachSorted: true,
  11580. reverseParams: true,
  11581. nextUid: true,
  11582. setHashKey: true,
  11583. extend: true,
  11584. toInt: true,
  11585. inherit: true,
  11586. merge: true,
  11587. noop: true,
  11588. identity: true,
  11589. valueFn: true,
  11590. isUndefined: true,
  11591. isDefined: true,
  11592. isObject: true,
  11593. isBlankObject: true,
  11594. isString: true,
  11595. isNumber: true,
  11596. isDate: true,
  11597. isArray: true,
  11598. isFunction: true,
  11599. isRegExp: true,
  11600. isWindow: true,
  11601. isScope: true,
  11602. isFile: true,
  11603. isFormData: true,
  11604. isBlob: true,
  11605. isBoolean: true,
  11606. isPromiseLike: true,
  11607. trim: true,
  11608. escapeForRegexp: true,
  11609. isElement: true,
  11610. makeMap: true,
  11611. includes: true,
  11612. arrayRemove: true,
  11613. copy: true,
  11614. shallowCopy: true,
  11615. equals: true,
  11616. csp: true,
  11617. jq: true,
  11618. concat: true,
  11619. sliceArgs: true,
  11620. bind: true,
  11621. toJsonReplacer: true,
  11622. toJson: true,
  11623. fromJson: true,
  11624. convertTimezoneToLocal: true,
  11625. timezoneToOffset: true,
  11626. startingTag: true,
  11627. tryDecodeURIComponent: true,
  11628. parseKeyValue: true,
  11629. toKeyValue: true,
  11630. encodeUriSegment: true,
  11631. encodeUriQuery: true,
  11632. angularInit: true,
  11633. bootstrap: true,
  11634. getTestability: true,
  11635. snake_case: true,
  11636. bindJQuery: true,
  11637. assertArg: true,
  11638. assertArgFn: true,
  11639. assertNotHasOwnProperty: true,
  11640. getter: true,
  11641. getBlockNodes: true,
  11642. hasOwnProperty: true,
  11643. createMap: true,
  11644. NODE_TYPE_ELEMENT: true,
  11645. NODE_TYPE_ATTRIBUTE: true,
  11646. NODE_TYPE_TEXT: true,
  11647. NODE_TYPE_COMMENT: true,
  11648. NODE_TYPE_DOCUMENT: true,
  11649. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  11650. */
  11651. ////////////////////////////////////
  11652. /**
  11653. * @ngdoc module
  11654. * @name ng
  11655. * @module ng
  11656. * @description
  11657. *
  11658. * # ng (core module)
  11659. * The ng module is loaded by default when an AngularJS application is started. The module itself
  11660. * contains the essential components for an AngularJS application to function. The table below
  11661. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  11662. * components available within this core module.
  11663. *
  11664. * <div doc-module-components="ng"></div>
  11665. */
  11666. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  11667. // The name of a form control's ValidityState property.
  11668. // This is used so that it's possible for internal tests to create mock ValidityStates.
  11669. var VALIDITY_STATE_PROPERTY = 'validity';
  11670. var hasOwnProperty = Object.prototype.hasOwnProperty;
  11671. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  11672. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  11673. var manualLowercase = function(s) {
  11674. /* jshint bitwise: false */
  11675. return isString(s)
  11676. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  11677. : s;
  11678. };
  11679. var manualUppercase = function(s) {
  11680. /* jshint bitwise: false */
  11681. return isString(s)
  11682. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  11683. : s;
  11684. };
  11685. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  11686. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  11687. // with correct but slower alternatives. See https://github.com/angular/angular.js/issues/11387
  11688. if ('i' !== 'I'.toLowerCase()) {
  11689. lowercase = manualLowercase;
  11690. uppercase = manualUppercase;
  11691. }
  11692. var
  11693. msie, // holds major version number for IE, or NaN if UA is not IE.
  11694. jqLite, // delay binding since jQuery could be loaded after us.
  11695. jQuery, // delay binding
  11696. slice = [].slice,
  11697. splice = [].splice,
  11698. push = [].push,
  11699. toString = Object.prototype.toString,
  11700. getPrototypeOf = Object.getPrototypeOf,
  11701. ngMinErr = minErr('ng'),
  11702. /** @name angular */
  11703. angular = window.angular || (window.angular = {}),
  11704. angularModule,
  11705. uid = 0;
  11706. /**
  11707. * documentMode is an IE-only property
  11708. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  11709. */
  11710. msie = document.documentMode;
  11711. /**
  11712. * @private
  11713. * @param {*} obj
  11714. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  11715. * String ...)
  11716. */
  11717. function isArrayLike(obj) {
  11718. // `null`, `undefined` and `window` are not array-like
  11719. if (obj == null || isWindow(obj)) return false;
  11720. // arrays, strings and jQuery/jqLite objects are array like
  11721. // * jqLite is either the jQuery or jqLite constructor function
  11722. // * we have to check the existence of jqLite first as this method is called
  11723. // via the forEach method when constructing the jqLite object in the first place
  11724. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  11725. // Support: iOS 8.2 (not reproducible in simulator)
  11726. // "length" in obj used to prevent JIT error (gh-11508)
  11727. var length = "length" in Object(obj) && obj.length;
  11728. // NodeList objects (with `item` method) and
  11729. // other objects with suitable length characteristics are array-like
  11730. return isNumber(length) &&
  11731. (length >= 0 && ((length - 1) in obj || obj instanceof Array) || typeof obj.item == 'function');
  11732. }
  11733. /**
  11734. * @ngdoc function
  11735. * @name angular.forEach
  11736. * @module ng
  11737. * @kind function
  11738. *
  11739. * @description
  11740. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  11741. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  11742. * is the value of an object property or an array element, `key` is the object property key or
  11743. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  11744. *
  11745. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  11746. * using the `hasOwnProperty` method.
  11747. *
  11748. * Unlike ES262's
  11749. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  11750. * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  11751. * return the value provided.
  11752. *
  11753. ```js
  11754. var values = {name: 'misko', gender: 'male'};
  11755. var log = [];
  11756. angular.forEach(values, function(value, key) {
  11757. this.push(key + ': ' + value);
  11758. }, log);
  11759. expect(log).toEqual(['name: misko', 'gender: male']);
  11760. ```
  11761. *
  11762. * @param {Object|Array} obj Object to iterate over.
  11763. * @param {Function} iterator Iterator function.
  11764. * @param {Object=} context Object to become context (`this`) for the iterator function.
  11765. * @returns {Object|Array} Reference to `obj`.
  11766. */
  11767. function forEach(obj, iterator, context) {
  11768. var key, length;
  11769. if (obj) {
  11770. if (isFunction(obj)) {
  11771. for (key in obj) {
  11772. // Need to check if hasOwnProperty exists,
  11773. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  11774. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  11775. iterator.call(context, obj[key], key, obj);
  11776. }
  11777. }
  11778. } else if (isArray(obj) || isArrayLike(obj)) {
  11779. var isPrimitive = typeof obj !== 'object';
  11780. for (key = 0, length = obj.length; key < length; key++) {
  11781. if (isPrimitive || key in obj) {
  11782. iterator.call(context, obj[key], key, obj);
  11783. }
  11784. }
  11785. } else if (obj.forEach && obj.forEach !== forEach) {
  11786. obj.forEach(iterator, context, obj);
  11787. } else if (isBlankObject(obj)) {
  11788. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  11789. for (key in obj) {
  11790. iterator.call(context, obj[key], key, obj);
  11791. }
  11792. } else if (typeof obj.hasOwnProperty === 'function') {
  11793. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  11794. for (key in obj) {
  11795. if (obj.hasOwnProperty(key)) {
  11796. iterator.call(context, obj[key], key, obj);
  11797. }
  11798. }
  11799. } else {
  11800. // Slow path for objects which do not have a method `hasOwnProperty`
  11801. for (key in obj) {
  11802. if (hasOwnProperty.call(obj, key)) {
  11803. iterator.call(context, obj[key], key, obj);
  11804. }
  11805. }
  11806. }
  11807. }
  11808. return obj;
  11809. }
  11810. function forEachSorted(obj, iterator, context) {
  11811. var keys = Object.keys(obj).sort();
  11812. for (var i = 0; i < keys.length; i++) {
  11813. iterator.call(context, obj[keys[i]], keys[i]);
  11814. }
  11815. return keys;
  11816. }
  11817. /**
  11818. * when using forEach the params are value, key, but it is often useful to have key, value.
  11819. * @param {function(string, *)} iteratorFn
  11820. * @returns {function(*, string)}
  11821. */
  11822. function reverseParams(iteratorFn) {
  11823. return function(value, key) {iteratorFn(key, value);};
  11824. }
  11825. /**
  11826. * A consistent way of creating unique IDs in angular.
  11827. *
  11828. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  11829. * we hit number precision issues in JavaScript.
  11830. *
  11831. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  11832. *
  11833. * @returns {number} an unique alpha-numeric string
  11834. */
  11835. function nextUid() {
  11836. return ++uid;
  11837. }
  11838. /**
  11839. * Set or clear the hashkey for an object.
  11840. * @param obj object
  11841. * @param h the hashkey (!truthy to delete the hashkey)
  11842. */
  11843. function setHashKey(obj, h) {
  11844. if (h) {
  11845. obj.$$hashKey = h;
  11846. } else {
  11847. delete obj.$$hashKey;
  11848. }
  11849. }
  11850. function baseExtend(dst, objs, deep) {
  11851. var h = dst.$$hashKey;
  11852. for (var i = 0, ii = objs.length; i < ii; ++i) {
  11853. var obj = objs[i];
  11854. if (!isObject(obj) && !isFunction(obj)) continue;
  11855. var keys = Object.keys(obj);
  11856. for (var j = 0, jj = keys.length; j < jj; j++) {
  11857. var key = keys[j];
  11858. var src = obj[key];
  11859. if (deep && isObject(src)) {
  11860. if (isDate(src)) {
  11861. dst[key] = new Date(src.valueOf());
  11862. } else if (isRegExp(src)) {
  11863. dst[key] = new RegExp(src);
  11864. } else if (src.nodeName) {
  11865. dst[key] = src.cloneNode(true);
  11866. } else if (isElement(src)) {
  11867. dst[key] = src.clone();
  11868. } else {
  11869. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  11870. baseExtend(dst[key], [src], true);
  11871. }
  11872. } else {
  11873. dst[key] = src;
  11874. }
  11875. }
  11876. }
  11877. setHashKey(dst, h);
  11878. return dst;
  11879. }
  11880. /**
  11881. * @ngdoc function
  11882. * @name angular.extend
  11883. * @module ng
  11884. * @kind function
  11885. *
  11886. * @description
  11887. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  11888. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  11889. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  11890. *
  11891. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  11892. * {@link angular.merge} for this.
  11893. *
  11894. * @param {Object} dst Destination object.
  11895. * @param {...Object} src Source object(s).
  11896. * @returns {Object} Reference to `dst`.
  11897. */
  11898. function extend(dst) {
  11899. return baseExtend(dst, slice.call(arguments, 1), false);
  11900. }
  11901. /**
  11902. * @ngdoc function
  11903. * @name angular.merge
  11904. * @module ng
  11905. * @kind function
  11906. *
  11907. * @description
  11908. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  11909. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  11910. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  11911. *
  11912. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  11913. * objects, performing a deep copy.
  11914. *
  11915. * @param {Object} dst Destination object.
  11916. * @param {...Object} src Source object(s).
  11917. * @returns {Object} Reference to `dst`.
  11918. */
  11919. function merge(dst) {
  11920. return baseExtend(dst, slice.call(arguments, 1), true);
  11921. }
  11922. function toInt(str) {
  11923. return parseInt(str, 10);
  11924. }
  11925. function inherit(parent, extra) {
  11926. return extend(Object.create(parent), extra);
  11927. }
  11928. /**
  11929. * @ngdoc function
  11930. * @name angular.noop
  11931. * @module ng
  11932. * @kind function
  11933. *
  11934. * @description
  11935. * A function that performs no operations. This function can be useful when writing code in the
  11936. * functional style.
  11937. ```js
  11938. function foo(callback) {
  11939. var result = calculateResult();
  11940. (callback || angular.noop)(result);
  11941. }
  11942. ```
  11943. */
  11944. function noop() {}
  11945. noop.$inject = [];
  11946. /**
  11947. * @ngdoc function
  11948. * @name angular.identity
  11949. * @module ng
  11950. * @kind function
  11951. *
  11952. * @description
  11953. * A function that returns its first argument. This function is useful when writing code in the
  11954. * functional style.
  11955. *
  11956. ```js
  11957. function transformer(transformationFn, value) {
  11958. return (transformationFn || angular.identity)(value);
  11959. };
  11960. ```
  11961. * @param {*} value to be returned.
  11962. * @returns {*} the value passed in.
  11963. */
  11964. function identity($) {return $;}
  11965. identity.$inject = [];
  11966. function valueFn(value) {return function valueRef() {return value;};}
  11967. function hasCustomToString(obj) {
  11968. return isFunction(obj.toString) && obj.toString !== toString;
  11969. }
  11970. /**
  11971. * @ngdoc function
  11972. * @name angular.isUndefined
  11973. * @module ng
  11974. * @kind function
  11975. *
  11976. * @description
  11977. * Determines if a reference is undefined.
  11978. *
  11979. * @param {*} value Reference to check.
  11980. * @returns {boolean} True if `value` is undefined.
  11981. */
  11982. function isUndefined(value) {return typeof value === 'undefined';}
  11983. /**
  11984. * @ngdoc function
  11985. * @name angular.isDefined
  11986. * @module ng
  11987. * @kind function
  11988. *
  11989. * @description
  11990. * Determines if a reference is defined.
  11991. *
  11992. * @param {*} value Reference to check.
  11993. * @returns {boolean} True if `value` is defined.
  11994. */
  11995. function isDefined(value) {return typeof value !== 'undefined';}
  11996. /**
  11997. * @ngdoc function
  11998. * @name angular.isObject
  11999. * @module ng
  12000. * @kind function
  12001. *
  12002. * @description
  12003. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  12004. * considered to be objects. Note that JavaScript arrays are objects.
  12005. *
  12006. * @param {*} value Reference to check.
  12007. * @returns {boolean} True if `value` is an `Object` but not `null`.
  12008. */
  12009. function isObject(value) {
  12010. // http://jsperf.com/isobject4
  12011. return value !== null && typeof value === 'object';
  12012. }
  12013. /**
  12014. * Determine if a value is an object with a null prototype
  12015. *
  12016. * @returns {boolean} True if `value` is an `Object` with a null prototype
  12017. */
  12018. function isBlankObject(value) {
  12019. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  12020. }
  12021. /**
  12022. * @ngdoc function
  12023. * @name angular.isString
  12024. * @module ng
  12025. * @kind function
  12026. *
  12027. * @description
  12028. * Determines if a reference is a `String`.
  12029. *
  12030. * @param {*} value Reference to check.
  12031. * @returns {boolean} True if `value` is a `String`.
  12032. */
  12033. function isString(value) {return typeof value === 'string';}
  12034. /**
  12035. * @ngdoc function
  12036. * @name angular.isNumber
  12037. * @module ng
  12038. * @kind function
  12039. *
  12040. * @description
  12041. * Determines if a reference is a `Number`.
  12042. *
  12043. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  12044. *
  12045. * If you wish to exclude these then you can use the native
  12046. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  12047. * method.
  12048. *
  12049. * @param {*} value Reference to check.
  12050. * @returns {boolean} True if `value` is a `Number`.
  12051. */
  12052. function isNumber(value) {return typeof value === 'number';}
  12053. /**
  12054. * @ngdoc function
  12055. * @name angular.isDate
  12056. * @module ng
  12057. * @kind function
  12058. *
  12059. * @description
  12060. * Determines if a value is a date.
  12061. *
  12062. * @param {*} value Reference to check.
  12063. * @returns {boolean} True if `value` is a `Date`.
  12064. */
  12065. function isDate(value) {
  12066. return toString.call(value) === '[object Date]';
  12067. }
  12068. /**
  12069. * @ngdoc function
  12070. * @name angular.isArray
  12071. * @module ng
  12072. * @kind function
  12073. *
  12074. * @description
  12075. * Determines if a reference is an `Array`.
  12076. *
  12077. * @param {*} value Reference to check.
  12078. * @returns {boolean} True if `value` is an `Array`.
  12079. */
  12080. var isArray = Array.isArray;
  12081. /**
  12082. * @ngdoc function
  12083. * @name angular.isFunction
  12084. * @module ng
  12085. * @kind function
  12086. *
  12087. * @description
  12088. * Determines if a reference is a `Function`.
  12089. *
  12090. * @param {*} value Reference to check.
  12091. * @returns {boolean} True if `value` is a `Function`.
  12092. */
  12093. function isFunction(value) {return typeof value === 'function';}
  12094. /**
  12095. * Determines if a value is a regular expression object.
  12096. *
  12097. * @private
  12098. * @param {*} value Reference to check.
  12099. * @returns {boolean} True if `value` is a `RegExp`.
  12100. */
  12101. function isRegExp(value) {
  12102. return toString.call(value) === '[object RegExp]';
  12103. }
  12104. /**
  12105. * Checks if `obj` is a window object.
  12106. *
  12107. * @private
  12108. * @param {*} obj Object to check
  12109. * @returns {boolean} True if `obj` is a window obj.
  12110. */
  12111. function isWindow(obj) {
  12112. return obj && obj.window === obj;
  12113. }
  12114. function isScope(obj) {
  12115. return obj && obj.$evalAsync && obj.$watch;
  12116. }
  12117. function isFile(obj) {
  12118. return toString.call(obj) === '[object File]';
  12119. }
  12120. function isFormData(obj) {
  12121. return toString.call(obj) === '[object FormData]';
  12122. }
  12123. function isBlob(obj) {
  12124. return toString.call(obj) === '[object Blob]';
  12125. }
  12126. function isBoolean(value) {
  12127. return typeof value === 'boolean';
  12128. }
  12129. function isPromiseLike(obj) {
  12130. return obj && isFunction(obj.then);
  12131. }
  12132. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  12133. function isTypedArray(value) {
  12134. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  12135. }
  12136. function isArrayBuffer(obj) {
  12137. return toString.call(obj) === '[object ArrayBuffer]';
  12138. }
  12139. var trim = function(value) {
  12140. return isString(value) ? value.trim() : value;
  12141. };
  12142. // Copied from:
  12143. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  12144. // Prereq: s is a string.
  12145. var escapeForRegexp = function(s) {
  12146. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  12147. replace(/\x08/g, '\\x08');
  12148. };
  12149. /**
  12150. * @ngdoc function
  12151. * @name angular.isElement
  12152. * @module ng
  12153. * @kind function
  12154. *
  12155. * @description
  12156. * Determines if a reference is a DOM element (or wrapped jQuery element).
  12157. *
  12158. * @param {*} value Reference to check.
  12159. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  12160. */
  12161. function isElement(node) {
  12162. return !!(node &&
  12163. (node.nodeName // we are a direct element
  12164. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  12165. }
  12166. /**
  12167. * @param str 'key1,key2,...'
  12168. * @returns {object} in the form of {key1:true, key2:true, ...}
  12169. */
  12170. function makeMap(str) {
  12171. var obj = {}, items = str.split(','), i;
  12172. for (i = 0; i < items.length; i++) {
  12173. obj[items[i]] = true;
  12174. }
  12175. return obj;
  12176. }
  12177. function nodeName_(element) {
  12178. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  12179. }
  12180. function includes(array, obj) {
  12181. return Array.prototype.indexOf.call(array, obj) != -1;
  12182. }
  12183. function arrayRemove(array, value) {
  12184. var index = array.indexOf(value);
  12185. if (index >= 0) {
  12186. array.splice(index, 1);
  12187. }
  12188. return index;
  12189. }
  12190. /**
  12191. * @ngdoc function
  12192. * @name angular.copy
  12193. * @module ng
  12194. * @kind function
  12195. *
  12196. * @description
  12197. * Creates a deep copy of `source`, which should be an object or an array.
  12198. *
  12199. * * If no destination is supplied, a copy of the object or array is created.
  12200. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  12201. * are deleted and then all elements/properties from the source are copied to it.
  12202. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  12203. * * If `source` is identical to 'destination' an exception will be thrown.
  12204. *
  12205. * @param {*} source The source that will be used to make a copy.
  12206. * Can be any type, including primitives, `null`, and `undefined`.
  12207. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  12208. * provided, must be of the same type as `source`.
  12209. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  12210. *
  12211. * @example
  12212. <example module="copyExample">
  12213. <file name="index.html">
  12214. <div ng-controller="ExampleController">
  12215. <form novalidate class="simple-form">
  12216. Name: <input type="text" ng-model="user.name" /><br />
  12217. E-mail: <input type="email" ng-model="user.email" /><br />
  12218. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  12219. <input type="radio" ng-model="user.gender" value="female" />female<br />
  12220. <button ng-click="reset()">RESET</button>
  12221. <button ng-click="update(user)">SAVE</button>
  12222. </form>
  12223. <pre>form = {{user | json}}</pre>
  12224. <pre>master = {{master | json}}</pre>
  12225. </div>
  12226. <script>
  12227. angular.module('copyExample', [])
  12228. .controller('ExampleController', ['$scope', function($scope) {
  12229. $scope.master= {};
  12230. $scope.update = function(user) {
  12231. // Example with 1 argument
  12232. $scope.master= angular.copy(user);
  12233. };
  12234. $scope.reset = function() {
  12235. // Example with 2 arguments
  12236. angular.copy($scope.master, $scope.user);
  12237. };
  12238. $scope.reset();
  12239. }]);
  12240. </script>
  12241. </file>
  12242. </example>
  12243. */
  12244. function copy(source, destination) {
  12245. var stackSource = [];
  12246. var stackDest = [];
  12247. if (destination) {
  12248. if (isTypedArray(destination) || isArrayBuffer(destination)) {
  12249. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  12250. }
  12251. if (source === destination) {
  12252. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  12253. }
  12254. // Empty the destination object
  12255. if (isArray(destination)) {
  12256. destination.length = 0;
  12257. } else {
  12258. forEach(destination, function(value, key) {
  12259. if (key !== '$$hashKey') {
  12260. delete destination[key];
  12261. }
  12262. });
  12263. }
  12264. stackSource.push(source);
  12265. stackDest.push(destination);
  12266. return copyRecurse(source, destination);
  12267. }
  12268. return copyElement(source);
  12269. function copyRecurse(source, destination) {
  12270. var h = destination.$$hashKey;
  12271. var key;
  12272. if (isArray(source)) {
  12273. for (var i = 0, ii = source.length; i < ii; i++) {
  12274. destination.push(copyElement(source[i]));
  12275. }
  12276. } else if (isBlankObject(source)) {
  12277. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  12278. for (key in source) {
  12279. destination[key] = copyElement(source[key]);
  12280. }
  12281. } else if (source && typeof source.hasOwnProperty === 'function') {
  12282. // Slow path, which must rely on hasOwnProperty
  12283. for (key in source) {
  12284. if (source.hasOwnProperty(key)) {
  12285. destination[key] = copyElement(source[key]);
  12286. }
  12287. }
  12288. } else {
  12289. // Slowest path --- hasOwnProperty can't be called as a method
  12290. for (key in source) {
  12291. if (hasOwnProperty.call(source, key)) {
  12292. destination[key] = copyElement(source[key]);
  12293. }
  12294. }
  12295. }
  12296. setHashKey(destination, h);
  12297. return destination;
  12298. }
  12299. function copyElement(source) {
  12300. // Simple values
  12301. if (!isObject(source)) {
  12302. return source;
  12303. }
  12304. // Already copied values
  12305. var index = stackSource.indexOf(source);
  12306. if (index !== -1) {
  12307. return stackDest[index];
  12308. }
  12309. if (isWindow(source) || isScope(source)) {
  12310. throw ngMinErr('cpws',
  12311. "Can't copy! Making copies of Window or Scope instances is not supported.");
  12312. }
  12313. var needsRecurse = false;
  12314. var destination = copyType(source);
  12315. if (destination === undefined) {
  12316. destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
  12317. needsRecurse = true;
  12318. }
  12319. stackSource.push(source);
  12320. stackDest.push(destination);
  12321. return needsRecurse
  12322. ? copyRecurse(source, destination)
  12323. : destination;
  12324. }
  12325. function copyType(source) {
  12326. switch (toString.call(source)) {
  12327. case '[object Int8Array]':
  12328. case '[object Int16Array]':
  12329. case '[object Int32Array]':
  12330. case '[object Float32Array]':
  12331. case '[object Float64Array]':
  12332. case '[object Uint8Array]':
  12333. case '[object Uint8ClampedArray]':
  12334. case '[object Uint16Array]':
  12335. case '[object Uint32Array]':
  12336. return new source.constructor(copyElement(source.buffer));
  12337. case '[object ArrayBuffer]':
  12338. //Support: IE10
  12339. if (!source.slice) {
  12340. var copied = new ArrayBuffer(source.byteLength);
  12341. new Uint8Array(copied).set(new Uint8Array(source));
  12342. return copied;
  12343. }
  12344. return source.slice(0);
  12345. case '[object Boolean]':
  12346. case '[object Number]':
  12347. case '[object String]':
  12348. case '[object Date]':
  12349. return new source.constructor(source.valueOf());
  12350. case '[object RegExp]':
  12351. var re = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  12352. re.lastIndex = source.lastIndex;
  12353. return re;
  12354. case '[object Blob]':
  12355. return new source.constructor([source], {type: source.type});
  12356. }
  12357. if (isFunction(source.cloneNode)) {
  12358. return source.cloneNode(true);
  12359. }
  12360. }
  12361. }
  12362. /**
  12363. * Creates a shallow copy of an object, an array or a primitive.
  12364. *
  12365. * Assumes that there are no proto properties for objects.
  12366. */
  12367. function shallowCopy(src, dst) {
  12368. if (isArray(src)) {
  12369. dst = dst || [];
  12370. for (var i = 0, ii = src.length; i < ii; i++) {
  12371. dst[i] = src[i];
  12372. }
  12373. } else if (isObject(src)) {
  12374. dst = dst || {};
  12375. for (var key in src) {
  12376. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  12377. dst[key] = src[key];
  12378. }
  12379. }
  12380. }
  12381. return dst || src;
  12382. }
  12383. /**
  12384. * @ngdoc function
  12385. * @name angular.equals
  12386. * @module ng
  12387. * @kind function
  12388. *
  12389. * @description
  12390. * Determines if two objects or two values are equivalent. Supports value types, regular
  12391. * expressions, arrays and objects.
  12392. *
  12393. * Two objects or values are considered equivalent if at least one of the following is true:
  12394. *
  12395. * * Both objects or values pass `===` comparison.
  12396. * * Both objects or values are of the same type and all of their properties are equal by
  12397. * comparing them with `angular.equals`.
  12398. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  12399. * * Both values represent the same regular expression (In JavaScript,
  12400. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  12401. * representation matches).
  12402. *
  12403. * During a property comparison, properties of `function` type and properties with names
  12404. * that begin with `$` are ignored.
  12405. *
  12406. * Scope and DOMWindow objects are being compared only by identify (`===`).
  12407. *
  12408. * @param {*} o1 Object or value to compare.
  12409. * @param {*} o2 Object or value to compare.
  12410. * @returns {boolean} True if arguments are equal.
  12411. */
  12412. function equals(o1, o2) {
  12413. if (o1 === o2) return true;
  12414. if (o1 === null || o2 === null) return false;
  12415. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  12416. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  12417. if (t1 == t2 && t1 == 'object') {
  12418. if (isArray(o1)) {
  12419. if (!isArray(o2)) return false;
  12420. if ((length = o1.length) == o2.length) {
  12421. for (key = 0; key < length; key++) {
  12422. if (!equals(o1[key], o2[key])) return false;
  12423. }
  12424. return true;
  12425. }
  12426. } else if (isDate(o1)) {
  12427. if (!isDate(o2)) return false;
  12428. return equals(o1.getTime(), o2.getTime());
  12429. } else if (isRegExp(o1)) {
  12430. if (!isRegExp(o2)) return false;
  12431. return o1.toString() == o2.toString();
  12432. } else {
  12433. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  12434. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  12435. keySet = createMap();
  12436. for (key in o1) {
  12437. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  12438. if (!equals(o1[key], o2[key])) return false;
  12439. keySet[key] = true;
  12440. }
  12441. for (key in o2) {
  12442. if (!(key in keySet) &&
  12443. key.charAt(0) !== '$' &&
  12444. isDefined(o2[key]) &&
  12445. !isFunction(o2[key])) return false;
  12446. }
  12447. return true;
  12448. }
  12449. }
  12450. return false;
  12451. }
  12452. var csp = function() {
  12453. if (!isDefined(csp.rules)) {
  12454. var ngCspElement = (document.querySelector('[ng-csp]') ||
  12455. document.querySelector('[data-ng-csp]'));
  12456. if (ngCspElement) {
  12457. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  12458. ngCspElement.getAttribute('data-ng-csp');
  12459. csp.rules = {
  12460. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  12461. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  12462. };
  12463. } else {
  12464. csp.rules = {
  12465. noUnsafeEval: noUnsafeEval(),
  12466. noInlineStyle: false
  12467. };
  12468. }
  12469. }
  12470. return csp.rules;
  12471. function noUnsafeEval() {
  12472. try {
  12473. /* jshint -W031, -W054 */
  12474. new Function('');
  12475. /* jshint +W031, +W054 */
  12476. return false;
  12477. } catch (e) {
  12478. return true;
  12479. }
  12480. }
  12481. };
  12482. /**
  12483. * @ngdoc directive
  12484. * @module ng
  12485. * @name ngJq
  12486. *
  12487. * @element ANY
  12488. * @param {string=} ngJq the name of the library available under `window`
  12489. * to be used for angular.element
  12490. * @description
  12491. * Use this directive to force the angular.element library. This should be
  12492. * used to force either jqLite by leaving ng-jq blank or setting the name of
  12493. * the jquery variable under window (eg. jQuery).
  12494. *
  12495. * Since angular looks for this directive when it is loaded (doesn't wait for the
  12496. * DOMContentLoaded event), it must be placed on an element that comes before the script
  12497. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  12498. * others ignored.
  12499. *
  12500. * @example
  12501. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  12502. ```html
  12503. <!doctype html>
  12504. <html ng-app ng-jq>
  12505. ...
  12506. ...
  12507. </html>
  12508. ```
  12509. * @example
  12510. * This example shows how to use a jQuery based library of a different name.
  12511. * The library name must be available at the top most 'window'.
  12512. ```html
  12513. <!doctype html>
  12514. <html ng-app ng-jq="jQueryLib">
  12515. ...
  12516. ...
  12517. </html>
  12518. ```
  12519. */
  12520. var jq = function() {
  12521. if (isDefined(jq.name_)) return jq.name_;
  12522. var el;
  12523. var i, ii = ngAttrPrefixes.length, prefix, name;
  12524. for (i = 0; i < ii; ++i) {
  12525. prefix = ngAttrPrefixes[i];
  12526. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  12527. name = el.getAttribute(prefix + 'jq');
  12528. break;
  12529. }
  12530. }
  12531. return (jq.name_ = name);
  12532. };
  12533. function concat(array1, array2, index) {
  12534. return array1.concat(slice.call(array2, index));
  12535. }
  12536. function sliceArgs(args, startIndex) {
  12537. return slice.call(args, startIndex || 0);
  12538. }
  12539. /* jshint -W101 */
  12540. /**
  12541. * @ngdoc function
  12542. * @name angular.bind
  12543. * @module ng
  12544. * @kind function
  12545. *
  12546. * @description
  12547. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  12548. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  12549. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  12550. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  12551. *
  12552. * @param {Object} self Context which `fn` should be evaluated in.
  12553. * @param {function()} fn Function to be bound.
  12554. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  12555. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  12556. */
  12557. /* jshint +W101 */
  12558. function bind(self, fn) {
  12559. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  12560. if (isFunction(fn) && !(fn instanceof RegExp)) {
  12561. return curryArgs.length
  12562. ? function() {
  12563. return arguments.length
  12564. ? fn.apply(self, concat(curryArgs, arguments, 0))
  12565. : fn.apply(self, curryArgs);
  12566. }
  12567. : function() {
  12568. return arguments.length
  12569. ? fn.apply(self, arguments)
  12570. : fn.call(self);
  12571. };
  12572. } else {
  12573. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  12574. return fn;
  12575. }
  12576. }
  12577. function toJsonReplacer(key, value) {
  12578. var val = value;
  12579. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  12580. val = undefined;
  12581. } else if (isWindow(value)) {
  12582. val = '$WINDOW';
  12583. } else if (value && document === value) {
  12584. val = '$DOCUMENT';
  12585. } else if (isScope(value)) {
  12586. val = '$SCOPE';
  12587. }
  12588. return val;
  12589. }
  12590. /**
  12591. * @ngdoc function
  12592. * @name angular.toJson
  12593. * @module ng
  12594. * @kind function
  12595. *
  12596. * @description
  12597. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  12598. * stripped since angular uses this notation internally.
  12599. *
  12600. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  12601. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  12602. * If set to an integer, the JSON output will contain that many spaces per indentation.
  12603. * @returns {string|undefined} JSON-ified string representing `obj`.
  12604. */
  12605. function toJson(obj, pretty) {
  12606. if (isUndefined(obj)) return undefined;
  12607. if (!isNumber(pretty)) {
  12608. pretty = pretty ? 2 : null;
  12609. }
  12610. return JSON.stringify(obj, toJsonReplacer, pretty);
  12611. }
  12612. /**
  12613. * @ngdoc function
  12614. * @name angular.fromJson
  12615. * @module ng
  12616. * @kind function
  12617. *
  12618. * @description
  12619. * Deserializes a JSON string.
  12620. *
  12621. * @param {string} json JSON string to deserialize.
  12622. * @returns {Object|Array|string|number} Deserialized JSON string.
  12623. */
  12624. function fromJson(json) {
  12625. return isString(json)
  12626. ? JSON.parse(json)
  12627. : json;
  12628. }
  12629. var ALL_COLONS = /:/g;
  12630. function timezoneToOffset(timezone, fallback) {
  12631. // IE/Edge do not "understand" colon (`:`) in timezone
  12632. timezone = timezone.replace(ALL_COLONS, '');
  12633. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  12634. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  12635. }
  12636. function addDateMinutes(date, minutes) {
  12637. date = new Date(date.getTime());
  12638. date.setMinutes(date.getMinutes() + minutes);
  12639. return date;
  12640. }
  12641. function convertTimezoneToLocal(date, timezone, reverse) {
  12642. reverse = reverse ? -1 : 1;
  12643. var dateTimezoneOffset = date.getTimezoneOffset();
  12644. var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  12645. return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset));
  12646. }
  12647. /**
  12648. * @returns {string} Returns the string representation of the element.
  12649. */
  12650. function startingTag(element) {
  12651. element = jqLite(element).clone();
  12652. try {
  12653. // turns out IE does not let you set .html() on elements which
  12654. // are not allowed to have children. So we just ignore it.
  12655. element.empty();
  12656. } catch (e) {}
  12657. var elemHtml = jqLite('<div>').append(element).html();
  12658. try {
  12659. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  12660. elemHtml.
  12661. match(/^(<[^>]+>)/)[1].
  12662. replace(/^<([\w\-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);});
  12663. } catch (e) {
  12664. return lowercase(elemHtml);
  12665. }
  12666. }
  12667. /////////////////////////////////////////////////
  12668. /**
  12669. * Tries to decode the URI component without throwing an exception.
  12670. *
  12671. * @private
  12672. * @param str value potential URI component to check.
  12673. * @returns {boolean} True if `value` can be decoded
  12674. * with the decodeURIComponent function.
  12675. */
  12676. function tryDecodeURIComponent(value) {
  12677. try {
  12678. return decodeURIComponent(value);
  12679. } catch (e) {
  12680. // Ignore any invalid uri component
  12681. }
  12682. }
  12683. /**
  12684. * Parses an escaped url query string into key-value pairs.
  12685. * @returns {Object.<string,boolean|Array>}
  12686. */
  12687. function parseKeyValue(/**string*/keyValue) {
  12688. var obj = {};
  12689. forEach((keyValue || "").split('&'), function(keyValue) {
  12690. var splitPoint, key, val;
  12691. if (keyValue) {
  12692. key = keyValue = keyValue.replace(/\+/g,'%20');
  12693. splitPoint = keyValue.indexOf('=');
  12694. if (splitPoint !== -1) {
  12695. key = keyValue.substring(0, splitPoint);
  12696. val = keyValue.substring(splitPoint + 1);
  12697. }
  12698. key = tryDecodeURIComponent(key);
  12699. if (isDefined(key)) {
  12700. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  12701. if (!hasOwnProperty.call(obj, key)) {
  12702. obj[key] = val;
  12703. } else if (isArray(obj[key])) {
  12704. obj[key].push(val);
  12705. } else {
  12706. obj[key] = [obj[key],val];
  12707. }
  12708. }
  12709. }
  12710. });
  12711. return obj;
  12712. }
  12713. function toKeyValue(obj) {
  12714. var parts = [];
  12715. forEach(obj, function(value, key) {
  12716. if (isArray(value)) {
  12717. forEach(value, function(arrayValue) {
  12718. parts.push(encodeUriQuery(key, true) +
  12719. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  12720. });
  12721. } else {
  12722. parts.push(encodeUriQuery(key, true) +
  12723. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  12724. }
  12725. });
  12726. return parts.length ? parts.join('&') : '';
  12727. }
  12728. /**
  12729. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  12730. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  12731. * segments:
  12732. * segment = *pchar
  12733. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  12734. * pct-encoded = "%" HEXDIG HEXDIG
  12735. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  12736. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  12737. * / "*" / "+" / "," / ";" / "="
  12738. */
  12739. function encodeUriSegment(val) {
  12740. return encodeUriQuery(val, true).
  12741. replace(/%26/gi, '&').
  12742. replace(/%3D/gi, '=').
  12743. replace(/%2B/gi, '+');
  12744. }
  12745. /**
  12746. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  12747. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  12748. * encoded per http://tools.ietf.org/html/rfc3986:
  12749. * query = *( pchar / "/" / "?" )
  12750. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  12751. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  12752. * pct-encoded = "%" HEXDIG HEXDIG
  12753. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  12754. * / "*" / "+" / "," / ";" / "="
  12755. */
  12756. function encodeUriQuery(val, pctEncodeSpaces) {
  12757. return encodeURIComponent(val).
  12758. replace(/%40/gi, '@').
  12759. replace(/%3A/gi, ':').
  12760. replace(/%24/g, '$').
  12761. replace(/%2C/gi, ',').
  12762. replace(/%3B/gi, ';').
  12763. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  12764. }
  12765. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  12766. function getNgAttribute(element, ngAttr) {
  12767. var attr, i, ii = ngAttrPrefixes.length;
  12768. for (i = 0; i < ii; ++i) {
  12769. attr = ngAttrPrefixes[i] + ngAttr;
  12770. if (isString(attr = element.getAttribute(attr))) {
  12771. return attr;
  12772. }
  12773. }
  12774. return null;
  12775. }
  12776. /**
  12777. * @ngdoc directive
  12778. * @name ngApp
  12779. * @module ng
  12780. *
  12781. * @element ANY
  12782. * @param {angular.Module} ngApp an optional application
  12783. * {@link angular.module module} name to load.
  12784. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  12785. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  12786. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  12787. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  12788. * tracking down the root of these bugs.
  12789. *
  12790. * @description
  12791. *
  12792. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  12793. * designates the **root element** of the application and is typically placed near the root element
  12794. * of the page - e.g. on the `<body>` or `<html>` tags.
  12795. *
  12796. * There are a few things to keep in mind when using `ngApp`:
  12797. * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  12798. * found in the document will be used to define the root element to auto-bootstrap as an
  12799. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  12800. * {@link angular.bootstrap} instead.
  12801. * - AngularJS applications cannot be nested within each other.
  12802. * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`.
  12803. * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and
  12804. * {@link ngRoute.ngView `ngView`}.
  12805. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  12806. * causing animations to stop working and making the injector inaccessible from outside the app.
  12807. *
  12808. * You can specify an **AngularJS module** to be used as the root module for the application. This
  12809. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  12810. * should contain the application code needed or have dependencies on other modules that will
  12811. * contain the code. See {@link angular.module} for more information.
  12812. *
  12813. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  12814. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  12815. * would not be resolved to `3`.
  12816. *
  12817. * `ngApp` is the easiest, and most common way to bootstrap an application.
  12818. *
  12819. <example module="ngAppDemo">
  12820. <file name="index.html">
  12821. <div ng-controller="ngAppDemoController">
  12822. I can add: {{a}} + {{b}} = {{ a+b }}
  12823. </div>
  12824. </file>
  12825. <file name="script.js">
  12826. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  12827. $scope.a = 1;
  12828. $scope.b = 2;
  12829. });
  12830. </file>
  12831. </example>
  12832. *
  12833. * Using `ngStrictDi`, you would see something like this:
  12834. *
  12835. <example ng-app-included="true">
  12836. <file name="index.html">
  12837. <div ng-app="ngAppStrictDemo" ng-strict-di>
  12838. <div ng-controller="GoodController1">
  12839. I can add: {{a}} + {{b}} = {{ a+b }}
  12840. <p>This renders because the controller does not fail to
  12841. instantiate, by using explicit annotation style (see
  12842. script.js for details)
  12843. </p>
  12844. </div>
  12845. <div ng-controller="GoodController2">
  12846. Name: <input ng-model="name"><br />
  12847. Hello, {{name}}!
  12848. <p>This renders because the controller does not fail to
  12849. instantiate, by using explicit annotation style
  12850. (see script.js for details)
  12851. </p>
  12852. </div>
  12853. <div ng-controller="BadController">
  12854. I can add: {{a}} + {{b}} = {{ a+b }}
  12855. <p>The controller could not be instantiated, due to relying
  12856. on automatic function annotations (which are disabled in
  12857. strict mode). As such, the content of this section is not
  12858. interpolated, and there should be an error in your web console.
  12859. </p>
  12860. </div>
  12861. </div>
  12862. </file>
  12863. <file name="script.js">
  12864. angular.module('ngAppStrictDemo', [])
  12865. // BadController will fail to instantiate, due to relying on automatic function annotation,
  12866. // rather than an explicit annotation
  12867. .controller('BadController', function($scope) {
  12868. $scope.a = 1;
  12869. $scope.b = 2;
  12870. })
  12871. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  12872. // due to using explicit annotations using the array style and $inject property, respectively.
  12873. .controller('GoodController1', ['$scope', function($scope) {
  12874. $scope.a = 1;
  12875. $scope.b = 2;
  12876. }])
  12877. .controller('GoodController2', GoodController2);
  12878. function GoodController2($scope) {
  12879. $scope.name = "World";
  12880. }
  12881. GoodController2.$inject = ['$scope'];
  12882. </file>
  12883. <file name="style.css">
  12884. div[ng-controller] {
  12885. margin-bottom: 1em;
  12886. -webkit-border-radius: 4px;
  12887. border-radius: 4px;
  12888. border: 1px solid;
  12889. padding: .5em;
  12890. }
  12891. div[ng-controller^=Good] {
  12892. border-color: #d6e9c6;
  12893. background-color: #dff0d8;
  12894. color: #3c763d;
  12895. }
  12896. div[ng-controller^=Bad] {
  12897. border-color: #ebccd1;
  12898. background-color: #f2dede;
  12899. color: #a94442;
  12900. margin-bottom: 0;
  12901. }
  12902. </file>
  12903. </example>
  12904. */
  12905. function angularInit(element, bootstrap) {
  12906. var appElement,
  12907. module,
  12908. config = {};
  12909. // The element `element` has priority over any other element
  12910. forEach(ngAttrPrefixes, function(prefix) {
  12911. var name = prefix + 'app';
  12912. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  12913. appElement = element;
  12914. module = element.getAttribute(name);
  12915. }
  12916. });
  12917. forEach(ngAttrPrefixes, function(prefix) {
  12918. var name = prefix + 'app';
  12919. var candidate;
  12920. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  12921. appElement = candidate;
  12922. module = candidate.getAttribute(name);
  12923. }
  12924. });
  12925. if (appElement) {
  12926. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  12927. bootstrap(appElement, module ? [module] : [], config);
  12928. }
  12929. }
  12930. /**
  12931. * @ngdoc function
  12932. * @name angular.bootstrap
  12933. * @module ng
  12934. * @description
  12935. * Use this function to manually start up angular application.
  12936. *
  12937. * For more information, see the {@link guide/bootstrap Bootstrap guide}.
  12938. *
  12939. * Angular will detect if it has been loaded into the browser more than once and only allow the
  12940. * first loaded script to be bootstrapped and will report a warning to the browser console for
  12941. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  12942. * multiple instances of Angular try to work on the DOM.
  12943. *
  12944. * <div class="alert alert-warning">
  12945. * **Note:** Protractor based end-to-end tests cannot use this function to bootstrap manually.
  12946. * They must use {@link ng.directive:ngApp ngApp}.
  12947. * </div>
  12948. *
  12949. * <div class="alert alert-warning">
  12950. * **Note:** Do not bootstrap the app on an element with a directive that uses {@link ng.$compile#transclusion transclusion},
  12951. * such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and {@link ngRoute.ngView `ngView`}.
  12952. * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector},
  12953. * causing animations to stop working and making the injector inaccessible from outside the app.
  12954. * </div>
  12955. *
  12956. * ```html
  12957. * <!doctype html>
  12958. * <html>
  12959. * <body>
  12960. * <div ng-controller="WelcomeController">
  12961. * {{greeting}}
  12962. * </div>
  12963. *
  12964. * <script src="angular.js"></script>
  12965. * <script>
  12966. * var app = angular.module('demo', [])
  12967. * .controller('WelcomeController', function($scope) {
  12968. * $scope.greeting = 'Welcome!';
  12969. * });
  12970. * angular.bootstrap(document, ['demo']);
  12971. * </script>
  12972. * </body>
  12973. * </html>
  12974. * ```
  12975. *
  12976. * @param {DOMElement} element DOM element which is the root of angular application.
  12977. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  12978. * Each item in the array should be the name of a predefined module or a (DI annotated)
  12979. * function that will be invoked by the injector as a `config` block.
  12980. * See: {@link angular.module modules}
  12981. * @param {Object=} config an object for defining configuration options for the application. The
  12982. * following keys are supported:
  12983. *
  12984. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  12985. * assist in finding bugs which break minified code. Defaults to `false`.
  12986. *
  12987. * @returns {auto.$injector} Returns the newly created injector for this app.
  12988. */
  12989. function bootstrap(element, modules, config) {
  12990. if (!isObject(config)) config = {};
  12991. var defaultConfig = {
  12992. strictDi: false
  12993. };
  12994. config = extend(defaultConfig, config);
  12995. var doBootstrap = function() {
  12996. element = jqLite(element);
  12997. if (element.injector()) {
  12998. var tag = (element[0] === document) ? 'document' : startingTag(element);
  12999. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  13000. throw ngMinErr(
  13001. 'btstrpd',
  13002. "App Already Bootstrapped with this Element '{0}'",
  13003. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  13004. }
  13005. modules = modules || [];
  13006. modules.unshift(['$provide', function($provide) {
  13007. $provide.value('$rootElement', element);
  13008. }]);
  13009. if (config.debugInfoEnabled) {
  13010. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  13011. modules.push(['$compileProvider', function($compileProvider) {
  13012. $compileProvider.debugInfoEnabled(true);
  13013. }]);
  13014. }
  13015. modules.unshift('ng');
  13016. var injector = createInjector(modules, config.strictDi);
  13017. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  13018. function bootstrapApply(scope, element, compile, injector) {
  13019. scope.$apply(function() {
  13020. element.data('$injector', injector);
  13021. compile(element)(scope);
  13022. });
  13023. }]
  13024. );
  13025. return injector;
  13026. };
  13027. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  13028. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  13029. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  13030. config.debugInfoEnabled = true;
  13031. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  13032. }
  13033. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  13034. return doBootstrap();
  13035. }
  13036. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  13037. angular.resumeBootstrap = function(extraModules) {
  13038. forEach(extraModules, function(module) {
  13039. modules.push(module);
  13040. });
  13041. return doBootstrap();
  13042. };
  13043. if (isFunction(angular.resumeDeferredBootstrap)) {
  13044. angular.resumeDeferredBootstrap();
  13045. }
  13046. }
  13047. /**
  13048. * @ngdoc function
  13049. * @name angular.reloadWithDebugInfo
  13050. * @module ng
  13051. * @description
  13052. * Use this function to reload the current application with debug information turned on.
  13053. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  13054. *
  13055. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  13056. */
  13057. function reloadWithDebugInfo() {
  13058. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  13059. window.location.reload();
  13060. }
  13061. /**
  13062. * @name angular.getTestability
  13063. * @module ng
  13064. * @description
  13065. * Get the testability service for the instance of Angular on the given
  13066. * element.
  13067. * @param {DOMElement} element DOM element which is the root of angular application.
  13068. */
  13069. function getTestability(rootElement) {
  13070. var injector = angular.element(rootElement).injector();
  13071. if (!injector) {
  13072. throw ngMinErr('test',
  13073. 'no injector found for element argument to getTestability');
  13074. }
  13075. return injector.get('$$testability');
  13076. }
  13077. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  13078. function snake_case(name, separator) {
  13079. separator = separator || '_';
  13080. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  13081. return (pos ? separator : '') + letter.toLowerCase();
  13082. });
  13083. }
  13084. var bindJQueryFired = false;
  13085. function bindJQuery() {
  13086. var originalCleanData;
  13087. if (bindJQueryFired) {
  13088. return;
  13089. }
  13090. // bind to jQuery if present;
  13091. var jqName = jq();
  13092. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  13093. !jqName ? undefined : // use jqLite
  13094. window[jqName]; // use jQuery specified by `ngJq`
  13095. // Use jQuery if it exists with proper functionality, otherwise default to us.
  13096. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  13097. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  13098. // versions. It will not work for sure with jQuery <1.7, though.
  13099. if (jQuery && jQuery.fn.on) {
  13100. jqLite = jQuery;
  13101. extend(jQuery.fn, {
  13102. scope: JQLitePrototype.scope,
  13103. isolateScope: JQLitePrototype.isolateScope,
  13104. controller: JQLitePrototype.controller,
  13105. injector: JQLitePrototype.injector,
  13106. inheritedData: JQLitePrototype.inheritedData
  13107. });
  13108. // All nodes removed from the DOM via various jQuery APIs like .remove()
  13109. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  13110. // the $destroy event on all removed nodes.
  13111. originalCleanData = jQuery.cleanData;
  13112. jQuery.cleanData = function(elems) {
  13113. var events;
  13114. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  13115. events = jQuery._data(elem, "events");
  13116. if (events && events.$destroy) {
  13117. jQuery(elem).triggerHandler('$destroy');
  13118. }
  13119. }
  13120. originalCleanData(elems);
  13121. };
  13122. } else {
  13123. jqLite = JQLite;
  13124. }
  13125. angular.element = jqLite;
  13126. // Prevent double-proxying.
  13127. bindJQueryFired = true;
  13128. }
  13129. /**
  13130. * throw error if the argument is falsy.
  13131. */
  13132. function assertArg(arg, name, reason) {
  13133. if (!arg) {
  13134. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  13135. }
  13136. return arg;
  13137. }
  13138. function assertArgFn(arg, name, acceptArrayAnnotation) {
  13139. if (acceptArrayAnnotation && isArray(arg)) {
  13140. arg = arg[arg.length - 1];
  13141. }
  13142. assertArg(isFunction(arg), name, 'not a function, got ' +
  13143. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  13144. return arg;
  13145. }
  13146. /**
  13147. * throw error if the name given is hasOwnProperty
  13148. * @param {String} name the name to test
  13149. * @param {String} context the context in which the name is used, such as module or directive
  13150. */
  13151. function assertNotHasOwnProperty(name, context) {
  13152. if (name === 'hasOwnProperty') {
  13153. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  13154. }
  13155. }
  13156. /**
  13157. * Return the value accessible from the object by path. Any undefined traversals are ignored
  13158. * @param {Object} obj starting object
  13159. * @param {String} path path to traverse
  13160. * @param {boolean} [bindFnToScope=true]
  13161. * @returns {Object} value as accessible by path
  13162. */
  13163. //TODO(misko): this function needs to be removed
  13164. function getter(obj, path, bindFnToScope) {
  13165. if (!path) return obj;
  13166. var keys = path.split('.');
  13167. var key;
  13168. var lastInstance = obj;
  13169. var len = keys.length;
  13170. for (var i = 0; i < len; i++) {
  13171. key = keys[i];
  13172. if (obj) {
  13173. obj = (lastInstance = obj)[key];
  13174. }
  13175. }
  13176. if (!bindFnToScope && isFunction(obj)) {
  13177. return bind(lastInstance, obj);
  13178. }
  13179. return obj;
  13180. }
  13181. /**
  13182. * Return the DOM siblings between the first and last node in the given array.
  13183. * @param {Array} array like object
  13184. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  13185. */
  13186. function getBlockNodes(nodes) {
  13187. // TODO(perf): update `nodes` instead of creating a new object?
  13188. var node = nodes[0];
  13189. var endNode = nodes[nodes.length - 1];
  13190. var blockNodes;
  13191. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  13192. if (blockNodes || nodes[i] !== node) {
  13193. if (!blockNodes) {
  13194. blockNodes = jqLite(slice.call(nodes, 0, i));
  13195. }
  13196. blockNodes.push(node);
  13197. }
  13198. }
  13199. return blockNodes || nodes;
  13200. }
  13201. /**
  13202. * Creates a new object without a prototype. This object is useful for lookup without having to
  13203. * guard against prototypically inherited properties via hasOwnProperty.
  13204. *
  13205. * Related micro-benchmarks:
  13206. * - http://jsperf.com/object-create2
  13207. * - http://jsperf.com/proto-map-lookup/2
  13208. * - http://jsperf.com/for-in-vs-object-keys2
  13209. *
  13210. * @returns {Object}
  13211. */
  13212. function createMap() {
  13213. return Object.create(null);
  13214. }
  13215. var NODE_TYPE_ELEMENT = 1;
  13216. var NODE_TYPE_ATTRIBUTE = 2;
  13217. var NODE_TYPE_TEXT = 3;
  13218. var NODE_TYPE_COMMENT = 8;
  13219. var NODE_TYPE_DOCUMENT = 9;
  13220. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  13221. /**
  13222. * @ngdoc type
  13223. * @name angular.Module
  13224. * @module ng
  13225. * @description
  13226. *
  13227. * Interface for configuring angular {@link angular.module modules}.
  13228. */
  13229. function setupModuleLoader(window) {
  13230. var $injectorMinErr = minErr('$injector');
  13231. var ngMinErr = minErr('ng');
  13232. function ensure(obj, name, factory) {
  13233. return obj[name] || (obj[name] = factory());
  13234. }
  13235. var angular = ensure(window, 'angular', Object);
  13236. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  13237. angular.$$minErr = angular.$$minErr || minErr;
  13238. return ensure(angular, 'module', function() {
  13239. /** @type {Object.<string, angular.Module>} */
  13240. var modules = {};
  13241. /**
  13242. * @ngdoc function
  13243. * @name angular.module
  13244. * @module ng
  13245. * @description
  13246. *
  13247. * The `angular.module` is a global place for creating, registering and retrieving Angular
  13248. * modules.
  13249. * All modules (angular core or 3rd party) that should be available to an application must be
  13250. * registered using this mechanism.
  13251. *
  13252. * Passing one argument retrieves an existing {@link angular.Module},
  13253. * whereas passing more than one argument creates a new {@link angular.Module}
  13254. *
  13255. *
  13256. * # Module
  13257. *
  13258. * A module is a collection of services, directives, controllers, filters, and configuration information.
  13259. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  13260. *
  13261. * ```js
  13262. * // Create a new module
  13263. * var myModule = angular.module('myModule', []);
  13264. *
  13265. * // register a new service
  13266. * myModule.value('appName', 'MyCoolApp');
  13267. *
  13268. * // configure existing services inside initialization blocks.
  13269. * myModule.config(['$locationProvider', function($locationProvider) {
  13270. * // Configure existing providers
  13271. * $locationProvider.hashPrefix('!');
  13272. * }]);
  13273. * ```
  13274. *
  13275. * Then you can create an injector and load your modules like this:
  13276. *
  13277. * ```js
  13278. * var injector = angular.injector(['ng', 'myModule'])
  13279. * ```
  13280. *
  13281. * However it's more likely that you'll just use
  13282. * {@link ng.directive:ngApp ngApp} or
  13283. * {@link angular.bootstrap} to simplify this process for you.
  13284. *
  13285. * @param {!string} name The name of the module to create or retrieve.
  13286. * @param {!Array.<string>=} requires If specified then new module is being created. If
  13287. * unspecified then the module is being retrieved for further configuration.
  13288. * @param {Function=} configFn Optional configuration function for the module. Same as
  13289. * {@link angular.Module#config Module#config()}.
  13290. * @returns {angular.Module} new module with the {@link angular.Module} api.
  13291. */
  13292. return function module(name, requires, configFn) {
  13293. var assertNotHasOwnProperty = function(name, context) {
  13294. if (name === 'hasOwnProperty') {
  13295. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  13296. }
  13297. };
  13298. assertNotHasOwnProperty(name, 'module');
  13299. if (requires && modules.hasOwnProperty(name)) {
  13300. modules[name] = null;
  13301. }
  13302. return ensure(modules, name, function() {
  13303. if (!requires) {
  13304. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  13305. "the module name or forgot to load it. If registering a module ensure that you " +
  13306. "specify the dependencies as the second argument.", name);
  13307. }
  13308. /** @type {!Array.<Array.<*>>} */
  13309. var invokeQueue = [];
  13310. /** @type {!Array.<Function>} */
  13311. var configBlocks = [];
  13312. /** @type {!Array.<Function>} */
  13313. var runBlocks = [];
  13314. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  13315. /** @type {angular.Module} */
  13316. var moduleInstance = {
  13317. // Private state
  13318. _invokeQueue: invokeQueue,
  13319. _configBlocks: configBlocks,
  13320. _runBlocks: runBlocks,
  13321. /**
  13322. * @ngdoc property
  13323. * @name angular.Module#requires
  13324. * @module ng
  13325. *
  13326. * @description
  13327. * Holds the list of modules which the injector will load before the current module is
  13328. * loaded.
  13329. */
  13330. requires: requires,
  13331. /**
  13332. * @ngdoc property
  13333. * @name angular.Module#name
  13334. * @module ng
  13335. *
  13336. * @description
  13337. * Name of the module.
  13338. */
  13339. name: name,
  13340. /**
  13341. * @ngdoc method
  13342. * @name angular.Module#provider
  13343. * @module ng
  13344. * @param {string} name service name
  13345. * @param {Function} providerType Construction function for creating new instance of the
  13346. * service.
  13347. * @description
  13348. * See {@link auto.$provide#provider $provide.provider()}.
  13349. */
  13350. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  13351. /**
  13352. * @ngdoc method
  13353. * @name angular.Module#factory
  13354. * @module ng
  13355. * @param {string} name service name
  13356. * @param {Function} providerFunction Function for creating new instance of the service.
  13357. * @description
  13358. * See {@link auto.$provide#factory $provide.factory()}.
  13359. */
  13360. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  13361. /**
  13362. * @ngdoc method
  13363. * @name angular.Module#service
  13364. * @module ng
  13365. * @param {string} name service name
  13366. * @param {Function} constructor A constructor function that will be instantiated.
  13367. * @description
  13368. * See {@link auto.$provide#service $provide.service()}.
  13369. */
  13370. service: invokeLaterAndSetModuleName('$provide', 'service'),
  13371. /**
  13372. * @ngdoc method
  13373. * @name angular.Module#value
  13374. * @module ng
  13375. * @param {string} name service name
  13376. * @param {*} object Service instance object.
  13377. * @description
  13378. * See {@link auto.$provide#value $provide.value()}.
  13379. */
  13380. value: invokeLater('$provide', 'value'),
  13381. /**
  13382. * @ngdoc method
  13383. * @name angular.Module#constant
  13384. * @module ng
  13385. * @param {string} name constant name
  13386. * @param {*} object Constant value.
  13387. * @description
  13388. * Because the constants are fixed, they get applied before other provide methods.
  13389. * See {@link auto.$provide#constant $provide.constant()}.
  13390. */
  13391. constant: invokeLater('$provide', 'constant', 'unshift'),
  13392. /**
  13393. * @ngdoc method
  13394. * @name angular.Module#decorator
  13395. * @module ng
  13396. * @param {string} The name of the service to decorate.
  13397. * @param {Function} This function will be invoked when the service needs to be
  13398. * instantiated and should return the decorated service instance.
  13399. * @description
  13400. * See {@link auto.$provide#decorator $provide.decorator()}.
  13401. */
  13402. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  13403. /**
  13404. * @ngdoc method
  13405. * @name angular.Module#animation
  13406. * @module ng
  13407. * @param {string} name animation name
  13408. * @param {Function} animationFactory Factory function for creating new instance of an
  13409. * animation.
  13410. * @description
  13411. *
  13412. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  13413. *
  13414. *
  13415. * Defines an animation hook that can be later used with
  13416. * {@link $animate $animate} service and directives that use this service.
  13417. *
  13418. * ```js
  13419. * module.animation('.animation-name', function($inject1, $inject2) {
  13420. * return {
  13421. * eventName : function(element, done) {
  13422. * //code to run the animation
  13423. * //once complete, then run done()
  13424. * return function cancellationFunction(element) {
  13425. * //code to cancel the animation
  13426. * }
  13427. * }
  13428. * }
  13429. * })
  13430. * ```
  13431. *
  13432. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  13433. * {@link ngAnimate ngAnimate module} for more information.
  13434. */
  13435. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  13436. /**
  13437. * @ngdoc method
  13438. * @name angular.Module#filter
  13439. * @module ng
  13440. * @param {string} name Filter name - this must be a valid angular expression identifier
  13441. * @param {Function} filterFactory Factory function for creating new instance of filter.
  13442. * @description
  13443. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  13444. *
  13445. * <div class="alert alert-warning">
  13446. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  13447. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  13448. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  13449. * (`myapp_subsection_filterx`).
  13450. * </div>
  13451. */
  13452. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  13453. /**
  13454. * @ngdoc method
  13455. * @name angular.Module#controller
  13456. * @module ng
  13457. * @param {string|Object} name Controller name, or an object map of controllers where the
  13458. * keys are the names and the values are the constructors.
  13459. * @param {Function} constructor Controller constructor function.
  13460. * @description
  13461. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  13462. */
  13463. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  13464. /**
  13465. * @ngdoc method
  13466. * @name angular.Module#directive
  13467. * @module ng
  13468. * @param {string|Object} name Directive name, or an object map of directives where the
  13469. * keys are the names and the values are the factories.
  13470. * @param {Function} directiveFactory Factory function for creating new instance of
  13471. * directives.
  13472. * @description
  13473. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  13474. */
  13475. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  13476. /**
  13477. * @ngdoc method
  13478. * @name angular.Module#component
  13479. * @module ng
  13480. * @param {string} name Name of the component in camel-case (i.e. myComp which will match as my-comp)
  13481. * @param {Object} options Component definition object (a simplified
  13482. * {@link ng.$compile#directive-definition-object directive definition object})
  13483. *
  13484. * @description
  13485. * See {@link ng.$compileProvider#component $compileProvider.component()}.
  13486. */
  13487. component: invokeLaterAndSetModuleName('$compileProvider', 'component'),
  13488. /**
  13489. * @ngdoc method
  13490. * @name angular.Module#config
  13491. * @module ng
  13492. * @param {Function} configFn Execute this function on module load. Useful for service
  13493. * configuration.
  13494. * @description
  13495. * Use this method to register work which needs to be performed on module loading.
  13496. * For more about how to configure services, see
  13497. * {@link providers#provider-recipe Provider Recipe}.
  13498. */
  13499. config: config,
  13500. /**
  13501. * @ngdoc method
  13502. * @name angular.Module#run
  13503. * @module ng
  13504. * @param {Function} initializationFn Execute this function after injector creation.
  13505. * Useful for application initialization.
  13506. * @description
  13507. * Use this method to register work which should be performed when the injector is done
  13508. * loading all modules.
  13509. */
  13510. run: function(block) {
  13511. runBlocks.push(block);
  13512. return this;
  13513. }
  13514. };
  13515. if (configFn) {
  13516. config(configFn);
  13517. }
  13518. return moduleInstance;
  13519. /**
  13520. * @param {string} provider
  13521. * @param {string} method
  13522. * @param {String=} insertMethod
  13523. * @returns {angular.Module}
  13524. */
  13525. function invokeLater(provider, method, insertMethod, queue) {
  13526. if (!queue) queue = invokeQueue;
  13527. return function() {
  13528. queue[insertMethod || 'push']([provider, method, arguments]);
  13529. return moduleInstance;
  13530. };
  13531. }
  13532. /**
  13533. * @param {string} provider
  13534. * @param {string} method
  13535. * @returns {angular.Module}
  13536. */
  13537. function invokeLaterAndSetModuleName(provider, method) {
  13538. return function(recipeName, factoryFunction) {
  13539. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  13540. invokeQueue.push([provider, method, arguments]);
  13541. return moduleInstance;
  13542. };
  13543. }
  13544. });
  13545. };
  13546. });
  13547. }
  13548. /* global: toDebugString: true */
  13549. function serializeObject(obj) {
  13550. var seen = [];
  13551. return JSON.stringify(obj, function(key, val) {
  13552. val = toJsonReplacer(key, val);
  13553. if (isObject(val)) {
  13554. if (seen.indexOf(val) >= 0) return '...';
  13555. seen.push(val);
  13556. }
  13557. return val;
  13558. });
  13559. }
  13560. function toDebugString(obj) {
  13561. if (typeof obj === 'function') {
  13562. return obj.toString().replace(/ \{[\s\S]*$/, '');
  13563. } else if (isUndefined(obj)) {
  13564. return 'undefined';
  13565. } else if (typeof obj !== 'string') {
  13566. return serializeObject(obj);
  13567. }
  13568. return obj;
  13569. }
  13570. /* global angularModule: true,
  13571. version: true,
  13572. $CompileProvider,
  13573. htmlAnchorDirective,
  13574. inputDirective,
  13575. inputDirective,
  13576. formDirective,
  13577. scriptDirective,
  13578. selectDirective,
  13579. styleDirective,
  13580. optionDirective,
  13581. ngBindDirective,
  13582. ngBindHtmlDirective,
  13583. ngBindTemplateDirective,
  13584. ngClassDirective,
  13585. ngClassEvenDirective,
  13586. ngClassOddDirective,
  13587. ngCloakDirective,
  13588. ngControllerDirective,
  13589. ngFormDirective,
  13590. ngHideDirective,
  13591. ngIfDirective,
  13592. ngIncludeDirective,
  13593. ngIncludeFillContentDirective,
  13594. ngInitDirective,
  13595. ngNonBindableDirective,
  13596. ngPluralizeDirective,
  13597. ngRepeatDirective,
  13598. ngShowDirective,
  13599. ngStyleDirective,
  13600. ngSwitchDirective,
  13601. ngSwitchWhenDirective,
  13602. ngSwitchDefaultDirective,
  13603. ngOptionsDirective,
  13604. ngTranscludeDirective,
  13605. ngModelDirective,
  13606. ngListDirective,
  13607. ngChangeDirective,
  13608. patternDirective,
  13609. patternDirective,
  13610. requiredDirective,
  13611. requiredDirective,
  13612. minlengthDirective,
  13613. minlengthDirective,
  13614. maxlengthDirective,
  13615. maxlengthDirective,
  13616. ngValueDirective,
  13617. ngModelOptionsDirective,
  13618. ngAttributeAliasDirectives,
  13619. ngEventDirectives,
  13620. $AnchorScrollProvider,
  13621. $AnimateProvider,
  13622. $CoreAnimateCssProvider,
  13623. $$CoreAnimateJsProvider,
  13624. $$CoreAnimateQueueProvider,
  13625. $$AnimateRunnerFactoryProvider,
  13626. $$AnimateAsyncRunFactoryProvider,
  13627. $BrowserProvider,
  13628. $CacheFactoryProvider,
  13629. $ControllerProvider,
  13630. $DateProvider,
  13631. $DocumentProvider,
  13632. $ExceptionHandlerProvider,
  13633. $FilterProvider,
  13634. $$ForceReflowProvider,
  13635. $InterpolateProvider,
  13636. $IntervalProvider,
  13637. $$HashMapProvider,
  13638. $HttpProvider,
  13639. $HttpParamSerializerProvider,
  13640. $HttpParamSerializerJQLikeProvider,
  13641. $HttpBackendProvider,
  13642. $xhrFactoryProvider,
  13643. $LocationProvider,
  13644. $LogProvider,
  13645. $ParseProvider,
  13646. $RootScopeProvider,
  13647. $QProvider,
  13648. $$QProvider,
  13649. $$SanitizeUriProvider,
  13650. $SceProvider,
  13651. $SceDelegateProvider,
  13652. $SnifferProvider,
  13653. $TemplateCacheProvider,
  13654. $TemplateRequestProvider,
  13655. $$TestabilityProvider,
  13656. $TimeoutProvider,
  13657. $$RAFProvider,
  13658. $WindowProvider,
  13659. $$jqLiteProvider,
  13660. $$CookieReaderProvider
  13661. */
  13662. /**
  13663. * @ngdoc object
  13664. * @name angular.version
  13665. * @module ng
  13666. * @description
  13667. * An object that contains information about the current AngularJS version.
  13668. *
  13669. * This object has the following properties:
  13670. *
  13671. * - `full` – `{string}` – Full version string, such as "0.9.18".
  13672. * - `major` – `{number}` – Major version number, such as "0".
  13673. * - `minor` – `{number}` – Minor version number, such as "9".
  13674. * - `dot` – `{number}` – Dot version number, such as "18".
  13675. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  13676. */
  13677. var version = {
  13678. full: '1.5.3', // all of these placeholder strings will be replaced by grunt's
  13679. major: 1, // package task
  13680. minor: 5,
  13681. dot: 3,
  13682. codeName: 'diplohaplontic-meiosis'
  13683. };
  13684. function publishExternalAPI(angular) {
  13685. extend(angular, {
  13686. 'bootstrap': bootstrap,
  13687. 'copy': copy,
  13688. 'extend': extend,
  13689. 'merge': merge,
  13690. 'equals': equals,
  13691. 'element': jqLite,
  13692. 'forEach': forEach,
  13693. 'injector': createInjector,
  13694. 'noop': noop,
  13695. 'bind': bind,
  13696. 'toJson': toJson,
  13697. 'fromJson': fromJson,
  13698. 'identity': identity,
  13699. 'isUndefined': isUndefined,
  13700. 'isDefined': isDefined,
  13701. 'isString': isString,
  13702. 'isFunction': isFunction,
  13703. 'isObject': isObject,
  13704. 'isNumber': isNumber,
  13705. 'isElement': isElement,
  13706. 'isArray': isArray,
  13707. 'version': version,
  13708. 'isDate': isDate,
  13709. 'lowercase': lowercase,
  13710. 'uppercase': uppercase,
  13711. 'callbacks': {counter: 0},
  13712. 'getTestability': getTestability,
  13713. '$$minErr': minErr,
  13714. '$$csp': csp,
  13715. 'reloadWithDebugInfo': reloadWithDebugInfo
  13716. });
  13717. angularModule = setupModuleLoader(window);
  13718. angularModule('ng', ['ngLocale'], ['$provide',
  13719. function ngModule($provide) {
  13720. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  13721. $provide.provider({
  13722. $$sanitizeUri: $$SanitizeUriProvider
  13723. });
  13724. $provide.provider('$compile', $CompileProvider).
  13725. directive({
  13726. a: htmlAnchorDirective,
  13727. input: inputDirective,
  13728. textarea: inputDirective,
  13729. form: formDirective,
  13730. script: scriptDirective,
  13731. select: selectDirective,
  13732. style: styleDirective,
  13733. option: optionDirective,
  13734. ngBind: ngBindDirective,
  13735. ngBindHtml: ngBindHtmlDirective,
  13736. ngBindTemplate: ngBindTemplateDirective,
  13737. ngClass: ngClassDirective,
  13738. ngClassEven: ngClassEvenDirective,
  13739. ngClassOdd: ngClassOddDirective,
  13740. ngCloak: ngCloakDirective,
  13741. ngController: ngControllerDirective,
  13742. ngForm: ngFormDirective,
  13743. ngHide: ngHideDirective,
  13744. ngIf: ngIfDirective,
  13745. ngInclude: ngIncludeDirective,
  13746. ngInit: ngInitDirective,
  13747. ngNonBindable: ngNonBindableDirective,
  13748. ngPluralize: ngPluralizeDirective,
  13749. ngRepeat: ngRepeatDirective,
  13750. ngShow: ngShowDirective,
  13751. ngStyle: ngStyleDirective,
  13752. ngSwitch: ngSwitchDirective,
  13753. ngSwitchWhen: ngSwitchWhenDirective,
  13754. ngSwitchDefault: ngSwitchDefaultDirective,
  13755. ngOptions: ngOptionsDirective,
  13756. ngTransclude: ngTranscludeDirective,
  13757. ngModel: ngModelDirective,
  13758. ngList: ngListDirective,
  13759. ngChange: ngChangeDirective,
  13760. pattern: patternDirective,
  13761. ngPattern: patternDirective,
  13762. required: requiredDirective,
  13763. ngRequired: requiredDirective,
  13764. minlength: minlengthDirective,
  13765. ngMinlength: minlengthDirective,
  13766. maxlength: maxlengthDirective,
  13767. ngMaxlength: maxlengthDirective,
  13768. ngValue: ngValueDirective,
  13769. ngModelOptions: ngModelOptionsDirective
  13770. }).
  13771. directive({
  13772. ngInclude: ngIncludeFillContentDirective
  13773. }).
  13774. directive(ngAttributeAliasDirectives).
  13775. directive(ngEventDirectives);
  13776. $provide.provider({
  13777. $anchorScroll: $AnchorScrollProvider,
  13778. $animate: $AnimateProvider,
  13779. $animateCss: $CoreAnimateCssProvider,
  13780. $$animateJs: $$CoreAnimateJsProvider,
  13781. $$animateQueue: $$CoreAnimateQueueProvider,
  13782. $$AnimateRunner: $$AnimateRunnerFactoryProvider,
  13783. $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider,
  13784. $browser: $BrowserProvider,
  13785. $cacheFactory: $CacheFactoryProvider,
  13786. $controller: $ControllerProvider,
  13787. $document: $DocumentProvider,
  13788. $exceptionHandler: $ExceptionHandlerProvider,
  13789. $filter: $FilterProvider,
  13790. $$forceReflow: $$ForceReflowProvider,
  13791. $interpolate: $InterpolateProvider,
  13792. $interval: $IntervalProvider,
  13793. $http: $HttpProvider,
  13794. $httpParamSerializer: $HttpParamSerializerProvider,
  13795. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  13796. $httpBackend: $HttpBackendProvider,
  13797. $xhrFactory: $xhrFactoryProvider,
  13798. $location: $LocationProvider,
  13799. $log: $LogProvider,
  13800. $parse: $ParseProvider,
  13801. $rootScope: $RootScopeProvider,
  13802. $q: $QProvider,
  13803. $$q: $$QProvider,
  13804. $sce: $SceProvider,
  13805. $sceDelegate: $SceDelegateProvider,
  13806. $sniffer: $SnifferProvider,
  13807. $templateCache: $TemplateCacheProvider,
  13808. $templateRequest: $TemplateRequestProvider,
  13809. $$testability: $$TestabilityProvider,
  13810. $timeout: $TimeoutProvider,
  13811. $window: $WindowProvider,
  13812. $$rAF: $$RAFProvider,
  13813. $$jqLite: $$jqLiteProvider,
  13814. $$HashMap: $$HashMapProvider,
  13815. $$cookieReader: $$CookieReaderProvider
  13816. });
  13817. }
  13818. ]);
  13819. }
  13820. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  13821. * Any commits to this file should be reviewed with security in mind. *
  13822. * Changes to this file can potentially create security vulnerabilities. *
  13823. * An approval from 2 Core members with history of modifying *
  13824. * this file is required. *
  13825. * *
  13826. * Does the change somehow allow for arbitrary javascript to be executed? *
  13827. * Or allows for someone to change the prototype of built-in objects? *
  13828. * Or gives undesired access to variables likes document or window? *
  13829. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  13830. /* global JQLitePrototype: true,
  13831. addEventListenerFn: true,
  13832. removeEventListenerFn: true,
  13833. BOOLEAN_ATTR: true,
  13834. ALIASED_ATTR: true,
  13835. */
  13836. //////////////////////////////////
  13837. //JQLite
  13838. //////////////////////////////////
  13839. /**
  13840. * @ngdoc function
  13841. * @name angular.element
  13842. * @module ng
  13843. * @kind function
  13844. *
  13845. * @description
  13846. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  13847. *
  13848. * If jQuery is available, `angular.element` is an alias for the
  13849. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  13850. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or **jqLite**.
  13851. *
  13852. * jqLite is a tiny, API-compatible subset of jQuery that allows
  13853. * Angular to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most
  13854. * commonly needed functionality with the goal of having a very small footprint.
  13855. *
  13856. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the
  13857. * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a
  13858. * specific version of jQuery if multiple versions exist on the page.
  13859. *
  13860. * <div class="alert alert-info">**Note:** All element references in Angular are always wrapped with jQuery or
  13861. * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.</div>
  13862. *
  13863. * <div class="alert alert-warning">**Note:** Keep in mind that this function will not find elements
  13864. * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)`
  13865. * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.</div>
  13866. *
  13867. * ## Angular's jqLite
  13868. * jqLite provides only the following jQuery methods:
  13869. *
  13870. * - [`addClass()`](http://api.jquery.com/addClass/)
  13871. * - [`after()`](http://api.jquery.com/after/)
  13872. * - [`append()`](http://api.jquery.com/append/)
  13873. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  13874. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  13875. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  13876. * - [`clone()`](http://api.jquery.com/clone/)
  13877. * - [`contents()`](http://api.jquery.com/contents/)
  13878. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`.
  13879. * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing.
  13880. * - [`data()`](http://api.jquery.com/data/)
  13881. * - [`detach()`](http://api.jquery.com/detach/)
  13882. * - [`empty()`](http://api.jquery.com/empty/)
  13883. * - [`eq()`](http://api.jquery.com/eq/)
  13884. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  13885. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  13886. * - [`html()`](http://api.jquery.com/html/)
  13887. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  13888. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  13889. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  13890. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  13891. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  13892. * - [`prepend()`](http://api.jquery.com/prepend/)
  13893. * - [`prop()`](http://api.jquery.com/prop/)
  13894. * - [`ready()`](http://api.jquery.com/ready/)
  13895. * - [`remove()`](http://api.jquery.com/remove/)
  13896. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  13897. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  13898. * - [`removeData()`](http://api.jquery.com/removeData/)
  13899. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  13900. * - [`text()`](http://api.jquery.com/text/)
  13901. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  13902. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  13903. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  13904. * - [`val()`](http://api.jquery.com/val/)
  13905. * - [`wrap()`](http://api.jquery.com/wrap/)
  13906. *
  13907. * ## jQuery/jqLite Extras
  13908. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  13909. *
  13910. * ### Events
  13911. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  13912. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  13913. * element before it is removed.
  13914. *
  13915. * ### Methods
  13916. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  13917. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  13918. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  13919. * `'ngModel'`).
  13920. * - `injector()` - retrieves the injector of the current element or its parent.
  13921. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  13922. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  13923. * be enabled.
  13924. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  13925. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  13926. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  13927. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  13928. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  13929. * parent element is reached.
  13930. *
  13931. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  13932. * @returns {Object} jQuery object.
  13933. */
  13934. JQLite.expando = 'ng339';
  13935. var jqCache = JQLite.cache = {},
  13936. jqId = 1,
  13937. addEventListenerFn = function(element, type, fn) {
  13938. element.addEventListener(type, fn, false);
  13939. },
  13940. removeEventListenerFn = function(element, type, fn) {
  13941. element.removeEventListener(type, fn, false);
  13942. };
  13943. /*
  13944. * !!! This is an undocumented "private" function !!!
  13945. */
  13946. JQLite._data = function(node) {
  13947. //jQuery always returns an object on cache miss
  13948. return this.cache[node[this.expando]] || {};
  13949. };
  13950. function jqNextId() { return ++jqId; }
  13951. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  13952. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  13953. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  13954. var jqLiteMinErr = minErr('jqLite');
  13955. /**
  13956. * Converts snake_case to camelCase.
  13957. * Also there is special case for Moz prefix starting with upper case letter.
  13958. * @param name Name to normalize
  13959. */
  13960. function camelCase(name) {
  13961. return name.
  13962. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  13963. return offset ? letter.toUpperCase() : letter;
  13964. }).
  13965. replace(MOZ_HACK_REGEXP, 'Moz$1');
  13966. }
  13967. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  13968. var HTML_REGEXP = /<|&#?\w+;/;
  13969. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  13970. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  13971. var wrapMap = {
  13972. 'option': [1, '<select multiple="multiple">', '</select>'],
  13973. 'thead': [1, '<table>', '</table>'],
  13974. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  13975. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  13976. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  13977. '_default': [0, "", ""]
  13978. };
  13979. wrapMap.optgroup = wrapMap.option;
  13980. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  13981. wrapMap.th = wrapMap.td;
  13982. function jqLiteIsTextNode(html) {
  13983. return !HTML_REGEXP.test(html);
  13984. }
  13985. function jqLiteAcceptsData(node) {
  13986. // The window object can accept data but has no nodeType
  13987. // Otherwise we are only interested in elements (1) and documents (9)
  13988. var nodeType = node.nodeType;
  13989. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  13990. }
  13991. function jqLiteHasData(node) {
  13992. for (var key in jqCache[node.ng339]) {
  13993. return true;
  13994. }
  13995. return false;
  13996. }
  13997. function jqLiteCleanData(nodes) {
  13998. for (var i = 0, ii = nodes.length; i < ii; i++) {
  13999. jqLiteRemoveData(nodes[i]);
  14000. }
  14001. }
  14002. function jqLiteBuildFragment(html, context) {
  14003. var tmp, tag, wrap,
  14004. fragment = context.createDocumentFragment(),
  14005. nodes = [], i;
  14006. if (jqLiteIsTextNode(html)) {
  14007. // Convert non-html into a text node
  14008. nodes.push(context.createTextNode(html));
  14009. } else {
  14010. // Convert html into DOM nodes
  14011. tmp = tmp || fragment.appendChild(context.createElement("div"));
  14012. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  14013. wrap = wrapMap[tag] || wrapMap._default;
  14014. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  14015. // Descend through wrappers to the right content
  14016. i = wrap[0];
  14017. while (i--) {
  14018. tmp = tmp.lastChild;
  14019. }
  14020. nodes = concat(nodes, tmp.childNodes);
  14021. tmp = fragment.firstChild;
  14022. tmp.textContent = "";
  14023. }
  14024. // Remove wrapper from fragment
  14025. fragment.textContent = "";
  14026. fragment.innerHTML = ""; // Clear inner HTML
  14027. forEach(nodes, function(node) {
  14028. fragment.appendChild(node);
  14029. });
  14030. return fragment;
  14031. }
  14032. function jqLiteParseHTML(html, context) {
  14033. context = context || document;
  14034. var parsed;
  14035. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  14036. return [context.createElement(parsed[1])];
  14037. }
  14038. if ((parsed = jqLiteBuildFragment(html, context))) {
  14039. return parsed.childNodes;
  14040. }
  14041. return [];
  14042. }
  14043. function jqLiteWrapNode(node, wrapper) {
  14044. var parent = node.parentNode;
  14045. if (parent) {
  14046. parent.replaceChild(wrapper, node);
  14047. }
  14048. wrapper.appendChild(node);
  14049. }
  14050. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  14051. var jqLiteContains = Node.prototype.contains || function(arg) {
  14052. // jshint bitwise: false
  14053. return !!(this.compareDocumentPosition(arg) & 16);
  14054. // jshint bitwise: true
  14055. };
  14056. /////////////////////////////////////////////
  14057. function JQLite(element) {
  14058. if (element instanceof JQLite) {
  14059. return element;
  14060. }
  14061. var argIsString;
  14062. if (isString(element)) {
  14063. element = trim(element);
  14064. argIsString = true;
  14065. }
  14066. if (!(this instanceof JQLite)) {
  14067. if (argIsString && element.charAt(0) != '<') {
  14068. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  14069. }
  14070. return new JQLite(element);
  14071. }
  14072. if (argIsString) {
  14073. jqLiteAddNodes(this, jqLiteParseHTML(element));
  14074. } else {
  14075. jqLiteAddNodes(this, element);
  14076. }
  14077. }
  14078. function jqLiteClone(element) {
  14079. return element.cloneNode(true);
  14080. }
  14081. function jqLiteDealoc(element, onlyDescendants) {
  14082. if (!onlyDescendants) jqLiteRemoveData(element);
  14083. if (element.querySelectorAll) {
  14084. var descendants = element.querySelectorAll('*');
  14085. for (var i = 0, l = descendants.length; i < l; i++) {
  14086. jqLiteRemoveData(descendants[i]);
  14087. }
  14088. }
  14089. }
  14090. function jqLiteOff(element, type, fn, unsupported) {
  14091. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  14092. var expandoStore = jqLiteExpandoStore(element);
  14093. var events = expandoStore && expandoStore.events;
  14094. var handle = expandoStore && expandoStore.handle;
  14095. if (!handle) return; //no listeners registered
  14096. if (!type) {
  14097. for (type in events) {
  14098. if (type !== '$destroy') {
  14099. removeEventListenerFn(element, type, handle);
  14100. }
  14101. delete events[type];
  14102. }
  14103. } else {
  14104. var removeHandler = function(type) {
  14105. var listenerFns = events[type];
  14106. if (isDefined(fn)) {
  14107. arrayRemove(listenerFns || [], fn);
  14108. }
  14109. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  14110. removeEventListenerFn(element, type, handle);
  14111. delete events[type];
  14112. }
  14113. };
  14114. forEach(type.split(' '), function(type) {
  14115. removeHandler(type);
  14116. if (MOUSE_EVENT_MAP[type]) {
  14117. removeHandler(MOUSE_EVENT_MAP[type]);
  14118. }
  14119. });
  14120. }
  14121. }
  14122. function jqLiteRemoveData(element, name) {
  14123. var expandoId = element.ng339;
  14124. var expandoStore = expandoId && jqCache[expandoId];
  14125. if (expandoStore) {
  14126. if (name) {
  14127. delete expandoStore.data[name];
  14128. return;
  14129. }
  14130. if (expandoStore.handle) {
  14131. if (expandoStore.events.$destroy) {
  14132. expandoStore.handle({}, '$destroy');
  14133. }
  14134. jqLiteOff(element);
  14135. }
  14136. delete jqCache[expandoId];
  14137. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  14138. }
  14139. }
  14140. function jqLiteExpandoStore(element, createIfNecessary) {
  14141. var expandoId = element.ng339,
  14142. expandoStore = expandoId && jqCache[expandoId];
  14143. if (createIfNecessary && !expandoStore) {
  14144. element.ng339 = expandoId = jqNextId();
  14145. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  14146. }
  14147. return expandoStore;
  14148. }
  14149. function jqLiteData(element, key, value) {
  14150. if (jqLiteAcceptsData(element)) {
  14151. var isSimpleSetter = isDefined(value);
  14152. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  14153. var massGetter = !key;
  14154. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  14155. var data = expandoStore && expandoStore.data;
  14156. if (isSimpleSetter) { // data('key', value)
  14157. data[key] = value;
  14158. } else {
  14159. if (massGetter) { // data()
  14160. return data;
  14161. } else {
  14162. if (isSimpleGetter) { // data('key')
  14163. // don't force creation of expandoStore if it doesn't exist yet
  14164. return data && data[key];
  14165. } else { // mass-setter: data({key1: val1, key2: val2})
  14166. extend(data, key);
  14167. }
  14168. }
  14169. }
  14170. }
  14171. }
  14172. function jqLiteHasClass(element, selector) {
  14173. if (!element.getAttribute) return false;
  14174. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  14175. indexOf(" " + selector + " ") > -1);
  14176. }
  14177. function jqLiteRemoveClass(element, cssClasses) {
  14178. if (cssClasses && element.setAttribute) {
  14179. forEach(cssClasses.split(' '), function(cssClass) {
  14180. element.setAttribute('class', trim(
  14181. (" " + (element.getAttribute('class') || '') + " ")
  14182. .replace(/[\n\t]/g, " ")
  14183. .replace(" " + trim(cssClass) + " ", " "))
  14184. );
  14185. });
  14186. }
  14187. }
  14188. function jqLiteAddClass(element, cssClasses) {
  14189. if (cssClasses && element.setAttribute) {
  14190. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  14191. .replace(/[\n\t]/g, " ");
  14192. forEach(cssClasses.split(' '), function(cssClass) {
  14193. cssClass = trim(cssClass);
  14194. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  14195. existingClasses += cssClass + ' ';
  14196. }
  14197. });
  14198. element.setAttribute('class', trim(existingClasses));
  14199. }
  14200. }
  14201. function jqLiteAddNodes(root, elements) {
  14202. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  14203. if (elements) {
  14204. // if a Node (the most common case)
  14205. if (elements.nodeType) {
  14206. root[root.length++] = elements;
  14207. } else {
  14208. var length = elements.length;
  14209. // if an Array or NodeList and not a Window
  14210. if (typeof length === 'number' && elements.window !== elements) {
  14211. if (length) {
  14212. for (var i = 0; i < length; i++) {
  14213. root[root.length++] = elements[i];
  14214. }
  14215. }
  14216. } else {
  14217. root[root.length++] = elements;
  14218. }
  14219. }
  14220. }
  14221. }
  14222. function jqLiteController(element, name) {
  14223. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  14224. }
  14225. function jqLiteInheritedData(element, name, value) {
  14226. // if element is the document object work with the html element instead
  14227. // this makes $(document).scope() possible
  14228. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  14229. element = element.documentElement;
  14230. }
  14231. var names = isArray(name) ? name : [name];
  14232. while (element) {
  14233. for (var i = 0, ii = names.length; i < ii; i++) {
  14234. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  14235. }
  14236. // If dealing with a document fragment node with a host element, and no parent, use the host
  14237. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  14238. // to lookup parent controllers.
  14239. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  14240. }
  14241. }
  14242. function jqLiteEmpty(element) {
  14243. jqLiteDealoc(element, true);
  14244. while (element.firstChild) {
  14245. element.removeChild(element.firstChild);
  14246. }
  14247. }
  14248. function jqLiteRemove(element, keepData) {
  14249. if (!keepData) jqLiteDealoc(element);
  14250. var parent = element.parentNode;
  14251. if (parent) parent.removeChild(element);
  14252. }
  14253. function jqLiteDocumentLoaded(action, win) {
  14254. win = win || window;
  14255. if (win.document.readyState === 'complete') {
  14256. // Force the action to be run async for consistent behavior
  14257. // from the action's point of view
  14258. // i.e. it will definitely not be in a $apply
  14259. win.setTimeout(action);
  14260. } else {
  14261. // No need to unbind this handler as load is only ever called once
  14262. jqLite(win).on('load', action);
  14263. }
  14264. }
  14265. //////////////////////////////////////////
  14266. // Functions which are declared directly.
  14267. //////////////////////////////////////////
  14268. var JQLitePrototype = JQLite.prototype = {
  14269. ready: function(fn) {
  14270. var fired = false;
  14271. function trigger() {
  14272. if (fired) return;
  14273. fired = true;
  14274. fn();
  14275. }
  14276. // check if document is already loaded
  14277. if (document.readyState === 'complete') {
  14278. setTimeout(trigger);
  14279. } else {
  14280. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  14281. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  14282. // jshint -W064
  14283. JQLite(window).on('load', trigger); // fallback to window.onload for others
  14284. // jshint +W064
  14285. }
  14286. },
  14287. toString: function() {
  14288. var value = [];
  14289. forEach(this, function(e) { value.push('' + e);});
  14290. return '[' + value.join(', ') + ']';
  14291. },
  14292. eq: function(index) {
  14293. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  14294. },
  14295. length: 0,
  14296. push: push,
  14297. sort: [].sort,
  14298. splice: [].splice
  14299. };
  14300. //////////////////////////////////////////
  14301. // Functions iterating getter/setters.
  14302. // these functions return self on setter and
  14303. // value on get.
  14304. //////////////////////////////////////////
  14305. var BOOLEAN_ATTR = {};
  14306. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  14307. BOOLEAN_ATTR[lowercase(value)] = value;
  14308. });
  14309. var BOOLEAN_ELEMENTS = {};
  14310. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  14311. BOOLEAN_ELEMENTS[value] = true;
  14312. });
  14313. var ALIASED_ATTR = {
  14314. 'ngMinlength': 'minlength',
  14315. 'ngMaxlength': 'maxlength',
  14316. 'ngMin': 'min',
  14317. 'ngMax': 'max',
  14318. 'ngPattern': 'pattern'
  14319. };
  14320. function getBooleanAttrName(element, name) {
  14321. // check dom last since we will most likely fail on name
  14322. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  14323. // booleanAttr is here twice to minimize DOM access
  14324. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  14325. }
  14326. function getAliasedAttrName(name) {
  14327. return ALIASED_ATTR[name];
  14328. }
  14329. forEach({
  14330. data: jqLiteData,
  14331. removeData: jqLiteRemoveData,
  14332. hasData: jqLiteHasData,
  14333. cleanData: jqLiteCleanData
  14334. }, function(fn, name) {
  14335. JQLite[name] = fn;
  14336. });
  14337. forEach({
  14338. data: jqLiteData,
  14339. inheritedData: jqLiteInheritedData,
  14340. scope: function(element) {
  14341. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  14342. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  14343. },
  14344. isolateScope: function(element) {
  14345. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  14346. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  14347. },
  14348. controller: jqLiteController,
  14349. injector: function(element) {
  14350. return jqLiteInheritedData(element, '$injector');
  14351. },
  14352. removeAttr: function(element, name) {
  14353. element.removeAttribute(name);
  14354. },
  14355. hasClass: jqLiteHasClass,
  14356. css: function(element, name, value) {
  14357. name = camelCase(name);
  14358. if (isDefined(value)) {
  14359. element.style[name] = value;
  14360. } else {
  14361. return element.style[name];
  14362. }
  14363. },
  14364. attr: function(element, name, value) {
  14365. var nodeType = element.nodeType;
  14366. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  14367. return;
  14368. }
  14369. var lowercasedName = lowercase(name);
  14370. if (BOOLEAN_ATTR[lowercasedName]) {
  14371. if (isDefined(value)) {
  14372. if (!!value) {
  14373. element[name] = true;
  14374. element.setAttribute(name, lowercasedName);
  14375. } else {
  14376. element[name] = false;
  14377. element.removeAttribute(lowercasedName);
  14378. }
  14379. } else {
  14380. return (element[name] ||
  14381. (element.attributes.getNamedItem(name) || noop).specified)
  14382. ? lowercasedName
  14383. : undefined;
  14384. }
  14385. } else if (isDefined(value)) {
  14386. element.setAttribute(name, value);
  14387. } else if (element.getAttribute) {
  14388. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  14389. // some elements (e.g. Document) don't have get attribute, so return undefined
  14390. var ret = element.getAttribute(name, 2);
  14391. // normalize non-existing attributes to undefined (as jQuery)
  14392. return ret === null ? undefined : ret;
  14393. }
  14394. },
  14395. prop: function(element, name, value) {
  14396. if (isDefined(value)) {
  14397. element[name] = value;
  14398. } else {
  14399. return element[name];
  14400. }
  14401. },
  14402. text: (function() {
  14403. getText.$dv = '';
  14404. return getText;
  14405. function getText(element, value) {
  14406. if (isUndefined(value)) {
  14407. var nodeType = element.nodeType;
  14408. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  14409. }
  14410. element.textContent = value;
  14411. }
  14412. })(),
  14413. val: function(element, value) {
  14414. if (isUndefined(value)) {
  14415. if (element.multiple && nodeName_(element) === 'select') {
  14416. var result = [];
  14417. forEach(element.options, function(option) {
  14418. if (option.selected) {
  14419. result.push(option.value || option.text);
  14420. }
  14421. });
  14422. return result.length === 0 ? null : result;
  14423. }
  14424. return element.value;
  14425. }
  14426. element.value = value;
  14427. },
  14428. html: function(element, value) {
  14429. if (isUndefined(value)) {
  14430. return element.innerHTML;
  14431. }
  14432. jqLiteDealoc(element, true);
  14433. element.innerHTML = value;
  14434. },
  14435. empty: jqLiteEmpty
  14436. }, function(fn, name) {
  14437. /**
  14438. * Properties: writes return selection, reads return first value
  14439. */
  14440. JQLite.prototype[name] = function(arg1, arg2) {
  14441. var i, key;
  14442. var nodeCount = this.length;
  14443. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  14444. // in a way that survives minification.
  14445. // jqLiteEmpty takes no arguments but is a setter.
  14446. if (fn !== jqLiteEmpty &&
  14447. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  14448. if (isObject(arg1)) {
  14449. // we are a write, but the object properties are the key/values
  14450. for (i = 0; i < nodeCount; i++) {
  14451. if (fn === jqLiteData) {
  14452. // data() takes the whole object in jQuery
  14453. fn(this[i], arg1);
  14454. } else {
  14455. for (key in arg1) {
  14456. fn(this[i], key, arg1[key]);
  14457. }
  14458. }
  14459. }
  14460. // return self for chaining
  14461. return this;
  14462. } else {
  14463. // we are a read, so read the first child.
  14464. // TODO: do we still need this?
  14465. var value = fn.$dv;
  14466. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  14467. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  14468. for (var j = 0; j < jj; j++) {
  14469. var nodeValue = fn(this[j], arg1, arg2);
  14470. value = value ? value + nodeValue : nodeValue;
  14471. }
  14472. return value;
  14473. }
  14474. } else {
  14475. // we are a write, so apply to all children
  14476. for (i = 0; i < nodeCount; i++) {
  14477. fn(this[i], arg1, arg2);
  14478. }
  14479. // return self for chaining
  14480. return this;
  14481. }
  14482. };
  14483. });
  14484. function createEventHandler(element, events) {
  14485. var eventHandler = function(event, type) {
  14486. // jQuery specific api
  14487. event.isDefaultPrevented = function() {
  14488. return event.defaultPrevented;
  14489. };
  14490. var eventFns = events[type || event.type];
  14491. var eventFnsLength = eventFns ? eventFns.length : 0;
  14492. if (!eventFnsLength) return;
  14493. if (isUndefined(event.immediatePropagationStopped)) {
  14494. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  14495. event.stopImmediatePropagation = function() {
  14496. event.immediatePropagationStopped = true;
  14497. if (event.stopPropagation) {
  14498. event.stopPropagation();
  14499. }
  14500. if (originalStopImmediatePropagation) {
  14501. originalStopImmediatePropagation.call(event);
  14502. }
  14503. };
  14504. }
  14505. event.isImmediatePropagationStopped = function() {
  14506. return event.immediatePropagationStopped === true;
  14507. };
  14508. // Some events have special handlers that wrap the real handler
  14509. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  14510. // Copy event handlers in case event handlers array is modified during execution.
  14511. if ((eventFnsLength > 1)) {
  14512. eventFns = shallowCopy(eventFns);
  14513. }
  14514. for (var i = 0; i < eventFnsLength; i++) {
  14515. if (!event.isImmediatePropagationStopped()) {
  14516. handlerWrapper(element, event, eventFns[i]);
  14517. }
  14518. }
  14519. };
  14520. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  14521. // events on `element`
  14522. eventHandler.elem = element;
  14523. return eventHandler;
  14524. }
  14525. function defaultHandlerWrapper(element, event, handler) {
  14526. handler.call(element, event);
  14527. }
  14528. function specialMouseHandlerWrapper(target, event, handler) {
  14529. // Refer to jQuery's implementation of mouseenter & mouseleave
  14530. // Read about mouseenter and mouseleave:
  14531. // http://www.quirksmode.org/js/events_mouse.html#link8
  14532. var related = event.relatedTarget;
  14533. // For mousenter/leave call the handler if related is outside the target.
  14534. // NB: No relatedTarget if the mouse left/entered the browser window
  14535. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  14536. handler.call(target, event);
  14537. }
  14538. }
  14539. //////////////////////////////////////////
  14540. // Functions iterating traversal.
  14541. // These functions chain results into a single
  14542. // selector.
  14543. //////////////////////////////////////////
  14544. forEach({
  14545. removeData: jqLiteRemoveData,
  14546. on: function jqLiteOn(element, type, fn, unsupported) {
  14547. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  14548. // Do not add event handlers to non-elements because they will not be cleaned up.
  14549. if (!jqLiteAcceptsData(element)) {
  14550. return;
  14551. }
  14552. var expandoStore = jqLiteExpandoStore(element, true);
  14553. var events = expandoStore.events;
  14554. var handle = expandoStore.handle;
  14555. if (!handle) {
  14556. handle = expandoStore.handle = createEventHandler(element, events);
  14557. }
  14558. // http://jsperf.com/string-indexof-vs-split
  14559. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  14560. var i = types.length;
  14561. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  14562. var eventFns = events[type];
  14563. if (!eventFns) {
  14564. eventFns = events[type] = [];
  14565. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  14566. if (type !== '$destroy' && !noEventListener) {
  14567. addEventListenerFn(element, type, handle);
  14568. }
  14569. }
  14570. eventFns.push(fn);
  14571. };
  14572. while (i--) {
  14573. type = types[i];
  14574. if (MOUSE_EVENT_MAP[type]) {
  14575. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  14576. addHandler(type, undefined, true);
  14577. } else {
  14578. addHandler(type);
  14579. }
  14580. }
  14581. },
  14582. off: jqLiteOff,
  14583. one: function(element, type, fn) {
  14584. element = jqLite(element);
  14585. //add the listener twice so that when it is called
  14586. //you can remove the original function and still be
  14587. //able to call element.off(ev, fn) normally
  14588. element.on(type, function onFn() {
  14589. element.off(type, fn);
  14590. element.off(type, onFn);
  14591. });
  14592. element.on(type, fn);
  14593. },
  14594. replaceWith: function(element, replaceNode) {
  14595. var index, parent = element.parentNode;
  14596. jqLiteDealoc(element);
  14597. forEach(new JQLite(replaceNode), function(node) {
  14598. if (index) {
  14599. parent.insertBefore(node, index.nextSibling);
  14600. } else {
  14601. parent.replaceChild(node, element);
  14602. }
  14603. index = node;
  14604. });
  14605. },
  14606. children: function(element) {
  14607. var children = [];
  14608. forEach(element.childNodes, function(element) {
  14609. if (element.nodeType === NODE_TYPE_ELEMENT) {
  14610. children.push(element);
  14611. }
  14612. });
  14613. return children;
  14614. },
  14615. contents: function(element) {
  14616. return element.contentDocument || element.childNodes || [];
  14617. },
  14618. append: function(element, node) {
  14619. var nodeType = element.nodeType;
  14620. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  14621. node = new JQLite(node);
  14622. for (var i = 0, ii = node.length; i < ii; i++) {
  14623. var child = node[i];
  14624. element.appendChild(child);
  14625. }
  14626. },
  14627. prepend: function(element, node) {
  14628. if (element.nodeType === NODE_TYPE_ELEMENT) {
  14629. var index = element.firstChild;
  14630. forEach(new JQLite(node), function(child) {
  14631. element.insertBefore(child, index);
  14632. });
  14633. }
  14634. },
  14635. wrap: function(element, wrapNode) {
  14636. jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]);
  14637. },
  14638. remove: jqLiteRemove,
  14639. detach: function(element) {
  14640. jqLiteRemove(element, true);
  14641. },
  14642. after: function(element, newElement) {
  14643. var index = element, parent = element.parentNode;
  14644. newElement = new JQLite(newElement);
  14645. for (var i = 0, ii = newElement.length; i < ii; i++) {
  14646. var node = newElement[i];
  14647. parent.insertBefore(node, index.nextSibling);
  14648. index = node;
  14649. }
  14650. },
  14651. addClass: jqLiteAddClass,
  14652. removeClass: jqLiteRemoveClass,
  14653. toggleClass: function(element, selector, condition) {
  14654. if (selector) {
  14655. forEach(selector.split(' '), function(className) {
  14656. var classCondition = condition;
  14657. if (isUndefined(classCondition)) {
  14658. classCondition = !jqLiteHasClass(element, className);
  14659. }
  14660. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  14661. });
  14662. }
  14663. },
  14664. parent: function(element) {
  14665. var parent = element.parentNode;
  14666. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  14667. },
  14668. next: function(element) {
  14669. return element.nextElementSibling;
  14670. },
  14671. find: function(element, selector) {
  14672. if (element.getElementsByTagName) {
  14673. return element.getElementsByTagName(selector);
  14674. } else {
  14675. return [];
  14676. }
  14677. },
  14678. clone: jqLiteClone,
  14679. triggerHandler: function(element, event, extraParameters) {
  14680. var dummyEvent, eventFnsCopy, handlerArgs;
  14681. var eventName = event.type || event;
  14682. var expandoStore = jqLiteExpandoStore(element);
  14683. var events = expandoStore && expandoStore.events;
  14684. var eventFns = events && events[eventName];
  14685. if (eventFns) {
  14686. // Create a dummy event to pass to the handlers
  14687. dummyEvent = {
  14688. preventDefault: function() { this.defaultPrevented = true; },
  14689. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  14690. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  14691. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  14692. stopPropagation: noop,
  14693. type: eventName,
  14694. target: element
  14695. };
  14696. // If a custom event was provided then extend our dummy event with it
  14697. if (event.type) {
  14698. dummyEvent = extend(dummyEvent, event);
  14699. }
  14700. // Copy event handlers in case event handlers array is modified during execution.
  14701. eventFnsCopy = shallowCopy(eventFns);
  14702. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  14703. forEach(eventFnsCopy, function(fn) {
  14704. if (!dummyEvent.isImmediatePropagationStopped()) {
  14705. fn.apply(element, handlerArgs);
  14706. }
  14707. });
  14708. }
  14709. }
  14710. }, function(fn, name) {
  14711. /**
  14712. * chaining functions
  14713. */
  14714. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  14715. var value;
  14716. for (var i = 0, ii = this.length; i < ii; i++) {
  14717. if (isUndefined(value)) {
  14718. value = fn(this[i], arg1, arg2, arg3);
  14719. if (isDefined(value)) {
  14720. // any function which returns a value needs to be wrapped
  14721. value = jqLite(value);
  14722. }
  14723. } else {
  14724. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  14725. }
  14726. }
  14727. return isDefined(value) ? value : this;
  14728. };
  14729. // bind legacy bind/unbind to on/off
  14730. JQLite.prototype.bind = JQLite.prototype.on;
  14731. JQLite.prototype.unbind = JQLite.prototype.off;
  14732. });
  14733. // Provider for private $$jqLite service
  14734. function $$jqLiteProvider() {
  14735. this.$get = function $$jqLite() {
  14736. return extend(JQLite, {
  14737. hasClass: function(node, classes) {
  14738. if (node.attr) node = node[0];
  14739. return jqLiteHasClass(node, classes);
  14740. },
  14741. addClass: function(node, classes) {
  14742. if (node.attr) node = node[0];
  14743. return jqLiteAddClass(node, classes);
  14744. },
  14745. removeClass: function(node, classes) {
  14746. if (node.attr) node = node[0];
  14747. return jqLiteRemoveClass(node, classes);
  14748. }
  14749. });
  14750. };
  14751. }
  14752. /**
  14753. * Computes a hash of an 'obj'.
  14754. * Hash of a:
  14755. * string is string
  14756. * number is number as string
  14757. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  14758. * that is also assigned to the $$hashKey property of the object.
  14759. *
  14760. * @param obj
  14761. * @returns {string} hash string such that the same input will have the same hash string.
  14762. * The resulting string key is in 'type:hashKey' format.
  14763. */
  14764. function hashKey(obj, nextUidFn) {
  14765. var key = obj && obj.$$hashKey;
  14766. if (key) {
  14767. if (typeof key === 'function') {
  14768. key = obj.$$hashKey();
  14769. }
  14770. return key;
  14771. }
  14772. var objType = typeof obj;
  14773. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  14774. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  14775. } else {
  14776. key = objType + ':' + obj;
  14777. }
  14778. return key;
  14779. }
  14780. /**
  14781. * HashMap which can use objects as keys
  14782. */
  14783. function HashMap(array, isolatedUid) {
  14784. if (isolatedUid) {
  14785. var uid = 0;
  14786. this.nextUid = function() {
  14787. return ++uid;
  14788. };
  14789. }
  14790. forEach(array, this.put, this);
  14791. }
  14792. HashMap.prototype = {
  14793. /**
  14794. * Store key value pair
  14795. * @param key key to store can be any type
  14796. * @param value value to store can be any type
  14797. */
  14798. put: function(key, value) {
  14799. this[hashKey(key, this.nextUid)] = value;
  14800. },
  14801. /**
  14802. * @param key
  14803. * @returns {Object} the value for the key
  14804. */
  14805. get: function(key) {
  14806. return this[hashKey(key, this.nextUid)];
  14807. },
  14808. /**
  14809. * Remove the key/value pair
  14810. * @param key
  14811. */
  14812. remove: function(key) {
  14813. var value = this[key = hashKey(key, this.nextUid)];
  14814. delete this[key];
  14815. return value;
  14816. }
  14817. };
  14818. var $$HashMapProvider = [function() {
  14819. this.$get = [function() {
  14820. return HashMap;
  14821. }];
  14822. }];
  14823. /**
  14824. * @ngdoc function
  14825. * @module ng
  14826. * @name angular.injector
  14827. * @kind function
  14828. *
  14829. * @description
  14830. * Creates an injector object that can be used for retrieving services as well as for
  14831. * dependency injection (see {@link guide/di dependency injection}).
  14832. *
  14833. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  14834. * {@link angular.module}. The `ng` module must be explicitly added.
  14835. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  14836. * disallows argument name annotation inference.
  14837. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  14838. *
  14839. * @example
  14840. * Typical usage
  14841. * ```js
  14842. * // create an injector
  14843. * var $injector = angular.injector(['ng']);
  14844. *
  14845. * // use the injector to kick off your application
  14846. * // use the type inference to auto inject arguments, or use implicit injection
  14847. * $injector.invoke(function($rootScope, $compile, $document) {
  14848. * $compile($document)($rootScope);
  14849. * $rootScope.$digest();
  14850. * });
  14851. * ```
  14852. *
  14853. * Sometimes you want to get access to the injector of a currently running Angular app
  14854. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  14855. * application has been bootstrapped. You can do this using the extra `injector()` added
  14856. * to JQuery/jqLite elements. See {@link angular.element}.
  14857. *
  14858. * *This is fairly rare but could be the case if a third party library is injecting the
  14859. * markup.*
  14860. *
  14861. * In the following example a new block of HTML containing a `ng-controller`
  14862. * directive is added to the end of the document body by JQuery. We then compile and link
  14863. * it into the current AngularJS scope.
  14864. *
  14865. * ```js
  14866. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  14867. * $(document.body).append($div);
  14868. *
  14869. * angular.element(document).injector().invoke(function($compile) {
  14870. * var scope = angular.element($div).scope();
  14871. * $compile($div)(scope);
  14872. * });
  14873. * ```
  14874. */
  14875. /**
  14876. * @ngdoc module
  14877. * @name auto
  14878. * @description
  14879. *
  14880. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  14881. */
  14882. var ARROW_ARG = /^([^\(]+?)=>/;
  14883. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  14884. var FN_ARG_SPLIT = /,/;
  14885. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  14886. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  14887. var $injectorMinErr = minErr('$injector');
  14888. function extractArgs(fn) {
  14889. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  14890. args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS);
  14891. return args;
  14892. }
  14893. function anonFn(fn) {
  14894. // For anonymous functions, showing at the very least the function signature can help in
  14895. // debugging.
  14896. var args = extractArgs(fn);
  14897. if (args) {
  14898. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  14899. }
  14900. return 'fn';
  14901. }
  14902. function annotate(fn, strictDi, name) {
  14903. var $inject,
  14904. argDecl,
  14905. last;
  14906. if (typeof fn === 'function') {
  14907. if (!($inject = fn.$inject)) {
  14908. $inject = [];
  14909. if (fn.length) {
  14910. if (strictDi) {
  14911. if (!isString(name) || !name) {
  14912. name = fn.name || anonFn(fn);
  14913. }
  14914. throw $injectorMinErr('strictdi',
  14915. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  14916. }
  14917. argDecl = extractArgs(fn);
  14918. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  14919. arg.replace(FN_ARG, function(all, underscore, name) {
  14920. $inject.push(name);
  14921. });
  14922. });
  14923. }
  14924. fn.$inject = $inject;
  14925. }
  14926. } else if (isArray(fn)) {
  14927. last = fn.length - 1;
  14928. assertArgFn(fn[last], 'fn');
  14929. $inject = fn.slice(0, last);
  14930. } else {
  14931. assertArgFn(fn, 'fn', true);
  14932. }
  14933. return $inject;
  14934. }
  14935. ///////////////////////////////////////
  14936. /**
  14937. * @ngdoc service
  14938. * @name $injector
  14939. *
  14940. * @description
  14941. *
  14942. * `$injector` is used to retrieve object instances as defined by
  14943. * {@link auto.$provide provider}, instantiate types, invoke methods,
  14944. * and load modules.
  14945. *
  14946. * The following always holds true:
  14947. *
  14948. * ```js
  14949. * var $injector = angular.injector();
  14950. * expect($injector.get('$injector')).toBe($injector);
  14951. * expect($injector.invoke(function($injector) {
  14952. * return $injector;
  14953. * })).toBe($injector);
  14954. * ```
  14955. *
  14956. * # Injection Function Annotation
  14957. *
  14958. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  14959. * following are all valid ways of annotating function with injection arguments and are equivalent.
  14960. *
  14961. * ```js
  14962. * // inferred (only works if code not minified/obfuscated)
  14963. * $injector.invoke(function(serviceA){});
  14964. *
  14965. * // annotated
  14966. * function explicit(serviceA) {};
  14967. * explicit.$inject = ['serviceA'];
  14968. * $injector.invoke(explicit);
  14969. *
  14970. * // inline
  14971. * $injector.invoke(['serviceA', function(serviceA){}]);
  14972. * ```
  14973. *
  14974. * ## Inference
  14975. *
  14976. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  14977. * can then be parsed and the function arguments can be extracted. This method of discovering
  14978. * annotations is disallowed when the injector is in strict mode.
  14979. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  14980. * argument names.
  14981. *
  14982. * ## `$inject` Annotation
  14983. * By adding an `$inject` property onto a function the injection parameters can be specified.
  14984. *
  14985. * ## Inline
  14986. * As an array of injection names, where the last item in the array is the function to call.
  14987. */
  14988. /**
  14989. * @ngdoc method
  14990. * @name $injector#get
  14991. *
  14992. * @description
  14993. * Return an instance of the service.
  14994. *
  14995. * @param {string} name The name of the instance to retrieve.
  14996. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  14997. * @return {*} The instance.
  14998. */
  14999. /**
  15000. * @ngdoc method
  15001. * @name $injector#invoke
  15002. *
  15003. * @description
  15004. * Invoke the method and supply the method arguments from the `$injector`.
  15005. *
  15006. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  15007. * injected according to the {@link guide/di $inject Annotation} rules.
  15008. * @param {Object=} self The `this` for the invoked method.
  15009. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  15010. * object first, before the `$injector` is consulted.
  15011. * @returns {*} the value returned by the invoked `fn` function.
  15012. */
  15013. /**
  15014. * @ngdoc method
  15015. * @name $injector#has
  15016. *
  15017. * @description
  15018. * Allows the user to query if the particular service exists.
  15019. *
  15020. * @param {string} name Name of the service to query.
  15021. * @returns {boolean} `true` if injector has given service.
  15022. */
  15023. /**
  15024. * @ngdoc method
  15025. * @name $injector#instantiate
  15026. * @description
  15027. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  15028. * operator, and supplies all of the arguments to the constructor function as specified by the
  15029. * constructor annotation.
  15030. *
  15031. * @param {Function} Type Annotated constructor function.
  15032. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  15033. * object first, before the `$injector` is consulted.
  15034. * @returns {Object} new instance of `Type`.
  15035. */
  15036. /**
  15037. * @ngdoc method
  15038. * @name $injector#annotate
  15039. *
  15040. * @description
  15041. * Returns an array of service names which the function is requesting for injection. This API is
  15042. * used by the injector to determine which services need to be injected into the function when the
  15043. * function is invoked. There are three ways in which the function can be annotated with the needed
  15044. * dependencies.
  15045. *
  15046. * # Argument names
  15047. *
  15048. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  15049. * by converting the function into a string using `toString()` method and extracting the argument
  15050. * names.
  15051. * ```js
  15052. * // Given
  15053. * function MyController($scope, $route) {
  15054. * // ...
  15055. * }
  15056. *
  15057. * // Then
  15058. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  15059. * ```
  15060. *
  15061. * You can disallow this method by using strict injection mode.
  15062. *
  15063. * This method does not work with code minification / obfuscation. For this reason the following
  15064. * annotation strategies are supported.
  15065. *
  15066. * # The `$inject` property
  15067. *
  15068. * If a function has an `$inject` property and its value is an array of strings, then the strings
  15069. * represent names of services to be injected into the function.
  15070. * ```js
  15071. * // Given
  15072. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  15073. * // ...
  15074. * }
  15075. * // Define function dependencies
  15076. * MyController['$inject'] = ['$scope', '$route'];
  15077. *
  15078. * // Then
  15079. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  15080. * ```
  15081. *
  15082. * # The array notation
  15083. *
  15084. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  15085. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  15086. * a way that survives minification is a better choice:
  15087. *
  15088. * ```js
  15089. * // We wish to write this (not minification / obfuscation safe)
  15090. * injector.invoke(function($compile, $rootScope) {
  15091. * // ...
  15092. * });
  15093. *
  15094. * // We are forced to write break inlining
  15095. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  15096. * // ...
  15097. * };
  15098. * tmpFn.$inject = ['$compile', '$rootScope'];
  15099. * injector.invoke(tmpFn);
  15100. *
  15101. * // To better support inline function the inline annotation is supported
  15102. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  15103. * // ...
  15104. * }]);
  15105. *
  15106. * // Therefore
  15107. * expect(injector.annotate(
  15108. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  15109. * ).toEqual(['$compile', '$rootScope']);
  15110. * ```
  15111. *
  15112. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  15113. * be retrieved as described above.
  15114. *
  15115. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  15116. *
  15117. * @returns {Array.<string>} The names of the services which the function requires.
  15118. */
  15119. /**
  15120. * @ngdoc service
  15121. * @name $provide
  15122. *
  15123. * @description
  15124. *
  15125. * The {@link auto.$provide $provide} service has a number of methods for registering components
  15126. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  15127. * {@link angular.Module}.
  15128. *
  15129. * An Angular **service** is a singleton object created by a **service factory**. These **service
  15130. * factories** are functions which, in turn, are created by a **service provider**.
  15131. * The **service providers** are constructor functions. When instantiated they must contain a
  15132. * property called `$get`, which holds the **service factory** function.
  15133. *
  15134. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  15135. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  15136. * function to get the instance of the **service**.
  15137. *
  15138. * Often services have no configuration options and there is no need to add methods to the service
  15139. * provider. The provider will be no more than a constructor function with a `$get` property. For
  15140. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  15141. * services without specifying a provider.
  15142. *
  15143. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  15144. * {@link auto.$injector $injector}
  15145. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  15146. * providers and services.
  15147. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  15148. * services, not providers.
  15149. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  15150. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  15151. * given factory function.
  15152. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  15153. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  15154. * a new object using the given constructor function.
  15155. *
  15156. * See the individual methods for more information and examples.
  15157. */
  15158. /**
  15159. * @ngdoc method
  15160. * @name $provide#provider
  15161. * @description
  15162. *
  15163. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  15164. * are constructor functions, whose instances are responsible for "providing" a factory for a
  15165. * service.
  15166. *
  15167. * Service provider names start with the name of the service they provide followed by `Provider`.
  15168. * For example, the {@link ng.$log $log} service has a provider called
  15169. * {@link ng.$logProvider $logProvider}.
  15170. *
  15171. * Service provider objects can have additional methods which allow configuration of the provider
  15172. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  15173. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  15174. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  15175. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  15176. * console or not.
  15177. *
  15178. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  15179. 'Provider'` key.
  15180. * @param {(Object|function())} provider If the provider is:
  15181. *
  15182. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  15183. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  15184. * - `Constructor`: a new instance of the provider will be created using
  15185. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  15186. *
  15187. * @returns {Object} registered provider instance
  15188. * @example
  15189. *
  15190. * The following example shows how to create a simple event tracking service and register it using
  15191. * {@link auto.$provide#provider $provide.provider()}.
  15192. *
  15193. * ```js
  15194. * // Define the eventTracker provider
  15195. * function EventTrackerProvider() {
  15196. * var trackingUrl = '/track';
  15197. *
  15198. * // A provider method for configuring where the tracked events should been saved
  15199. * this.setTrackingUrl = function(url) {
  15200. * trackingUrl = url;
  15201. * };
  15202. *
  15203. * // The service factory function
  15204. * this.$get = ['$http', function($http) {
  15205. * var trackedEvents = {};
  15206. * return {
  15207. * // Call this to track an event
  15208. * event: function(event) {
  15209. * var count = trackedEvents[event] || 0;
  15210. * count += 1;
  15211. * trackedEvents[event] = count;
  15212. * return count;
  15213. * },
  15214. * // Call this to save the tracked events to the trackingUrl
  15215. * save: function() {
  15216. * $http.post(trackingUrl, trackedEvents);
  15217. * }
  15218. * };
  15219. * }];
  15220. * }
  15221. *
  15222. * describe('eventTracker', function() {
  15223. * var postSpy;
  15224. *
  15225. * beforeEach(module(function($provide) {
  15226. * // Register the eventTracker provider
  15227. * $provide.provider('eventTracker', EventTrackerProvider);
  15228. * }));
  15229. *
  15230. * beforeEach(module(function(eventTrackerProvider) {
  15231. * // Configure eventTracker provider
  15232. * eventTrackerProvider.setTrackingUrl('/custom-track');
  15233. * }));
  15234. *
  15235. * it('tracks events', inject(function(eventTracker) {
  15236. * expect(eventTracker.event('login')).toEqual(1);
  15237. * expect(eventTracker.event('login')).toEqual(2);
  15238. * }));
  15239. *
  15240. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  15241. * postSpy = spyOn($http, 'post');
  15242. * eventTracker.event('login');
  15243. * eventTracker.save();
  15244. * expect(postSpy).toHaveBeenCalled();
  15245. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  15246. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  15247. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  15248. * }));
  15249. * });
  15250. * ```
  15251. */
  15252. /**
  15253. * @ngdoc method
  15254. * @name $provide#factory
  15255. * @description
  15256. *
  15257. * Register a **service factory**, which will be called to return the service instance.
  15258. * This is short for registering a service where its provider consists of only a `$get` property,
  15259. * which is the given service factory function.
  15260. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  15261. * configure your service in a provider.
  15262. *
  15263. * @param {string} name The name of the instance.
  15264. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  15265. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  15266. * @returns {Object} registered provider instance
  15267. *
  15268. * @example
  15269. * Here is an example of registering a service
  15270. * ```js
  15271. * $provide.factory('ping', ['$http', function($http) {
  15272. * return function ping() {
  15273. * return $http.send('/ping');
  15274. * };
  15275. * }]);
  15276. * ```
  15277. * You would then inject and use this service like this:
  15278. * ```js
  15279. * someModule.controller('Ctrl', ['ping', function(ping) {
  15280. * ping();
  15281. * }]);
  15282. * ```
  15283. */
  15284. /**
  15285. * @ngdoc method
  15286. * @name $provide#service
  15287. * @description
  15288. *
  15289. * Register a **service constructor**, which will be invoked with `new` to create the service
  15290. * instance.
  15291. * This is short for registering a service where its provider's `$get` property is a factory
  15292. * function that returns an instance instantiated by the injector from the service constructor
  15293. * function.
  15294. *
  15295. * Internally it looks a bit like this:
  15296. *
  15297. * ```
  15298. * {
  15299. * $get: function() {
  15300. * return $injector.instantiate(constructor);
  15301. * }
  15302. * }
  15303. * ```
  15304. *
  15305. *
  15306. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  15307. * as a type/class.
  15308. *
  15309. * @param {string} name The name of the instance.
  15310. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  15311. * that will be instantiated.
  15312. * @returns {Object} registered provider instance
  15313. *
  15314. * @example
  15315. * Here is an example of registering a service using
  15316. * {@link auto.$provide#service $provide.service(class)}.
  15317. * ```js
  15318. * var Ping = function($http) {
  15319. * this.$http = $http;
  15320. * };
  15321. *
  15322. * Ping.$inject = ['$http'];
  15323. *
  15324. * Ping.prototype.send = function() {
  15325. * return this.$http.get('/ping');
  15326. * };
  15327. * $provide.service('ping', Ping);
  15328. * ```
  15329. * You would then inject and use this service like this:
  15330. * ```js
  15331. * someModule.controller('Ctrl', ['ping', function(ping) {
  15332. * ping.send();
  15333. * }]);
  15334. * ```
  15335. */
  15336. /**
  15337. * @ngdoc method
  15338. * @name $provide#value
  15339. * @description
  15340. *
  15341. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  15342. * number, an array, an object or a function. This is short for registering a service where its
  15343. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  15344. * service**. That also means it is not possible to inject other services into a value service.
  15345. *
  15346. * Value services are similar to constant services, except that they cannot be injected into a
  15347. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  15348. * an Angular {@link auto.$provide#decorator decorator}.
  15349. *
  15350. * @param {string} name The name of the instance.
  15351. * @param {*} value The value.
  15352. * @returns {Object} registered provider instance
  15353. *
  15354. * @example
  15355. * Here are some examples of creating value services.
  15356. * ```js
  15357. * $provide.value('ADMIN_USER', 'admin');
  15358. *
  15359. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  15360. *
  15361. * $provide.value('halfOf', function(value) {
  15362. * return value / 2;
  15363. * });
  15364. * ```
  15365. */
  15366. /**
  15367. * @ngdoc method
  15368. * @name $provide#constant
  15369. * @description
  15370. *
  15371. * Register a **constant service** with the {@link auto.$injector $injector}, such as a string,
  15372. * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not
  15373. * possible to inject other services into a constant.
  15374. *
  15375. * But unlike {@link auto.$provide#value value}, a constant can be
  15376. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  15377. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  15378. *
  15379. * @param {string} name The name of the constant.
  15380. * @param {*} value The constant value.
  15381. * @returns {Object} registered instance
  15382. *
  15383. * @example
  15384. * Here a some examples of creating constants:
  15385. * ```js
  15386. * $provide.constant('SHARD_HEIGHT', 306);
  15387. *
  15388. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  15389. *
  15390. * $provide.constant('double', function(value) {
  15391. * return value * 2;
  15392. * });
  15393. * ```
  15394. */
  15395. /**
  15396. * @ngdoc method
  15397. * @name $provide#decorator
  15398. * @description
  15399. *
  15400. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  15401. * intercepts the creation of a service, allowing it to override or modify the behavior of the
  15402. * service. The object returned by the decorator may be the original service, or a new service
  15403. * object which replaces or wraps and delegates to the original service.
  15404. *
  15405. * @param {string} name The name of the service to decorate.
  15406. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  15407. * instantiated and should return the decorated service instance. The function is called using
  15408. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  15409. * Local injection arguments:
  15410. *
  15411. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  15412. * decorated or delegated to.
  15413. *
  15414. * @example
  15415. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  15416. * calls to {@link ng.$log#error $log.warn()}.
  15417. * ```js
  15418. * $provide.decorator('$log', ['$delegate', function($delegate) {
  15419. * $delegate.warn = $delegate.error;
  15420. * return $delegate;
  15421. * }]);
  15422. * ```
  15423. */
  15424. function createInjector(modulesToLoad, strictDi) {
  15425. strictDi = (strictDi === true);
  15426. var INSTANTIATING = {},
  15427. providerSuffix = 'Provider',
  15428. path = [],
  15429. loadedModules = new HashMap([], true),
  15430. providerCache = {
  15431. $provide: {
  15432. provider: supportObject(provider),
  15433. factory: supportObject(factory),
  15434. service: supportObject(service),
  15435. value: supportObject(value),
  15436. constant: supportObject(constant),
  15437. decorator: decorator
  15438. }
  15439. },
  15440. providerInjector = (providerCache.$injector =
  15441. createInternalInjector(providerCache, function(serviceName, caller) {
  15442. if (angular.isString(caller)) {
  15443. path.push(caller);
  15444. }
  15445. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  15446. })),
  15447. instanceCache = {},
  15448. protoInstanceInjector =
  15449. createInternalInjector(instanceCache, function(serviceName, caller) {
  15450. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  15451. return instanceInjector.invoke(
  15452. provider.$get, provider, undefined, serviceName);
  15453. }),
  15454. instanceInjector = protoInstanceInjector;
  15455. providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) };
  15456. var runBlocks = loadModules(modulesToLoad);
  15457. instanceInjector = protoInstanceInjector.get('$injector');
  15458. instanceInjector.strictDi = strictDi;
  15459. forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); });
  15460. return instanceInjector;
  15461. ////////////////////////////////////
  15462. // $provider
  15463. ////////////////////////////////////
  15464. function supportObject(delegate) {
  15465. return function(key, value) {
  15466. if (isObject(key)) {
  15467. forEach(key, reverseParams(delegate));
  15468. } else {
  15469. return delegate(key, value);
  15470. }
  15471. };
  15472. }
  15473. function provider(name, provider_) {
  15474. assertNotHasOwnProperty(name, 'service');
  15475. if (isFunction(provider_) || isArray(provider_)) {
  15476. provider_ = providerInjector.instantiate(provider_);
  15477. }
  15478. if (!provider_.$get) {
  15479. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  15480. }
  15481. return providerCache[name + providerSuffix] = provider_;
  15482. }
  15483. function enforceReturnValue(name, factory) {
  15484. return function enforcedReturnValue() {
  15485. var result = instanceInjector.invoke(factory, this);
  15486. if (isUndefined(result)) {
  15487. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  15488. }
  15489. return result;
  15490. };
  15491. }
  15492. function factory(name, factoryFn, enforce) {
  15493. return provider(name, {
  15494. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  15495. });
  15496. }
  15497. function service(name, constructor) {
  15498. return factory(name, ['$injector', function($injector) {
  15499. return $injector.instantiate(constructor);
  15500. }]);
  15501. }
  15502. function value(name, val) { return factory(name, valueFn(val), false); }
  15503. function constant(name, value) {
  15504. assertNotHasOwnProperty(name, 'constant');
  15505. providerCache[name] = value;
  15506. instanceCache[name] = value;
  15507. }
  15508. function decorator(serviceName, decorFn) {
  15509. var origProvider = providerInjector.get(serviceName + providerSuffix),
  15510. orig$get = origProvider.$get;
  15511. origProvider.$get = function() {
  15512. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  15513. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  15514. };
  15515. }
  15516. ////////////////////////////////////
  15517. // Module Loading
  15518. ////////////////////////////////////
  15519. function loadModules(modulesToLoad) {
  15520. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  15521. var runBlocks = [], moduleFn;
  15522. forEach(modulesToLoad, function(module) {
  15523. if (loadedModules.get(module)) return;
  15524. loadedModules.put(module, true);
  15525. function runInvokeQueue(queue) {
  15526. var i, ii;
  15527. for (i = 0, ii = queue.length; i < ii; i++) {
  15528. var invokeArgs = queue[i],
  15529. provider = providerInjector.get(invokeArgs[0]);
  15530. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  15531. }
  15532. }
  15533. try {
  15534. if (isString(module)) {
  15535. moduleFn = angularModule(module);
  15536. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  15537. runInvokeQueue(moduleFn._invokeQueue);
  15538. runInvokeQueue(moduleFn._configBlocks);
  15539. } else if (isFunction(module)) {
  15540. runBlocks.push(providerInjector.invoke(module));
  15541. } else if (isArray(module)) {
  15542. runBlocks.push(providerInjector.invoke(module));
  15543. } else {
  15544. assertArgFn(module, 'module');
  15545. }
  15546. } catch (e) {
  15547. if (isArray(module)) {
  15548. module = module[module.length - 1];
  15549. }
  15550. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  15551. // Safari & FF's stack traces don't contain error.message content
  15552. // unlike those of Chrome and IE
  15553. // So if stack doesn't contain message, we create a new string that contains both.
  15554. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  15555. /* jshint -W022 */
  15556. e = e.message + '\n' + e.stack;
  15557. }
  15558. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  15559. module, e.stack || e.message || e);
  15560. }
  15561. });
  15562. return runBlocks;
  15563. }
  15564. ////////////////////////////////////
  15565. // internal Injector
  15566. ////////////////////////////////////
  15567. function createInternalInjector(cache, factory) {
  15568. function getService(serviceName, caller) {
  15569. if (cache.hasOwnProperty(serviceName)) {
  15570. if (cache[serviceName] === INSTANTIATING) {
  15571. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  15572. serviceName + ' <- ' + path.join(' <- '));
  15573. }
  15574. return cache[serviceName];
  15575. } else {
  15576. try {
  15577. path.unshift(serviceName);
  15578. cache[serviceName] = INSTANTIATING;
  15579. return cache[serviceName] = factory(serviceName, caller);
  15580. } catch (err) {
  15581. if (cache[serviceName] === INSTANTIATING) {
  15582. delete cache[serviceName];
  15583. }
  15584. throw err;
  15585. } finally {
  15586. path.shift();
  15587. }
  15588. }
  15589. }
  15590. function injectionArgs(fn, locals, serviceName) {
  15591. var args = [],
  15592. $inject = createInjector.$$annotate(fn, strictDi, serviceName);
  15593. for (var i = 0, length = $inject.length; i < length; i++) {
  15594. var key = $inject[i];
  15595. if (typeof key !== 'string') {
  15596. throw $injectorMinErr('itkn',
  15597. 'Incorrect injection token! Expected service name as string, got {0}', key);
  15598. }
  15599. args.push(locals && locals.hasOwnProperty(key) ? locals[key] :
  15600. getService(key, serviceName));
  15601. }
  15602. return args;
  15603. }
  15604. function isClass(func) {
  15605. // IE 9-11 do not support classes and IE9 leaks with the code below.
  15606. if (msie <= 11) {
  15607. return false;
  15608. }
  15609. // Workaround for MS Edge.
  15610. // Check https://connect.microsoft.com/IE/Feedback/Details/2211653
  15611. return typeof func === 'function'
  15612. && /^(?:class\s|constructor\()/.test(Function.prototype.toString.call(func));
  15613. }
  15614. function invoke(fn, self, locals, serviceName) {
  15615. if (typeof locals === 'string') {
  15616. serviceName = locals;
  15617. locals = null;
  15618. }
  15619. var args = injectionArgs(fn, locals, serviceName);
  15620. if (isArray(fn)) {
  15621. fn = fn[fn.length - 1];
  15622. }
  15623. if (!isClass(fn)) {
  15624. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  15625. // #5388
  15626. return fn.apply(self, args);
  15627. } else {
  15628. args.unshift(null);
  15629. return new (Function.prototype.bind.apply(fn, args))();
  15630. }
  15631. }
  15632. function instantiate(Type, locals, serviceName) {
  15633. // Check if Type is annotated and use just the given function at n-1 as parameter
  15634. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  15635. var ctor = (isArray(Type) ? Type[Type.length - 1] : Type);
  15636. var args = injectionArgs(Type, locals, serviceName);
  15637. // Empty object at position 0 is ignored for invocation with `new`, but required.
  15638. args.unshift(null);
  15639. return new (Function.prototype.bind.apply(ctor, args))();
  15640. }
  15641. return {
  15642. invoke: invoke,
  15643. instantiate: instantiate,
  15644. get: getService,
  15645. annotate: createInjector.$$annotate,
  15646. has: function(name) {
  15647. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  15648. }
  15649. };
  15650. }
  15651. }
  15652. createInjector.$$annotate = annotate;
  15653. /**
  15654. * @ngdoc provider
  15655. * @name $anchorScrollProvider
  15656. *
  15657. * @description
  15658. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  15659. * {@link ng.$location#hash $location.hash()} changes.
  15660. */
  15661. function $AnchorScrollProvider() {
  15662. var autoScrollingEnabled = true;
  15663. /**
  15664. * @ngdoc method
  15665. * @name $anchorScrollProvider#disableAutoScrolling
  15666. *
  15667. * @description
  15668. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  15669. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  15670. * Use this method to disable automatic scrolling.
  15671. *
  15672. * If automatic scrolling is disabled, one must explicitly call
  15673. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  15674. * current hash.
  15675. */
  15676. this.disableAutoScrolling = function() {
  15677. autoScrollingEnabled = false;
  15678. };
  15679. /**
  15680. * @ngdoc service
  15681. * @name $anchorScroll
  15682. * @kind function
  15683. * @requires $window
  15684. * @requires $location
  15685. * @requires $rootScope
  15686. *
  15687. * @description
  15688. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  15689. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  15690. * in the
  15691. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  15692. *
  15693. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  15694. * match any anchor whenever it changes. This can be disabled by calling
  15695. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  15696. *
  15697. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  15698. * vertical scroll-offset (either fixed or dynamic).
  15699. *
  15700. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  15701. * {@link ng.$location#hash $location.hash()} will be used.
  15702. *
  15703. * @property {(number|function|jqLite)} yOffset
  15704. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  15705. * positioned elements at the top of the page, such as navbars, headers etc.
  15706. *
  15707. * `yOffset` can be specified in various ways:
  15708. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  15709. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  15710. * a number representing the offset (in pixels).<br /><br />
  15711. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  15712. * the top of the page to the element's bottom will be used as offset.<br />
  15713. * **Note**: The element will be taken into account only as long as its `position` is set to
  15714. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  15715. * their height and/or positioning according to the viewport's size.
  15716. *
  15717. * <br />
  15718. * <div class="alert alert-warning">
  15719. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  15720. * not some child element.
  15721. * </div>
  15722. *
  15723. * @example
  15724. <example module="anchorScrollExample">
  15725. <file name="index.html">
  15726. <div id="scrollArea" ng-controller="ScrollController">
  15727. <a ng-click="gotoBottom()">Go to bottom</a>
  15728. <a id="bottom"></a> You're at the bottom!
  15729. </div>
  15730. </file>
  15731. <file name="script.js">
  15732. angular.module('anchorScrollExample', [])
  15733. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  15734. function ($scope, $location, $anchorScroll) {
  15735. $scope.gotoBottom = function() {
  15736. // set the location.hash to the id of
  15737. // the element you wish to scroll to.
  15738. $location.hash('bottom');
  15739. // call $anchorScroll()
  15740. $anchorScroll();
  15741. };
  15742. }]);
  15743. </file>
  15744. <file name="style.css">
  15745. #scrollArea {
  15746. height: 280px;
  15747. overflow: auto;
  15748. }
  15749. #bottom {
  15750. display: block;
  15751. margin-top: 2000px;
  15752. }
  15753. </file>
  15754. </example>
  15755. *
  15756. * <hr />
  15757. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  15758. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  15759. *
  15760. * @example
  15761. <example module="anchorScrollOffsetExample">
  15762. <file name="index.html">
  15763. <div class="fixed-header" ng-controller="headerCtrl">
  15764. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  15765. Go to anchor {{x}}
  15766. </a>
  15767. </div>
  15768. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  15769. Anchor {{x}} of 5
  15770. </div>
  15771. </file>
  15772. <file name="script.js">
  15773. angular.module('anchorScrollOffsetExample', [])
  15774. .run(['$anchorScroll', function($anchorScroll) {
  15775. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  15776. }])
  15777. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  15778. function ($anchorScroll, $location, $scope) {
  15779. $scope.gotoAnchor = function(x) {
  15780. var newHash = 'anchor' + x;
  15781. if ($location.hash() !== newHash) {
  15782. // set the $location.hash to `newHash` and
  15783. // $anchorScroll will automatically scroll to it
  15784. $location.hash('anchor' + x);
  15785. } else {
  15786. // call $anchorScroll() explicitly,
  15787. // since $location.hash hasn't changed
  15788. $anchorScroll();
  15789. }
  15790. };
  15791. }
  15792. ]);
  15793. </file>
  15794. <file name="style.css">
  15795. body {
  15796. padding-top: 50px;
  15797. }
  15798. .anchor {
  15799. border: 2px dashed DarkOrchid;
  15800. padding: 10px 10px 200px 10px;
  15801. }
  15802. .fixed-header {
  15803. background-color: rgba(0, 0, 0, 0.2);
  15804. height: 50px;
  15805. position: fixed;
  15806. top: 0; left: 0; right: 0;
  15807. }
  15808. .fixed-header > a {
  15809. display: inline-block;
  15810. margin: 5px 15px;
  15811. }
  15812. </file>
  15813. </example>
  15814. */
  15815. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  15816. var document = $window.document;
  15817. // Helper function to get first anchor from a NodeList
  15818. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  15819. // and working in all supported browsers.)
  15820. function getFirstAnchor(list) {
  15821. var result = null;
  15822. Array.prototype.some.call(list, function(element) {
  15823. if (nodeName_(element) === 'a') {
  15824. result = element;
  15825. return true;
  15826. }
  15827. });
  15828. return result;
  15829. }
  15830. function getYOffset() {
  15831. var offset = scroll.yOffset;
  15832. if (isFunction(offset)) {
  15833. offset = offset();
  15834. } else if (isElement(offset)) {
  15835. var elem = offset[0];
  15836. var style = $window.getComputedStyle(elem);
  15837. if (style.position !== 'fixed') {
  15838. offset = 0;
  15839. } else {
  15840. offset = elem.getBoundingClientRect().bottom;
  15841. }
  15842. } else if (!isNumber(offset)) {
  15843. offset = 0;
  15844. }
  15845. return offset;
  15846. }
  15847. function scrollTo(elem) {
  15848. if (elem) {
  15849. elem.scrollIntoView();
  15850. var offset = getYOffset();
  15851. if (offset) {
  15852. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  15853. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  15854. // top of the viewport.
  15855. //
  15856. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  15857. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  15858. // way down the page.
  15859. //
  15860. // This is often the case for elements near the bottom of the page.
  15861. //
  15862. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  15863. // the top of the element and the offset, which is enough to align the top of `elem` at the
  15864. // desired position.
  15865. var elemTop = elem.getBoundingClientRect().top;
  15866. $window.scrollBy(0, elemTop - offset);
  15867. }
  15868. } else {
  15869. $window.scrollTo(0, 0);
  15870. }
  15871. }
  15872. function scroll(hash) {
  15873. hash = isString(hash) ? hash : $location.hash();
  15874. var elm;
  15875. // empty hash, scroll to the top of the page
  15876. if (!hash) scrollTo(null);
  15877. // element with given id
  15878. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  15879. // first anchor with given name :-D
  15880. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  15881. // no element and hash == 'top', scroll to the top of the page
  15882. else if (hash === 'top') scrollTo(null);
  15883. }
  15884. // does not scroll when user clicks on anchor link that is currently on
  15885. // (no url change, no $location.hash() change), browser native does scroll
  15886. if (autoScrollingEnabled) {
  15887. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  15888. function autoScrollWatchAction(newVal, oldVal) {
  15889. // skip the initial scroll if $location.hash is empty
  15890. if (newVal === oldVal && newVal === '') return;
  15891. jqLiteDocumentLoaded(function() {
  15892. $rootScope.$evalAsync(scroll);
  15893. });
  15894. });
  15895. }
  15896. return scroll;
  15897. }];
  15898. }
  15899. var $animateMinErr = minErr('$animate');
  15900. var ELEMENT_NODE = 1;
  15901. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  15902. function mergeClasses(a,b) {
  15903. if (!a && !b) return '';
  15904. if (!a) return b;
  15905. if (!b) return a;
  15906. if (isArray(a)) a = a.join(' ');
  15907. if (isArray(b)) b = b.join(' ');
  15908. return a + ' ' + b;
  15909. }
  15910. function extractElementNode(element) {
  15911. for (var i = 0; i < element.length; i++) {
  15912. var elm = element[i];
  15913. if (elm.nodeType === ELEMENT_NODE) {
  15914. return elm;
  15915. }
  15916. }
  15917. }
  15918. function splitClasses(classes) {
  15919. if (isString(classes)) {
  15920. classes = classes.split(' ');
  15921. }
  15922. // Use createMap() to prevent class assumptions involving property names in
  15923. // Object.prototype
  15924. var obj = createMap();
  15925. forEach(classes, function(klass) {
  15926. // sometimes the split leaves empty string values
  15927. // incase extra spaces were applied to the options
  15928. if (klass.length) {
  15929. obj[klass] = true;
  15930. }
  15931. });
  15932. return obj;
  15933. }
  15934. // if any other type of options value besides an Object value is
  15935. // passed into the $animate.method() animation then this helper code
  15936. // will be run which will ignore it. While this patch is not the
  15937. // greatest solution to this, a lot of existing plugins depend on
  15938. // $animate to either call the callback (< 1.2) or return a promise
  15939. // that can be changed. This helper function ensures that the options
  15940. // are wiped clean incase a callback function is provided.
  15941. function prepareAnimateOptions(options) {
  15942. return isObject(options)
  15943. ? options
  15944. : {};
  15945. }
  15946. var $$CoreAnimateJsProvider = function() {
  15947. this.$get = noop;
  15948. };
  15949. // this is prefixed with Core since it conflicts with
  15950. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  15951. var $$CoreAnimateQueueProvider = function() {
  15952. var postDigestQueue = new HashMap();
  15953. var postDigestElements = [];
  15954. this.$get = ['$$AnimateRunner', '$rootScope',
  15955. function($$AnimateRunner, $rootScope) {
  15956. return {
  15957. enabled: noop,
  15958. on: noop,
  15959. off: noop,
  15960. pin: noop,
  15961. push: function(element, event, options, domOperation) {
  15962. domOperation && domOperation();
  15963. options = options || {};
  15964. options.from && element.css(options.from);
  15965. options.to && element.css(options.to);
  15966. if (options.addClass || options.removeClass) {
  15967. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  15968. }
  15969. var runner = new $$AnimateRunner(); // jshint ignore:line
  15970. // since there are no animations to run the runner needs to be
  15971. // notified that the animation call is complete.
  15972. runner.complete();
  15973. return runner;
  15974. }
  15975. };
  15976. function updateData(data, classes, value) {
  15977. var changed = false;
  15978. if (classes) {
  15979. classes = isString(classes) ? classes.split(' ') :
  15980. isArray(classes) ? classes : [];
  15981. forEach(classes, function(className) {
  15982. if (className) {
  15983. changed = true;
  15984. data[className] = value;
  15985. }
  15986. });
  15987. }
  15988. return changed;
  15989. }
  15990. function handleCSSClassChanges() {
  15991. forEach(postDigestElements, function(element) {
  15992. var data = postDigestQueue.get(element);
  15993. if (data) {
  15994. var existing = splitClasses(element.attr('class'));
  15995. var toAdd = '';
  15996. var toRemove = '';
  15997. forEach(data, function(status, className) {
  15998. var hasClass = !!existing[className];
  15999. if (status !== hasClass) {
  16000. if (status) {
  16001. toAdd += (toAdd.length ? ' ' : '') + className;
  16002. } else {
  16003. toRemove += (toRemove.length ? ' ' : '') + className;
  16004. }
  16005. }
  16006. });
  16007. forEach(element, function(elm) {
  16008. toAdd && jqLiteAddClass(elm, toAdd);
  16009. toRemove && jqLiteRemoveClass(elm, toRemove);
  16010. });
  16011. postDigestQueue.remove(element);
  16012. }
  16013. });
  16014. postDigestElements.length = 0;
  16015. }
  16016. function addRemoveClassesPostDigest(element, add, remove) {
  16017. var data = postDigestQueue.get(element) || {};
  16018. var classesAdded = updateData(data, add, true);
  16019. var classesRemoved = updateData(data, remove, false);
  16020. if (classesAdded || classesRemoved) {
  16021. postDigestQueue.put(element, data);
  16022. postDigestElements.push(element);
  16023. if (postDigestElements.length === 1) {
  16024. $rootScope.$$postDigest(handleCSSClassChanges);
  16025. }
  16026. }
  16027. }
  16028. }];
  16029. };
  16030. /**
  16031. * @ngdoc provider
  16032. * @name $animateProvider
  16033. *
  16034. * @description
  16035. * Default implementation of $animate that doesn't perform any animations, instead just
  16036. * synchronously performs DOM updates and resolves the returned runner promise.
  16037. *
  16038. * In order to enable animations the `ngAnimate` module has to be loaded.
  16039. *
  16040. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  16041. */
  16042. var $AnimateProvider = ['$provide', function($provide) {
  16043. var provider = this;
  16044. this.$$registeredAnimations = Object.create(null);
  16045. /**
  16046. * @ngdoc method
  16047. * @name $animateProvider#register
  16048. *
  16049. * @description
  16050. * Registers a new injectable animation factory function. The factory function produces the
  16051. * animation object which contains callback functions for each event that is expected to be
  16052. * animated.
  16053. *
  16054. * * `eventFn`: `function(element, ... , doneFunction, options)`
  16055. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  16056. * on the type of animation additional arguments will be injected into the animation function. The
  16057. * list below explains the function signatures for the different animation methods:
  16058. *
  16059. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  16060. * - addClass: function(element, addedClasses, doneFunction, options)
  16061. * - removeClass: function(element, removedClasses, doneFunction, options)
  16062. * - enter, leave, move: function(element, doneFunction, options)
  16063. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  16064. *
  16065. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  16066. *
  16067. * ```js
  16068. * return {
  16069. * //enter, leave, move signature
  16070. * eventFn : function(element, done, options) {
  16071. * //code to run the animation
  16072. * //once complete, then run done()
  16073. * return function endFunction(wasCancelled) {
  16074. * //code to cancel the animation
  16075. * }
  16076. * }
  16077. * }
  16078. * ```
  16079. *
  16080. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  16081. * @param {Function} factory The factory function that will be executed to return the animation
  16082. * object.
  16083. */
  16084. this.register = function(name, factory) {
  16085. if (name && name.charAt(0) !== '.') {
  16086. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  16087. }
  16088. var key = name + '-animation';
  16089. provider.$$registeredAnimations[name.substr(1)] = key;
  16090. $provide.factory(key, factory);
  16091. };
  16092. /**
  16093. * @ngdoc method
  16094. * @name $animateProvider#classNameFilter
  16095. *
  16096. * @description
  16097. * Sets and/or returns the CSS class regular expression that is checked when performing
  16098. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  16099. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  16100. * When setting the `classNameFilter` value, animations will only be performed on elements
  16101. * that successfully match the filter expression. This in turn can boost performance
  16102. * for low-powered devices as well as applications containing a lot of structural operations.
  16103. * @param {RegExp=} expression The className expression which will be checked against all animations
  16104. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  16105. */
  16106. this.classNameFilter = function(expression) {
  16107. if (arguments.length === 1) {
  16108. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  16109. if (this.$$classNameFilter) {
  16110. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  16111. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  16112. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  16113. }
  16114. }
  16115. }
  16116. return this.$$classNameFilter;
  16117. };
  16118. this.$get = ['$$animateQueue', function($$animateQueue) {
  16119. function domInsert(element, parentElement, afterElement) {
  16120. // if for some reason the previous element was removed
  16121. // from the dom sometime before this code runs then let's
  16122. // just stick to using the parent element as the anchor
  16123. if (afterElement) {
  16124. var afterNode = extractElementNode(afterElement);
  16125. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  16126. afterElement = null;
  16127. }
  16128. }
  16129. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  16130. }
  16131. /**
  16132. * @ngdoc service
  16133. * @name $animate
  16134. * @description The $animate service exposes a series of DOM utility methods that provide support
  16135. * for animation hooks. The default behavior is the application of DOM operations, however,
  16136. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  16137. * to ensure that animation runs with the triggered DOM operation.
  16138. *
  16139. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  16140. * included and only when it is active then the animation hooks that `$animate` triggers will be
  16141. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  16142. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  16143. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  16144. *
  16145. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  16146. *
  16147. * To learn more about enabling animation support, click here to visit the
  16148. * {@link ngAnimate ngAnimate module page}.
  16149. */
  16150. return {
  16151. // we don't call it directly since non-existant arguments may
  16152. // be interpreted as null within the sub enabled function
  16153. /**
  16154. *
  16155. * @ngdoc method
  16156. * @name $animate#on
  16157. * @kind function
  16158. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  16159. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  16160. * is fired with the following params:
  16161. *
  16162. * ```js
  16163. * $animate.on('enter', container,
  16164. * function callback(element, phase) {
  16165. * // cool we detected an enter animation within the container
  16166. * }
  16167. * );
  16168. * ```
  16169. *
  16170. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  16171. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  16172. * as well as among its children
  16173. * @param {Function} callback the callback function that will be fired when the listener is triggered
  16174. *
  16175. * The arguments present in the callback function are:
  16176. * * `element` - The captured DOM element that the animation was fired on.
  16177. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  16178. */
  16179. on: $$animateQueue.on,
  16180. /**
  16181. *
  16182. * @ngdoc method
  16183. * @name $animate#off
  16184. * @kind function
  16185. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  16186. * can be used in three different ways depending on the arguments:
  16187. *
  16188. * ```js
  16189. * // remove all the animation event listeners listening for `enter`
  16190. * $animate.off('enter');
  16191. *
  16192. * // remove all the animation event listeners listening for `enter` on the given element and its children
  16193. * $animate.off('enter', container);
  16194. *
  16195. * // remove the event listener function provided by `callback` that is set
  16196. * // to listen for `enter` on the given `container` as well as its children
  16197. * $animate.off('enter', container, callback);
  16198. * ```
  16199. *
  16200. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  16201. * @param {DOMElement=} container the container element the event listener was placed on
  16202. * @param {Function=} callback the callback function that was registered as the listener
  16203. */
  16204. off: $$animateQueue.off,
  16205. /**
  16206. * @ngdoc method
  16207. * @name $animate#pin
  16208. * @kind function
  16209. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  16210. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  16211. * element despite being outside the realm of the application or within another application. Say for example if the application
  16212. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  16213. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  16214. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  16215. *
  16216. * Note that this feature is only active when the `ngAnimate` module is used.
  16217. *
  16218. * @param {DOMElement} element the external element that will be pinned
  16219. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  16220. */
  16221. pin: $$animateQueue.pin,
  16222. /**
  16223. *
  16224. * @ngdoc method
  16225. * @name $animate#enabled
  16226. * @kind function
  16227. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  16228. * function can be called in four ways:
  16229. *
  16230. * ```js
  16231. * // returns true or false
  16232. * $animate.enabled();
  16233. *
  16234. * // changes the enabled state for all animations
  16235. * $animate.enabled(false);
  16236. * $animate.enabled(true);
  16237. *
  16238. * // returns true or false if animations are enabled for an element
  16239. * $animate.enabled(element);
  16240. *
  16241. * // changes the enabled state for an element and its children
  16242. * $animate.enabled(element, true);
  16243. * $animate.enabled(element, false);
  16244. * ```
  16245. *
  16246. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  16247. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  16248. *
  16249. * @return {boolean} whether or not animations are enabled
  16250. */
  16251. enabled: $$animateQueue.enabled,
  16252. /**
  16253. * @ngdoc method
  16254. * @name $animate#cancel
  16255. * @kind function
  16256. * @description Cancels the provided animation.
  16257. *
  16258. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  16259. */
  16260. cancel: function(runner) {
  16261. runner.end && runner.end();
  16262. },
  16263. /**
  16264. *
  16265. * @ngdoc method
  16266. * @name $animate#enter
  16267. * @kind function
  16268. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  16269. * as the first child within the `parent` element and then triggers an animation.
  16270. * A promise is returned that will be resolved during the next digest once the animation
  16271. * has completed.
  16272. *
  16273. * @param {DOMElement} element the element which will be inserted into the DOM
  16274. * @param {DOMElement} parent the parent element which will append the element as
  16275. * a child (so long as the after element is not present)
  16276. * @param {DOMElement=} after the sibling element after which the element will be appended
  16277. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16278. *
  16279. * @return {Promise} the animation callback promise
  16280. */
  16281. enter: function(element, parent, after, options) {
  16282. parent = parent && jqLite(parent);
  16283. after = after && jqLite(after);
  16284. parent = parent || after.parent();
  16285. domInsert(element, parent, after);
  16286. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  16287. },
  16288. /**
  16289. *
  16290. * @ngdoc method
  16291. * @name $animate#move
  16292. * @kind function
  16293. * @description Inserts (moves) the element into its new position in the DOM either after
  16294. * the `after` element (if provided) or as the first child within the `parent` element
  16295. * and then triggers an animation. A promise is returned that will be resolved
  16296. * during the next digest once the animation has completed.
  16297. *
  16298. * @param {DOMElement} element the element which will be moved into the new DOM position
  16299. * @param {DOMElement} parent the parent element which will append the element as
  16300. * a child (so long as the after element is not present)
  16301. * @param {DOMElement=} after the sibling element after which the element will be appended
  16302. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16303. *
  16304. * @return {Promise} the animation callback promise
  16305. */
  16306. move: function(element, parent, after, options) {
  16307. parent = parent && jqLite(parent);
  16308. after = after && jqLite(after);
  16309. parent = parent || after.parent();
  16310. domInsert(element, parent, after);
  16311. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  16312. },
  16313. /**
  16314. * @ngdoc method
  16315. * @name $animate#leave
  16316. * @kind function
  16317. * @description Triggers an animation and then removes the element from the DOM.
  16318. * When the function is called a promise is returned that will be resolved during the next
  16319. * digest once the animation has completed.
  16320. *
  16321. * @param {DOMElement} element the element which will be removed from the DOM
  16322. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16323. *
  16324. * @return {Promise} the animation callback promise
  16325. */
  16326. leave: function(element, options) {
  16327. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  16328. element.remove();
  16329. });
  16330. },
  16331. /**
  16332. * @ngdoc method
  16333. * @name $animate#addClass
  16334. * @kind function
  16335. *
  16336. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  16337. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  16338. * animation if element already contains the CSS class or if the class is removed at a later step.
  16339. * Note that class-based animations are treated differently compared to structural animations
  16340. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16341. * depending if CSS or JavaScript animations are used.
  16342. *
  16343. * @param {DOMElement} element the element which the CSS classes will be applied to
  16344. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  16345. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16346. *
  16347. * @return {Promise} the animation callback promise
  16348. */
  16349. addClass: function(element, className, options) {
  16350. options = prepareAnimateOptions(options);
  16351. options.addClass = mergeClasses(options.addclass, className);
  16352. return $$animateQueue.push(element, 'addClass', options);
  16353. },
  16354. /**
  16355. * @ngdoc method
  16356. * @name $animate#removeClass
  16357. * @kind function
  16358. *
  16359. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  16360. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  16361. * animation if element does not contain the CSS class or if the class is added at a later step.
  16362. * Note that class-based animations are treated differently compared to structural animations
  16363. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16364. * depending if CSS or JavaScript animations are used.
  16365. *
  16366. * @param {DOMElement} element the element which the CSS classes will be applied to
  16367. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  16368. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16369. *
  16370. * @return {Promise} the animation callback promise
  16371. */
  16372. removeClass: function(element, className, options) {
  16373. options = prepareAnimateOptions(options);
  16374. options.removeClass = mergeClasses(options.removeClass, className);
  16375. return $$animateQueue.push(element, 'removeClass', options);
  16376. },
  16377. /**
  16378. * @ngdoc method
  16379. * @name $animate#setClass
  16380. * @kind function
  16381. *
  16382. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  16383. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  16384. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  16385. * passed. Note that class-based animations are treated differently compared to structural animations
  16386. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  16387. * depending if CSS or JavaScript animations are used.
  16388. *
  16389. * @param {DOMElement} element the element which the CSS classes will be applied to
  16390. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  16391. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  16392. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16393. *
  16394. * @return {Promise} the animation callback promise
  16395. */
  16396. setClass: function(element, add, remove, options) {
  16397. options = prepareAnimateOptions(options);
  16398. options.addClass = mergeClasses(options.addClass, add);
  16399. options.removeClass = mergeClasses(options.removeClass, remove);
  16400. return $$animateQueue.push(element, 'setClass', options);
  16401. },
  16402. /**
  16403. * @ngdoc method
  16404. * @name $animate#animate
  16405. * @kind function
  16406. *
  16407. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  16408. * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take
  16409. * on the provided styles. For example, if a transition animation is set for the given classNamem, then the provided `from` and
  16410. * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding
  16411. * style in `to`, the style in `from` is applied immediately, and no animation is run.
  16412. * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate`
  16413. * method (or as part of the `options` parameter):
  16414. *
  16415. * ```js
  16416. * ngModule.animation('.my-inline-animation', function() {
  16417. * return {
  16418. * animate : function(element, from, to, done, options) {
  16419. * //animation
  16420. * done();
  16421. * }
  16422. * }
  16423. * });
  16424. * ```
  16425. *
  16426. * @param {DOMElement} element the element which the CSS styles will be applied to
  16427. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  16428. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  16429. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  16430. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  16431. * (Note that if no animation is detected then this value will not be applied to the element.)
  16432. * @param {object=} options an optional collection of options/styles that will be applied to the element
  16433. *
  16434. * @return {Promise} the animation callback promise
  16435. */
  16436. animate: function(element, from, to, className, options) {
  16437. options = prepareAnimateOptions(options);
  16438. options.from = options.from ? extend(options.from, from) : from;
  16439. options.to = options.to ? extend(options.to, to) : to;
  16440. className = className || 'ng-inline-animate';
  16441. options.tempClasses = mergeClasses(options.tempClasses, className);
  16442. return $$animateQueue.push(element, 'animate', options);
  16443. }
  16444. };
  16445. }];
  16446. }];
  16447. var $$AnimateAsyncRunFactoryProvider = function() {
  16448. this.$get = ['$$rAF', function($$rAF) {
  16449. var waitQueue = [];
  16450. function waitForTick(fn) {
  16451. waitQueue.push(fn);
  16452. if (waitQueue.length > 1) return;
  16453. $$rAF(function() {
  16454. for (var i = 0; i < waitQueue.length; i++) {
  16455. waitQueue[i]();
  16456. }
  16457. waitQueue = [];
  16458. });
  16459. }
  16460. return function() {
  16461. var passed = false;
  16462. waitForTick(function() {
  16463. passed = true;
  16464. });
  16465. return function(callback) {
  16466. passed ? callback() : waitForTick(callback);
  16467. };
  16468. };
  16469. }];
  16470. };
  16471. var $$AnimateRunnerFactoryProvider = function() {
  16472. this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$document', '$timeout',
  16473. function($q, $sniffer, $$animateAsyncRun, $document, $timeout) {
  16474. var INITIAL_STATE = 0;
  16475. var DONE_PENDING_STATE = 1;
  16476. var DONE_COMPLETE_STATE = 2;
  16477. AnimateRunner.chain = function(chain, callback) {
  16478. var index = 0;
  16479. next();
  16480. function next() {
  16481. if (index === chain.length) {
  16482. callback(true);
  16483. return;
  16484. }
  16485. chain[index](function(response) {
  16486. if (response === false) {
  16487. callback(false);
  16488. return;
  16489. }
  16490. index++;
  16491. next();
  16492. });
  16493. }
  16494. };
  16495. AnimateRunner.all = function(runners, callback) {
  16496. var count = 0;
  16497. var status = true;
  16498. forEach(runners, function(runner) {
  16499. runner.done(onProgress);
  16500. });
  16501. function onProgress(response) {
  16502. status = status && response;
  16503. if (++count === runners.length) {
  16504. callback(status);
  16505. }
  16506. }
  16507. };
  16508. function AnimateRunner(host) {
  16509. this.setHost(host);
  16510. var rafTick = $$animateAsyncRun();
  16511. var timeoutTick = function(fn) {
  16512. $timeout(fn, 0, false);
  16513. };
  16514. this._doneCallbacks = [];
  16515. this._tick = function(fn) {
  16516. var doc = $document[0];
  16517. // the document may not be ready or attached
  16518. // to the module for some internal tests
  16519. if (doc && doc.hidden) {
  16520. timeoutTick(fn);
  16521. } else {
  16522. rafTick(fn);
  16523. }
  16524. };
  16525. this._state = 0;
  16526. }
  16527. AnimateRunner.prototype = {
  16528. setHost: function(host) {
  16529. this.host = host || {};
  16530. },
  16531. done: function(fn) {
  16532. if (this._state === DONE_COMPLETE_STATE) {
  16533. fn();
  16534. } else {
  16535. this._doneCallbacks.push(fn);
  16536. }
  16537. },
  16538. progress: noop,
  16539. getPromise: function() {
  16540. if (!this.promise) {
  16541. var self = this;
  16542. this.promise = $q(function(resolve, reject) {
  16543. self.done(function(status) {
  16544. status === false ? reject() : resolve();
  16545. });
  16546. });
  16547. }
  16548. return this.promise;
  16549. },
  16550. then: function(resolveHandler, rejectHandler) {
  16551. return this.getPromise().then(resolveHandler, rejectHandler);
  16552. },
  16553. 'catch': function(handler) {
  16554. return this.getPromise()['catch'](handler);
  16555. },
  16556. 'finally': function(handler) {
  16557. return this.getPromise()['finally'](handler);
  16558. },
  16559. pause: function() {
  16560. if (this.host.pause) {
  16561. this.host.pause();
  16562. }
  16563. },
  16564. resume: function() {
  16565. if (this.host.resume) {
  16566. this.host.resume();
  16567. }
  16568. },
  16569. end: function() {
  16570. if (this.host.end) {
  16571. this.host.end();
  16572. }
  16573. this._resolve(true);
  16574. },
  16575. cancel: function() {
  16576. if (this.host.cancel) {
  16577. this.host.cancel();
  16578. }
  16579. this._resolve(false);
  16580. },
  16581. complete: function(response) {
  16582. var self = this;
  16583. if (self._state === INITIAL_STATE) {
  16584. self._state = DONE_PENDING_STATE;
  16585. self._tick(function() {
  16586. self._resolve(response);
  16587. });
  16588. }
  16589. },
  16590. _resolve: function(response) {
  16591. if (this._state !== DONE_COMPLETE_STATE) {
  16592. forEach(this._doneCallbacks, function(fn) {
  16593. fn(response);
  16594. });
  16595. this._doneCallbacks.length = 0;
  16596. this._state = DONE_COMPLETE_STATE;
  16597. }
  16598. }
  16599. };
  16600. return AnimateRunner;
  16601. }];
  16602. };
  16603. /**
  16604. * @ngdoc service
  16605. * @name $animateCss
  16606. * @kind object
  16607. *
  16608. * @description
  16609. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  16610. * then the `$animateCss` service will actually perform animations.
  16611. *
  16612. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  16613. */
  16614. var $CoreAnimateCssProvider = function() {
  16615. this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) {
  16616. return function(element, initialOptions) {
  16617. // all of the animation functions should create
  16618. // a copy of the options data, however, if a
  16619. // parent service has already created a copy then
  16620. // we should stick to using that
  16621. var options = initialOptions || {};
  16622. if (!options.$$prepared) {
  16623. options = copy(options);
  16624. }
  16625. // there is no point in applying the styles since
  16626. // there is no animation that goes on at all in
  16627. // this version of $animateCss.
  16628. if (options.cleanupStyles) {
  16629. options.from = options.to = null;
  16630. }
  16631. if (options.from) {
  16632. element.css(options.from);
  16633. options.from = null;
  16634. }
  16635. /* jshint newcap: false */
  16636. var closed, runner = new $$AnimateRunner();
  16637. return {
  16638. start: run,
  16639. end: run
  16640. };
  16641. function run() {
  16642. $$rAF(function() {
  16643. applyAnimationContents();
  16644. if (!closed) {
  16645. runner.complete();
  16646. }
  16647. closed = true;
  16648. });
  16649. return runner;
  16650. }
  16651. function applyAnimationContents() {
  16652. if (options.addClass) {
  16653. element.addClass(options.addClass);
  16654. options.addClass = null;
  16655. }
  16656. if (options.removeClass) {
  16657. element.removeClass(options.removeClass);
  16658. options.removeClass = null;
  16659. }
  16660. if (options.to) {
  16661. element.css(options.to);
  16662. options.to = null;
  16663. }
  16664. }
  16665. };
  16666. }];
  16667. };
  16668. /* global stripHash: true */
  16669. /**
  16670. * ! This is a private undocumented service !
  16671. *
  16672. * @name $browser
  16673. * @requires $log
  16674. * @description
  16675. * This object has two goals:
  16676. *
  16677. * - hide all the global state in the browser caused by the window object
  16678. * - abstract away all the browser specific features and inconsistencies
  16679. *
  16680. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  16681. * service, which can be used for convenient testing of the application without the interaction with
  16682. * the real browser apis.
  16683. */
  16684. /**
  16685. * @param {object} window The global window object.
  16686. * @param {object} document jQuery wrapped document.
  16687. * @param {object} $log window.console or an object with the same interface.
  16688. * @param {object} $sniffer $sniffer service
  16689. */
  16690. function Browser(window, document, $log, $sniffer) {
  16691. var self = this,
  16692. location = window.location,
  16693. history = window.history,
  16694. setTimeout = window.setTimeout,
  16695. clearTimeout = window.clearTimeout,
  16696. pendingDeferIds = {};
  16697. self.isMock = false;
  16698. var outstandingRequestCount = 0;
  16699. var outstandingRequestCallbacks = [];
  16700. // TODO(vojta): remove this temporary api
  16701. self.$$completeOutstandingRequest = completeOutstandingRequest;
  16702. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  16703. /**
  16704. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  16705. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  16706. */
  16707. function completeOutstandingRequest(fn) {
  16708. try {
  16709. fn.apply(null, sliceArgs(arguments, 1));
  16710. } finally {
  16711. outstandingRequestCount--;
  16712. if (outstandingRequestCount === 0) {
  16713. while (outstandingRequestCallbacks.length) {
  16714. try {
  16715. outstandingRequestCallbacks.pop()();
  16716. } catch (e) {
  16717. $log.error(e);
  16718. }
  16719. }
  16720. }
  16721. }
  16722. }
  16723. function getHash(url) {
  16724. var index = url.indexOf('#');
  16725. return index === -1 ? '' : url.substr(index);
  16726. }
  16727. /**
  16728. * @private
  16729. * Note: this method is used only by scenario runner
  16730. * TODO(vojta): prefix this method with $$ ?
  16731. * @param {function()} callback Function that will be called when no outstanding request
  16732. */
  16733. self.notifyWhenNoOutstandingRequests = function(callback) {
  16734. if (outstandingRequestCount === 0) {
  16735. callback();
  16736. } else {
  16737. outstandingRequestCallbacks.push(callback);
  16738. }
  16739. };
  16740. //////////////////////////////////////////////////////////////
  16741. // URL API
  16742. //////////////////////////////////////////////////////////////
  16743. var cachedState, lastHistoryState,
  16744. lastBrowserUrl = location.href,
  16745. baseElement = document.find('base'),
  16746. pendingLocation = null,
  16747. getCurrentState = !$sniffer.history ? noop : function getCurrentState() {
  16748. try {
  16749. return history.state;
  16750. } catch (e) {
  16751. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  16752. }
  16753. };
  16754. cacheState();
  16755. lastHistoryState = cachedState;
  16756. /**
  16757. * @name $browser#url
  16758. *
  16759. * @description
  16760. * GETTER:
  16761. * Without any argument, this method just returns current value of location.href.
  16762. *
  16763. * SETTER:
  16764. * With at least one argument, this method sets url to new value.
  16765. * If html5 history api supported, pushState/replaceState is used, otherwise
  16766. * location.href/location.replace is used.
  16767. * Returns its own instance to allow chaining
  16768. *
  16769. * NOTE: this api is intended for use only by the $location service. Please use the
  16770. * {@link ng.$location $location service} to change url.
  16771. *
  16772. * @param {string} url New url (when used as setter)
  16773. * @param {boolean=} replace Should new url replace current history record?
  16774. * @param {object=} state object to use with pushState/replaceState
  16775. */
  16776. self.url = function(url, replace, state) {
  16777. // In modern browsers `history.state` is `null` by default; treating it separately
  16778. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  16779. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  16780. if (isUndefined(state)) {
  16781. state = null;
  16782. }
  16783. // Android Browser BFCache causes location, history reference to become stale.
  16784. if (location !== window.location) location = window.location;
  16785. if (history !== window.history) history = window.history;
  16786. // setter
  16787. if (url) {
  16788. var sameState = lastHistoryState === state;
  16789. // Don't change anything if previous and current URLs and states match. This also prevents
  16790. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  16791. // See https://github.com/angular/angular.js/commit/ffb2701
  16792. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  16793. return self;
  16794. }
  16795. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  16796. lastBrowserUrl = url;
  16797. lastHistoryState = state;
  16798. // Don't use history API if only the hash changed
  16799. // due to a bug in IE10/IE11 which leads
  16800. // to not firing a `hashchange` nor `popstate` event
  16801. // in some cases (see #9143).
  16802. if ($sniffer.history && (!sameBase || !sameState)) {
  16803. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  16804. cacheState();
  16805. // Do the assignment again so that those two variables are referentially identical.
  16806. lastHistoryState = cachedState;
  16807. } else {
  16808. if (!sameBase || pendingLocation) {
  16809. pendingLocation = url;
  16810. }
  16811. if (replace) {
  16812. location.replace(url);
  16813. } else if (!sameBase) {
  16814. location.href = url;
  16815. } else {
  16816. location.hash = getHash(url);
  16817. }
  16818. if (location.href !== url) {
  16819. pendingLocation = url;
  16820. }
  16821. }
  16822. return self;
  16823. // getter
  16824. } else {
  16825. // - pendingLocation is needed as browsers don't allow to read out
  16826. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  16827. // https://openradar.appspot.com/22186109).
  16828. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  16829. return pendingLocation || location.href.replace(/%27/g,"'");
  16830. }
  16831. };
  16832. /**
  16833. * @name $browser#state
  16834. *
  16835. * @description
  16836. * This method is a getter.
  16837. *
  16838. * Return history.state or null if history.state is undefined.
  16839. *
  16840. * @returns {object} state
  16841. */
  16842. self.state = function() {
  16843. return cachedState;
  16844. };
  16845. var urlChangeListeners = [],
  16846. urlChangeInit = false;
  16847. function cacheStateAndFireUrlChange() {
  16848. pendingLocation = null;
  16849. cacheState();
  16850. fireUrlChange();
  16851. }
  16852. // This variable should be used *only* inside the cacheState function.
  16853. var lastCachedState = null;
  16854. function cacheState() {
  16855. // This should be the only place in $browser where `history.state` is read.
  16856. cachedState = getCurrentState();
  16857. cachedState = isUndefined(cachedState) ? null : cachedState;
  16858. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  16859. if (equals(cachedState, lastCachedState)) {
  16860. cachedState = lastCachedState;
  16861. }
  16862. lastCachedState = cachedState;
  16863. }
  16864. function fireUrlChange() {
  16865. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  16866. return;
  16867. }
  16868. lastBrowserUrl = self.url();
  16869. lastHistoryState = cachedState;
  16870. forEach(urlChangeListeners, function(listener) {
  16871. listener(self.url(), cachedState);
  16872. });
  16873. }
  16874. /**
  16875. * @name $browser#onUrlChange
  16876. *
  16877. * @description
  16878. * Register callback function that will be called, when url changes.
  16879. *
  16880. * It's only called when the url is changed from outside of angular:
  16881. * - user types different url into address bar
  16882. * - user clicks on history (forward/back) button
  16883. * - user clicks on a link
  16884. *
  16885. * It's not called when url is changed by $browser.url() method
  16886. *
  16887. * The listener gets called with new url as parameter.
  16888. *
  16889. * NOTE: this api is intended for use only by the $location service. Please use the
  16890. * {@link ng.$location $location service} to monitor url changes in angular apps.
  16891. *
  16892. * @param {function(string)} listener Listener function to be called when url changes.
  16893. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  16894. */
  16895. self.onUrlChange = function(callback) {
  16896. // TODO(vojta): refactor to use node's syntax for events
  16897. if (!urlChangeInit) {
  16898. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  16899. // don't fire popstate when user change the address bar and don't fire hashchange when url
  16900. // changed by push/replaceState
  16901. // html5 history api - popstate event
  16902. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  16903. // hashchange event
  16904. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  16905. urlChangeInit = true;
  16906. }
  16907. urlChangeListeners.push(callback);
  16908. return callback;
  16909. };
  16910. /**
  16911. * @private
  16912. * Remove popstate and hashchange handler from window.
  16913. *
  16914. * NOTE: this api is intended for use only by $rootScope.
  16915. */
  16916. self.$$applicationDestroyed = function() {
  16917. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  16918. };
  16919. /**
  16920. * Checks whether the url has changed outside of Angular.
  16921. * Needs to be exported to be able to check for changes that have been done in sync,
  16922. * as hashchange/popstate events fire in async.
  16923. */
  16924. self.$$checkUrlChange = fireUrlChange;
  16925. //////////////////////////////////////////////////////////////
  16926. // Misc API
  16927. //////////////////////////////////////////////////////////////
  16928. /**
  16929. * @name $browser#baseHref
  16930. *
  16931. * @description
  16932. * Returns current <base href>
  16933. * (always relative - without domain)
  16934. *
  16935. * @returns {string} The current base href
  16936. */
  16937. self.baseHref = function() {
  16938. var href = baseElement.attr('href');
  16939. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  16940. };
  16941. /**
  16942. * @name $browser#defer
  16943. * @param {function()} fn A function, who's execution should be deferred.
  16944. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  16945. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  16946. *
  16947. * @description
  16948. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  16949. *
  16950. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  16951. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  16952. * via `$browser.defer.flush()`.
  16953. *
  16954. */
  16955. self.defer = function(fn, delay) {
  16956. var timeoutId;
  16957. outstandingRequestCount++;
  16958. timeoutId = setTimeout(function() {
  16959. delete pendingDeferIds[timeoutId];
  16960. completeOutstandingRequest(fn);
  16961. }, delay || 0);
  16962. pendingDeferIds[timeoutId] = true;
  16963. return timeoutId;
  16964. };
  16965. /**
  16966. * @name $browser#defer.cancel
  16967. *
  16968. * @description
  16969. * Cancels a deferred task identified with `deferId`.
  16970. *
  16971. * @param {*} deferId Token returned by the `$browser.defer` function.
  16972. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16973. * canceled.
  16974. */
  16975. self.defer.cancel = function(deferId) {
  16976. if (pendingDeferIds[deferId]) {
  16977. delete pendingDeferIds[deferId];
  16978. clearTimeout(deferId);
  16979. completeOutstandingRequest(noop);
  16980. return true;
  16981. }
  16982. return false;
  16983. };
  16984. }
  16985. function $BrowserProvider() {
  16986. this.$get = ['$window', '$log', '$sniffer', '$document',
  16987. function($window, $log, $sniffer, $document) {
  16988. return new Browser($window, $document, $log, $sniffer);
  16989. }];
  16990. }
  16991. /**
  16992. * @ngdoc service
  16993. * @name $cacheFactory
  16994. *
  16995. * @description
  16996. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  16997. * them.
  16998. *
  16999. * ```js
  17000. *
  17001. * var cache = $cacheFactory('cacheId');
  17002. * expect($cacheFactory.get('cacheId')).toBe(cache);
  17003. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  17004. *
  17005. * cache.put("key", "value");
  17006. * cache.put("another key", "another value");
  17007. *
  17008. * // We've specified no options on creation
  17009. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  17010. *
  17011. * ```
  17012. *
  17013. *
  17014. * @param {string} cacheId Name or id of the newly created cache.
  17015. * @param {object=} options Options object that specifies the cache behavior. Properties:
  17016. *
  17017. * - `{number=}` `capacity` — turns the cache into LRU cache.
  17018. *
  17019. * @returns {object} Newly created cache object with the following set of methods:
  17020. *
  17021. * - `{object}` `info()` — Returns id, size, and options of cache.
  17022. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  17023. * it.
  17024. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  17025. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  17026. * - `{void}` `removeAll()` — Removes all cached values.
  17027. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  17028. *
  17029. * @example
  17030. <example module="cacheExampleApp">
  17031. <file name="index.html">
  17032. <div ng-controller="CacheController">
  17033. <input ng-model="newCacheKey" placeholder="Key">
  17034. <input ng-model="newCacheValue" placeholder="Value">
  17035. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  17036. <p ng-if="keys.length">Cached Values</p>
  17037. <div ng-repeat="key in keys">
  17038. <span ng-bind="key"></span>
  17039. <span>: </span>
  17040. <b ng-bind="cache.get(key)"></b>
  17041. </div>
  17042. <p>Cache Info</p>
  17043. <div ng-repeat="(key, value) in cache.info()">
  17044. <span ng-bind="key"></span>
  17045. <span>: </span>
  17046. <b ng-bind="value"></b>
  17047. </div>
  17048. </div>
  17049. </file>
  17050. <file name="script.js">
  17051. angular.module('cacheExampleApp', []).
  17052. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  17053. $scope.keys = [];
  17054. $scope.cache = $cacheFactory('cacheId');
  17055. $scope.put = function(key, value) {
  17056. if (angular.isUndefined($scope.cache.get(key))) {
  17057. $scope.keys.push(key);
  17058. }
  17059. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  17060. };
  17061. }]);
  17062. </file>
  17063. <file name="style.css">
  17064. p {
  17065. margin: 10px 0 3px;
  17066. }
  17067. </file>
  17068. </example>
  17069. */
  17070. function $CacheFactoryProvider() {
  17071. this.$get = function() {
  17072. var caches = {};
  17073. function cacheFactory(cacheId, options) {
  17074. if (cacheId in caches) {
  17075. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  17076. }
  17077. var size = 0,
  17078. stats = extend({}, options, {id: cacheId}),
  17079. data = createMap(),
  17080. capacity = (options && options.capacity) || Number.MAX_VALUE,
  17081. lruHash = createMap(),
  17082. freshEnd = null,
  17083. staleEnd = null;
  17084. /**
  17085. * @ngdoc type
  17086. * @name $cacheFactory.Cache
  17087. *
  17088. * @description
  17089. * A cache object used to store and retrieve data, primarily used by
  17090. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  17091. * templates and other data.
  17092. *
  17093. * ```js
  17094. * angular.module('superCache')
  17095. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  17096. * return $cacheFactory('super-cache');
  17097. * }]);
  17098. * ```
  17099. *
  17100. * Example test:
  17101. *
  17102. * ```js
  17103. * it('should behave like a cache', inject(function(superCache) {
  17104. * superCache.put('key', 'value');
  17105. * superCache.put('another key', 'another value');
  17106. *
  17107. * expect(superCache.info()).toEqual({
  17108. * id: 'super-cache',
  17109. * size: 2
  17110. * });
  17111. *
  17112. * superCache.remove('another key');
  17113. * expect(superCache.get('another key')).toBeUndefined();
  17114. *
  17115. * superCache.removeAll();
  17116. * expect(superCache.info()).toEqual({
  17117. * id: 'super-cache',
  17118. * size: 0
  17119. * });
  17120. * }));
  17121. * ```
  17122. */
  17123. return caches[cacheId] = {
  17124. /**
  17125. * @ngdoc method
  17126. * @name $cacheFactory.Cache#put
  17127. * @kind function
  17128. *
  17129. * @description
  17130. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  17131. * retrieved later, and incrementing the size of the cache if the key was not already
  17132. * present in the cache. If behaving like an LRU cache, it will also remove stale
  17133. * entries from the set.
  17134. *
  17135. * It will not insert undefined values into the cache.
  17136. *
  17137. * @param {string} key the key under which the cached data is stored.
  17138. * @param {*} value the value to store alongside the key. If it is undefined, the key
  17139. * will not be stored.
  17140. * @returns {*} the value stored.
  17141. */
  17142. put: function(key, value) {
  17143. if (isUndefined(value)) return;
  17144. if (capacity < Number.MAX_VALUE) {
  17145. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  17146. refresh(lruEntry);
  17147. }
  17148. if (!(key in data)) size++;
  17149. data[key] = value;
  17150. if (size > capacity) {
  17151. this.remove(staleEnd.key);
  17152. }
  17153. return value;
  17154. },
  17155. /**
  17156. * @ngdoc method
  17157. * @name $cacheFactory.Cache#get
  17158. * @kind function
  17159. *
  17160. * @description
  17161. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  17162. *
  17163. * @param {string} key the key of the data to be retrieved
  17164. * @returns {*} the value stored.
  17165. */
  17166. get: function(key) {
  17167. if (capacity < Number.MAX_VALUE) {
  17168. var lruEntry = lruHash[key];
  17169. if (!lruEntry) return;
  17170. refresh(lruEntry);
  17171. }
  17172. return data[key];
  17173. },
  17174. /**
  17175. * @ngdoc method
  17176. * @name $cacheFactory.Cache#remove
  17177. * @kind function
  17178. *
  17179. * @description
  17180. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  17181. *
  17182. * @param {string} key the key of the entry to be removed
  17183. */
  17184. remove: function(key) {
  17185. if (capacity < Number.MAX_VALUE) {
  17186. var lruEntry = lruHash[key];
  17187. if (!lruEntry) return;
  17188. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  17189. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  17190. link(lruEntry.n,lruEntry.p);
  17191. delete lruHash[key];
  17192. }
  17193. if (!(key in data)) return;
  17194. delete data[key];
  17195. size--;
  17196. },
  17197. /**
  17198. * @ngdoc method
  17199. * @name $cacheFactory.Cache#removeAll
  17200. * @kind function
  17201. *
  17202. * @description
  17203. * Clears the cache object of any entries.
  17204. */
  17205. removeAll: function() {
  17206. data = createMap();
  17207. size = 0;
  17208. lruHash = createMap();
  17209. freshEnd = staleEnd = null;
  17210. },
  17211. /**
  17212. * @ngdoc method
  17213. * @name $cacheFactory.Cache#destroy
  17214. * @kind function
  17215. *
  17216. * @description
  17217. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  17218. * removing it from the {@link $cacheFactory $cacheFactory} set.
  17219. */
  17220. destroy: function() {
  17221. data = null;
  17222. stats = null;
  17223. lruHash = null;
  17224. delete caches[cacheId];
  17225. },
  17226. /**
  17227. * @ngdoc method
  17228. * @name $cacheFactory.Cache#info
  17229. * @kind function
  17230. *
  17231. * @description
  17232. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  17233. *
  17234. * @returns {object} an object with the following properties:
  17235. * <ul>
  17236. * <li>**id**: the id of the cache instance</li>
  17237. * <li>**size**: the number of entries kept in the cache instance</li>
  17238. * <li>**...**: any additional properties from the options object when creating the
  17239. * cache.</li>
  17240. * </ul>
  17241. */
  17242. info: function() {
  17243. return extend({}, stats, {size: size});
  17244. }
  17245. };
  17246. /**
  17247. * makes the `entry` the freshEnd of the LRU linked list
  17248. */
  17249. function refresh(entry) {
  17250. if (entry != freshEnd) {
  17251. if (!staleEnd) {
  17252. staleEnd = entry;
  17253. } else if (staleEnd == entry) {
  17254. staleEnd = entry.n;
  17255. }
  17256. link(entry.n, entry.p);
  17257. link(entry, freshEnd);
  17258. freshEnd = entry;
  17259. freshEnd.n = null;
  17260. }
  17261. }
  17262. /**
  17263. * bidirectionally links two entries of the LRU linked list
  17264. */
  17265. function link(nextEntry, prevEntry) {
  17266. if (nextEntry != prevEntry) {
  17267. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  17268. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  17269. }
  17270. }
  17271. }
  17272. /**
  17273. * @ngdoc method
  17274. * @name $cacheFactory#info
  17275. *
  17276. * @description
  17277. * Get information about all the caches that have been created
  17278. *
  17279. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  17280. */
  17281. cacheFactory.info = function() {
  17282. var info = {};
  17283. forEach(caches, function(cache, cacheId) {
  17284. info[cacheId] = cache.info();
  17285. });
  17286. return info;
  17287. };
  17288. /**
  17289. * @ngdoc method
  17290. * @name $cacheFactory#get
  17291. *
  17292. * @description
  17293. * Get access to a cache object by the `cacheId` used when it was created.
  17294. *
  17295. * @param {string} cacheId Name or id of a cache to access.
  17296. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  17297. */
  17298. cacheFactory.get = function(cacheId) {
  17299. return caches[cacheId];
  17300. };
  17301. return cacheFactory;
  17302. };
  17303. }
  17304. /**
  17305. * @ngdoc service
  17306. * @name $templateCache
  17307. *
  17308. * @description
  17309. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  17310. * can load templates directly into the cache in a `script` tag, or by consuming the
  17311. * `$templateCache` service directly.
  17312. *
  17313. * Adding via the `script` tag:
  17314. *
  17315. * ```html
  17316. * <script type="text/ng-template" id="templateId.html">
  17317. * <p>This is the content of the template</p>
  17318. * </script>
  17319. * ```
  17320. *
  17321. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  17322. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  17323. * element with ng-app attribute), otherwise the template will be ignored.
  17324. *
  17325. * Adding via the `$templateCache` service:
  17326. *
  17327. * ```js
  17328. * var myApp = angular.module('myApp', []);
  17329. * myApp.run(function($templateCache) {
  17330. * $templateCache.put('templateId.html', 'This is the content of the template');
  17331. * });
  17332. * ```
  17333. *
  17334. * To retrieve the template later, simply use it in your HTML:
  17335. * ```html
  17336. * <div ng-include=" 'templateId.html' "></div>
  17337. * ```
  17338. *
  17339. * or get it via Javascript:
  17340. * ```js
  17341. * $templateCache.get('templateId.html')
  17342. * ```
  17343. *
  17344. * See {@link ng.$cacheFactory $cacheFactory}.
  17345. *
  17346. */
  17347. function $TemplateCacheProvider() {
  17348. this.$get = ['$cacheFactory', function($cacheFactory) {
  17349. return $cacheFactory('templates');
  17350. }];
  17351. }
  17352. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  17353. * Any commits to this file should be reviewed with security in mind. *
  17354. * Changes to this file can potentially create security vulnerabilities. *
  17355. * An approval from 2 Core members with history of modifying *
  17356. * this file is required. *
  17357. * *
  17358. * Does the change somehow allow for arbitrary javascript to be executed? *
  17359. * Or allows for someone to change the prototype of built-in objects? *
  17360. * Or gives undesired access to variables likes document or window? *
  17361. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  17362. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  17363. *
  17364. * DOM-related variables:
  17365. *
  17366. * - "node" - DOM Node
  17367. * - "element" - DOM Element or Node
  17368. * - "$node" or "$element" - jqLite-wrapped node or element
  17369. *
  17370. *
  17371. * Compiler related stuff:
  17372. *
  17373. * - "linkFn" - linking fn of a single directive
  17374. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  17375. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  17376. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  17377. */
  17378. /**
  17379. * @ngdoc service
  17380. * @name $compile
  17381. * @kind function
  17382. *
  17383. * @description
  17384. * Compiles an HTML string or DOM into a template and produces a template function, which
  17385. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  17386. *
  17387. * The compilation is a process of walking the DOM tree and matching DOM elements to
  17388. * {@link ng.$compileProvider#directive directives}.
  17389. *
  17390. * <div class="alert alert-warning">
  17391. * **Note:** This document is an in-depth reference of all directive options.
  17392. * For a gentle introduction to directives with examples of common use cases,
  17393. * see the {@link guide/directive directive guide}.
  17394. * </div>
  17395. *
  17396. * ## Comprehensive Directive API
  17397. *
  17398. * There are many different options for a directive.
  17399. *
  17400. * The difference resides in the return value of the factory function.
  17401. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  17402. * or just the `postLink` function (all other properties will have the default values).
  17403. *
  17404. * <div class="alert alert-success">
  17405. * **Best Practice:** It's recommended to use the "directive definition object" form.
  17406. * </div>
  17407. *
  17408. * Here's an example directive declared with a Directive Definition Object:
  17409. *
  17410. * ```js
  17411. * var myModule = angular.module(...);
  17412. *
  17413. * myModule.directive('directiveName', function factory(injectables) {
  17414. * var directiveDefinitionObject = {
  17415. * priority: 0,
  17416. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  17417. * // or
  17418. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  17419. * transclude: false,
  17420. * restrict: 'A',
  17421. * templateNamespace: 'html',
  17422. * scope: false,
  17423. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  17424. * controllerAs: 'stringIdentifier',
  17425. * bindToController: false,
  17426. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  17427. * compile: function compile(tElement, tAttrs, transclude) {
  17428. * return {
  17429. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  17430. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  17431. * }
  17432. * // or
  17433. * // return function postLink( ... ) { ... }
  17434. * },
  17435. * // or
  17436. * // link: {
  17437. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  17438. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  17439. * // }
  17440. * // or
  17441. * // link: function postLink( ... ) { ... }
  17442. * };
  17443. * return directiveDefinitionObject;
  17444. * });
  17445. * ```
  17446. *
  17447. * <div class="alert alert-warning">
  17448. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  17449. * </div>
  17450. *
  17451. * Therefore the above can be simplified as:
  17452. *
  17453. * ```js
  17454. * var myModule = angular.module(...);
  17455. *
  17456. * myModule.directive('directiveName', function factory(injectables) {
  17457. * var directiveDefinitionObject = {
  17458. * link: function postLink(scope, iElement, iAttrs) { ... }
  17459. * };
  17460. * return directiveDefinitionObject;
  17461. * // or
  17462. * // return function postLink(scope, iElement, iAttrs) { ... }
  17463. * });
  17464. * ```
  17465. *
  17466. *
  17467. *
  17468. * ### Directive Definition Object
  17469. *
  17470. * The directive definition object provides instructions to the {@link ng.$compile
  17471. * compiler}. The attributes are:
  17472. *
  17473. * #### `multiElement`
  17474. * When this property is set to true, the HTML compiler will collect DOM nodes between
  17475. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  17476. * together as the directive elements. It is recommended that this feature be used on directives
  17477. * which are not strictly behavioral (such as {@link ngClick}), and which
  17478. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  17479. *
  17480. * #### `priority`
  17481. * When there are multiple directives defined on a single DOM element, sometimes it
  17482. * is necessary to specify the order in which the directives are applied. The `priority` is used
  17483. * to sort the directives before their `compile` functions get called. Priority is defined as a
  17484. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  17485. * are also run in priority order, but post-link functions are run in reverse order. The order
  17486. * of directives with the same priority is undefined. The default priority is `0`.
  17487. *
  17488. * #### `terminal`
  17489. * If set to true then the current `priority` will be the last set of directives
  17490. * which will execute (any directives at the current priority will still execute
  17491. * as the order of execution on same `priority` is undefined). Note that expressions
  17492. * and other directives used in the directive's template will also be excluded from execution.
  17493. *
  17494. * #### `scope`
  17495. * The scope property can be `true`, an object or a falsy value:
  17496. *
  17497. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  17498. *
  17499. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  17500. * the directive's element. If multiple directives on the same element request a new scope,
  17501. * only one new scope is created. The new scope rule does not apply for the root of the template
  17502. * since the root of the template always gets a new scope.
  17503. *
  17504. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  17505. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  17506. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  17507. * data in the parent scope.
  17508. *
  17509. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  17510. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  17511. * the object hash map to the name of the property on the isolate scope; the values define how the property
  17512. * is bound to the parent scope, via matching attributes on the directive's element:
  17513. *
  17514. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  17515. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  17516. * attribute name is assumed to be the same as the local name. Given `<my-component
  17517. * my-attr="hello {{name}}">` and the isolate scope definition `scope: { localName:'@myAttr' }`,
  17518. * the directive's scope property `localName` will reflect the interpolated value of `hello
  17519. * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's
  17520. * scope. The `name` is read from the parent scope (not the directive's scope).
  17521. *
  17522. * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression
  17523. * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope.
  17524. * If no `attr` name is specified then the attribute name is assumed to be the same as the local
  17525. * name. Given `<my-component my-attr="parentModel">` and the isolate scope definition `scope: {
  17526. * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the
  17527. * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in
  17528. * `localModel` and vice versa. Optional attributes should be marked as such with a question mark:
  17529. * `=?` or `=?attr`. If the binding expression is non-assignable, or if the attribute isn't
  17530. * optional and doesn't exist, an exception ({@link error/$compile/nonassign `$compile:nonassign`})
  17531. * will be thrown upon discovering changes to the local value, since it will be impossible to sync
  17532. * them back to the parent scope. By default, the {@link ng.$rootScope.Scope#$watch `$watch`}
  17533. * method is used for tracking changes, and the equality check is based on object identity.
  17534. * However, if an object literal or an array literal is passed as the binding expression, the
  17535. * equality check is done by value (using the {@link angular.equals} function). It's also possible
  17536. * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection
  17537. * `$watchCollection`}: use `=*` or `=*attr` (`=*?` or `=*?attr` if the attribute is optional).
  17538. *
  17539. * * `<` or `<attr` - set up a one-way (one-directional) binding between a local scope property and an
  17540. * expression passed via the attribute `attr`. The expression is evaluated in the context of the
  17541. * parent scope. If no `attr` name is specified then the attribute name is assumed to be the same as the
  17542. * local name. You can also make the binding optional by adding `?`: `<?` or `<?attr`.
  17543. *
  17544. * For example, given `<my-component my-attr="parentModel">` and directive definition of
  17545. * `scope: { localModel:'<myAttr' }`, then the isolated scope property `localModel` will reflect the
  17546. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  17547. * in `localModel`, but changes in `localModel` will not reflect in `parentModel`. There are however
  17548. * two caveats:
  17549. * 1. one-way binding does not copy the value from the parent to the isolate scope, it simply
  17550. * sets the same value. That means if your bound value is an object, changes to its properties
  17551. * in the isolated scope will be reflected in the parent scope (because both reference the same object).
  17552. * 2. one-way binding watches changes to the **identity** of the parent value. That means the
  17553. * {@link ng.$rootScope.Scope#$watch `$watch`} on the parent value only fires if the reference
  17554. * to the value has changed. In most cases, this should not be of concern, but can be important
  17555. * to know if you one-way bind to an object, and then replace that object in the isolated scope.
  17556. * If you now change a property of the object in your parent scope, the change will not be
  17557. * propagated to the isolated scope, because the identity of the object on the parent scope
  17558. * has not changed. Instead you must assign a new object.
  17559. *
  17560. * One-way binding is useful if you do not plan to propagate changes to your isolated scope bindings
  17561. * back to the parent. However, it does not make this completely impossible.
  17562. *
  17563. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. If
  17564. * no `attr` name is specified then the attribute name is assumed to be the same as the local name.
  17565. * Given `<my-component my-attr="count = count + value">` and the isolate scope definition `scope: {
  17566. * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for
  17567. * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope
  17568. * via an expression to the parent scope. This can be done by passing a map of local variable names
  17569. * and values into the expression wrapper fn. For example, if the expression is `increment(amount)`
  17570. * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`.
  17571. *
  17572. * In general it's possible to apply more than one directive to one element, but there might be limitations
  17573. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  17574. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  17575. *
  17576. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  17577. * * **child scope** + **no scope** => Both directives will share one single child scope
  17578. * * **child scope** + **child scope** => Both directives will share one single child scope
  17579. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  17580. * its parent's scope
  17581. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  17582. * be applied to the same element.
  17583. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  17584. * cannot be applied to the same element.
  17585. *
  17586. *
  17587. * #### `bindToController`
  17588. * This property is used to bind scope properties directly to the controller. It can be either
  17589. * `true` or an object hash with the same format as the `scope` property. Additionally, a controller
  17590. * alias must be set, either by using `controllerAs: 'myAlias'` or by specifying the alias in the controller
  17591. * definition: `controller: 'myCtrl as myAlias'`.
  17592. *
  17593. * When an isolate scope is used for a directive (see above), `bindToController: true` will
  17594. * allow a component to have its properties bound to the controller, rather than to scope.
  17595. *
  17596. * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller
  17597. * properties. You can access these bindings once they have been initialized by providing a controller method called
  17598. * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings
  17599. * initialized.
  17600. *
  17601. * <div class="alert alert-warning">
  17602. * **Deprecation warning:** although bindings for non-ES6 class controllers are currently
  17603. * bound to `this` before the controller constructor is called, this use is now deprecated. Please place initialization
  17604. * code that relies upon bindings inside a `$onInit` method on the controller, instead.
  17605. * </div>
  17606. *
  17607. * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property.
  17608. * This will set up the scope bindings to the controller directly. Note that `scope` can still be used
  17609. * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate
  17610. * scope (useful for component directives).
  17611. *
  17612. * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`.
  17613. *
  17614. *
  17615. * #### `controller`
  17616. * Controller constructor function. The controller is instantiated before the
  17617. * pre-linking phase and can be accessed by other directives (see
  17618. * `require` attribute). This allows the directives to communicate with each other and augment
  17619. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  17620. *
  17621. * * `$scope` - Current scope associated with the element
  17622. * * `$element` - Current element
  17623. * * `$attrs` - Current attributes object for the element
  17624. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  17625. * `function([scope], cloneLinkingFn, futureParentElement, slotName)`:
  17626. * * `scope`: (optional) override the scope.
  17627. * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content.
  17628. * * `futureParentElement` (optional):
  17629. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  17630. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  17631. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  17632. * and when the `cloneLinkinFn` is passed,
  17633. * as those elements need to created and cloned in a special way when they are defined outside their
  17634. * usual containers (e.g. like `<svg>`).
  17635. * * See also the `directive.templateNamespace` property.
  17636. * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`)
  17637. * then the default translusion is provided.
  17638. * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns
  17639. * `true` if the specified slot contains content (i.e. one or more DOM nodes).
  17640. *
  17641. * The controller can provide the following methods that act as life-cycle hooks:
  17642. * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and
  17643. * had their bindings initialized (and before the pre &amp; post linking functions for the directives on
  17644. * this element). This is a good place to put initialization code for your controller.
  17645. * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The
  17646. * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an
  17647. * object of the form `{ currentValue: ..., previousValue: ... }`. Use this hook to trigger updates within a component
  17648. * such as cloning the bound value to prevent accidental mutation of the outer value.
  17649. * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing
  17650. * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in
  17651. * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent
  17652. * components will have their `$onDestroy()` hook called before child components.
  17653. * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link
  17654. * function this hook can be used to set up DOM event handlers and do direct DOM manipulation.
  17655. * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since
  17656. * they are waiting for their template to load asynchronously and their own compilation and linking has been
  17657. * suspended until that occurs.
  17658. *
  17659. *
  17660. * #### `require`
  17661. * Require another directive and inject its controller as the fourth argument to the linking function. The
  17662. * `require` property can be a string, an array or an object:
  17663. * * a **string** containing the name of the directive to pass to the linking function
  17664. * * an **array** containing the names of directives to pass to the linking function. The argument passed to the
  17665. * linking function will be an array of controllers in the same order as the names in the `require` property
  17666. * * an **object** whose property values are the names of the directives to pass to the linking function. The argument
  17667. * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding
  17668. * controllers.
  17669. *
  17670. * If the `require` property is an object and `bindToController` is truthy, then the required controllers are
  17671. * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers
  17672. * have been constructed but before `$onInit` is called.
  17673. * See the {@link $compileProvider#component} helper for an example of how this can be used.
  17674. *
  17675. * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is
  17676. * raised (unless no link function is specified and the required controllers are not being bound to the directive
  17677. * controller, in which case error checking is skipped). The name can be prefixed with:
  17678. *
  17679. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  17680. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  17681. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  17682. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  17683. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  17684. * `null` to the `link` fn if not found.
  17685. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  17686. * `null` to the `link` fn if not found.
  17687. *
  17688. *
  17689. * #### `controllerAs`
  17690. * Identifier name for a reference to the controller in the directive's scope.
  17691. * This allows the controller to be referenced from the directive template. This is especially
  17692. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  17693. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  17694. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  17695. *
  17696. *
  17697. * #### `restrict`
  17698. * String of subset of `EACM` which restricts the directive to a specific directive
  17699. * declaration style. If omitted, the defaults (elements and attributes) are used.
  17700. *
  17701. * * `E` - Element name (default): `<my-directive></my-directive>`
  17702. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  17703. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  17704. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  17705. *
  17706. *
  17707. * #### `templateNamespace`
  17708. * String representing the document type used by the markup in the template.
  17709. * AngularJS needs this information as those elements need to be created and cloned
  17710. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  17711. *
  17712. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  17713. * top-level elements such as `<svg>` or `<math>`.
  17714. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  17715. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  17716. *
  17717. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  17718. *
  17719. * #### `template`
  17720. * HTML markup that may:
  17721. * * Replace the contents of the directive's element (default).
  17722. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  17723. * * Wrap the contents of the directive's element (if `transclude` is true).
  17724. *
  17725. * Value may be:
  17726. *
  17727. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  17728. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  17729. * function api below) and returns a string value.
  17730. *
  17731. *
  17732. * #### `templateUrl`
  17733. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  17734. *
  17735. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  17736. * for later when the template has been resolved. In the meantime it will continue to compile and link
  17737. * sibling and parent elements as though this element had not contained any directives.
  17738. *
  17739. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  17740. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  17741. * case when only one deeply nested directive has `templateUrl`.
  17742. *
  17743. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  17744. *
  17745. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  17746. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  17747. * a string value representing the url. In either case, the template URL is passed through {@link
  17748. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  17749. *
  17750. *
  17751. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  17752. * specify what the template should replace. Defaults to `false`.
  17753. *
  17754. * * `true` - the template will replace the directive's element.
  17755. * * `false` - the template will replace the contents of the directive's element.
  17756. *
  17757. * The replacement process migrates all of the attributes / classes from the old element to the new
  17758. * one. See the {@link guide/directive#template-expanding-directive
  17759. * Directives Guide} for an example.
  17760. *
  17761. * There are very few scenarios where element replacement is required for the application function,
  17762. * the main one being reusable custom components that are used within SVG contexts
  17763. * (because SVG doesn't work with custom elements in the DOM tree).
  17764. *
  17765. * #### `transclude`
  17766. * Extract the contents of the element where the directive appears and make it available to the directive.
  17767. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  17768. * {@link $compile#transclusion Transclusion} section below.
  17769. *
  17770. *
  17771. * #### `compile`
  17772. *
  17773. * ```js
  17774. * function compile(tElement, tAttrs, transclude) { ... }
  17775. * ```
  17776. *
  17777. * The compile function deals with transforming the template DOM. Since most directives do not do
  17778. * template transformation, it is not used often. The compile function takes the following arguments:
  17779. *
  17780. * * `tElement` - template element - The element where the directive has been declared. It is
  17781. * safe to do template transformation on the element and child elements only.
  17782. *
  17783. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  17784. * between all directive compile functions.
  17785. *
  17786. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  17787. *
  17788. * <div class="alert alert-warning">
  17789. * **Note:** The template instance and the link instance may be different objects if the template has
  17790. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  17791. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  17792. * should be done in a linking function rather than in a compile function.
  17793. * </div>
  17794. * <div class="alert alert-warning">
  17795. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  17796. * own templates or compile functions. Compiling these directives results in an infinite loop and
  17797. * stack overflow errors.
  17798. *
  17799. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  17800. * a directive's template instead of relying on automatic template compilation via `template` or
  17801. * `templateUrl` declaration or manual compilation inside the compile function.
  17802. * </div>
  17803. *
  17804. * <div class="alert alert-danger">
  17805. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  17806. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  17807. * to the link function instead.
  17808. * </div>
  17809. * A compile function can have a return value which can be either a function or an object.
  17810. *
  17811. * * returning a (post-link) function - is equivalent to registering the linking function via the
  17812. * `link` property of the config object when the compile function is empty.
  17813. *
  17814. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  17815. * control when a linking function should be called during the linking phase. See info about
  17816. * pre-linking and post-linking functions below.
  17817. *
  17818. *
  17819. * #### `link`
  17820. * This property is used only if the `compile` property is not defined.
  17821. *
  17822. * ```js
  17823. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  17824. * ```
  17825. *
  17826. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  17827. * executed after the template has been cloned. This is where most of the directive logic will be
  17828. * put.
  17829. *
  17830. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  17831. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  17832. *
  17833. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  17834. * manipulate the children of the element only in `postLink` function since the children have
  17835. * already been linked.
  17836. *
  17837. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  17838. * between all directive linking functions.
  17839. *
  17840. * * `controller` - the directive's required controller instance(s) - Instances are shared
  17841. * among all directives, which allows the directives to use the controllers as a communication
  17842. * channel. The exact value depends on the directive's `require` property:
  17843. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  17844. * * `string`: the controller instance
  17845. * * `array`: array of controller instances
  17846. *
  17847. * If a required controller cannot be found, and it is optional, the instance is `null`,
  17848. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  17849. *
  17850. * Note that you can also require the directive's own controller - it will be made available like
  17851. * any other controller.
  17852. *
  17853. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  17854. * This is the same as the `$transclude`
  17855. * parameter of directive controllers, see there for details.
  17856. * `function([scope], cloneLinkingFn, futureParentElement)`.
  17857. *
  17858. * #### Pre-linking function
  17859. *
  17860. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  17861. * compiler linking function will fail to locate the correct elements for linking.
  17862. *
  17863. * #### Post-linking function
  17864. *
  17865. * Executed after the child elements are linked.
  17866. *
  17867. * Note that child elements that contain `templateUrl` directives will not have been compiled
  17868. * and linked since they are waiting for their template to load asynchronously and their own
  17869. * compilation and linking has been suspended until that occurs.
  17870. *
  17871. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  17872. * for their async templates to be resolved.
  17873. *
  17874. *
  17875. * ### Transclusion
  17876. *
  17877. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  17878. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  17879. * scope from where they were taken.
  17880. *
  17881. * Transclusion is used (often with {@link ngTransclude}) to insert the
  17882. * original contents of a directive's element into a specified place in the template of the directive.
  17883. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  17884. * content has access to the properties on the scope from which it was taken, even if the directive
  17885. * has isolated scope.
  17886. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  17887. *
  17888. * This makes it possible for the widget to have private state for its template, while the transcluded
  17889. * content has access to its originating scope.
  17890. *
  17891. * <div class="alert alert-warning">
  17892. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  17893. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  17894. * Testing Transclusion Directives}.
  17895. * </div>
  17896. *
  17897. * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the
  17898. * directive's element, the entire element or multiple parts of the element contents:
  17899. *
  17900. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  17901. * * `'element'` - transclude the whole of the directive's element including any directives on this
  17902. * element that defined at a lower priority than this directive. When used, the `template`
  17903. * property is ignored.
  17904. * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template.
  17905. *
  17906. * **Mult-slot transclusion** is declared by providing an object for the `transclude` property.
  17907. *
  17908. * This object is a map where the keys are the name of the slot to fill and the value is an element selector
  17909. * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`)
  17910. * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc).
  17911. *
  17912. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  17913. *
  17914. * If the element selector is prefixed with a `?` then that slot is optional.
  17915. *
  17916. * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `<my-custom-element>` elements to
  17917. * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive.
  17918. *
  17919. * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements
  17920. * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call
  17921. * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and
  17922. * injectable into the directive's controller.
  17923. *
  17924. *
  17925. * #### Transclusion Functions
  17926. *
  17927. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  17928. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  17929. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  17930. *
  17931. * <div class="alert alert-info">
  17932. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  17933. * ngTransclude will deal with it for us.
  17934. * </div>
  17935. *
  17936. * If you want to manually control the insertion and removal of the transcluded content in your directive
  17937. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  17938. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  17939. *
  17940. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  17941. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  17942. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  17943. *
  17944. * <div class="alert alert-info">
  17945. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function
  17946. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  17947. * </div>
  17948. *
  17949. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  17950. * attach function**:
  17951. *
  17952. * ```js
  17953. * var transcludedContent, transclusionScope;
  17954. *
  17955. * $transclude(function(clone, scope) {
  17956. * element.append(clone);
  17957. * transcludedContent = clone;
  17958. * transclusionScope = scope;
  17959. * });
  17960. * ```
  17961. *
  17962. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  17963. * associated transclusion scope:
  17964. *
  17965. * ```js
  17966. * transcludedContent.remove();
  17967. * transclusionScope.$destroy();
  17968. * ```
  17969. *
  17970. * <div class="alert alert-info">
  17971. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  17972. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  17973. * then you are also responsible for calling `$destroy` on the transclusion scope.
  17974. * </div>
  17975. *
  17976. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  17977. * automatically destroy their transcluded clones as necessary so you do not need to worry about this if
  17978. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  17979. *
  17980. *
  17981. * #### Transclusion Scopes
  17982. *
  17983. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  17984. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  17985. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  17986. * was taken.
  17987. *
  17988. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  17989. * like this:
  17990. *
  17991. * ```html
  17992. * <div ng-app>
  17993. * <div isolate>
  17994. * <div transclusion>
  17995. * </div>
  17996. * </div>
  17997. * </div>
  17998. * ```
  17999. *
  18000. * The `$parent` scope hierarchy will look like this:
  18001. *
  18002. ```
  18003. - $rootScope
  18004. - isolate
  18005. - transclusion
  18006. ```
  18007. *
  18008. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  18009. *
  18010. ```
  18011. - $rootScope
  18012. - transclusion
  18013. - isolate
  18014. ```
  18015. *
  18016. *
  18017. * ### Attributes
  18018. *
  18019. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  18020. * `link()` or `compile()` functions. It has a variety of uses.
  18021. *
  18022. * * *Accessing normalized attribute names:* Directives like 'ngBind' can be expressed in many ways:
  18023. * 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. The attributes object allows for normalized access
  18024. * to the attributes.
  18025. *
  18026. * * *Directive inter-communication:* All directives share the same instance of the attributes
  18027. * object which allows the directives to use the attributes object as inter directive
  18028. * communication.
  18029. *
  18030. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  18031. * allowing other directives to read the interpolated value.
  18032. *
  18033. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  18034. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  18035. * the only way to easily get the actual value because during the linking phase the interpolation
  18036. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  18037. *
  18038. * ```js
  18039. * function linkingFn(scope, elm, attrs, ctrl) {
  18040. * // get the attribute value
  18041. * console.log(attrs.ngModel);
  18042. *
  18043. * // change the attribute
  18044. * attrs.$set('ngModel', 'new value');
  18045. *
  18046. * // observe changes to interpolated attribute
  18047. * attrs.$observe('ngModel', function(value) {
  18048. * console.log('ngModel has changed value to ' + value);
  18049. * });
  18050. * }
  18051. * ```
  18052. *
  18053. * ## Example
  18054. *
  18055. * <div class="alert alert-warning">
  18056. * **Note**: Typically directives are registered with `module.directive`. The example below is
  18057. * to illustrate how `$compile` works.
  18058. * </div>
  18059. *
  18060. <example module="compileExample">
  18061. <file name="index.html">
  18062. <script>
  18063. angular.module('compileExample', [], function($compileProvider) {
  18064. // configure new 'compile' directive by passing a directive
  18065. // factory function. The factory function injects the '$compile'
  18066. $compileProvider.directive('compile', function($compile) {
  18067. // directive factory creates a link function
  18068. return function(scope, element, attrs) {
  18069. scope.$watch(
  18070. function(scope) {
  18071. // watch the 'compile' expression for changes
  18072. return scope.$eval(attrs.compile);
  18073. },
  18074. function(value) {
  18075. // when the 'compile' expression changes
  18076. // assign it into the current DOM
  18077. element.html(value);
  18078. // compile the new DOM and link it to the current
  18079. // scope.
  18080. // NOTE: we only compile .childNodes so that
  18081. // we don't get into infinite loop compiling ourselves
  18082. $compile(element.contents())(scope);
  18083. }
  18084. );
  18085. };
  18086. });
  18087. })
  18088. .controller('GreeterController', ['$scope', function($scope) {
  18089. $scope.name = 'Angular';
  18090. $scope.html = 'Hello {{name}}';
  18091. }]);
  18092. </script>
  18093. <div ng-controller="GreeterController">
  18094. <input ng-model="name"> <br/>
  18095. <textarea ng-model="html"></textarea> <br/>
  18096. <div compile="html"></div>
  18097. </div>
  18098. </file>
  18099. <file name="protractor.js" type="protractor">
  18100. it('should auto compile', function() {
  18101. var textarea = $('textarea');
  18102. var output = $('div[compile]');
  18103. // The initial state reads 'Hello Angular'.
  18104. expect(output.getText()).toBe('Hello Angular');
  18105. textarea.clear();
  18106. textarea.sendKeys('{{name}}!');
  18107. expect(output.getText()).toBe('Angular!');
  18108. });
  18109. </file>
  18110. </example>
  18111. *
  18112. *
  18113. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  18114. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  18115. *
  18116. * <div class="alert alert-danger">
  18117. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  18118. * e.g. will not use the right outer scope. Please pass the transclude function as a
  18119. * `parentBoundTranscludeFn` to the link function instead.
  18120. * </div>
  18121. *
  18122. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  18123. * root element(s), not their children)
  18124. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  18125. * (a DOM element/tree) to a scope. Where:
  18126. *
  18127. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  18128. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  18129. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  18130. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  18131. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  18132. *
  18133. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  18134. * * `scope` - is the current scope with which the linking function is working with.
  18135. *
  18136. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  18137. * keys may be used to control linking behavior:
  18138. *
  18139. * * `parentBoundTranscludeFn` - the transclude function made available to
  18140. * directives; if given, it will be passed through to the link functions of
  18141. * directives found in `element` during compilation.
  18142. * * `transcludeControllers` - an object hash with keys that map controller names
  18143. * to a hash with the key `instance`, which maps to the controller instance;
  18144. * if given, it will make the controllers available to directives on the compileNode:
  18145. * ```
  18146. * {
  18147. * parent: {
  18148. * instance: parentControllerInstance
  18149. * }
  18150. * }
  18151. * ```
  18152. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  18153. * the cloned elements; only needed for transcludes that are allowed to contain non html
  18154. * elements (e.g. SVG elements). See also the directive.controller property.
  18155. *
  18156. * Calling the linking function returns the element of the template. It is either the original
  18157. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  18158. *
  18159. * After linking the view is not updated until after a call to $digest which typically is done by
  18160. * Angular automatically.
  18161. *
  18162. * If you need access to the bound view, there are two ways to do it:
  18163. *
  18164. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  18165. * before you send them to the compiler and keep this reference around.
  18166. * ```js
  18167. * var element = $compile('<p>{{total}}</p>')(scope);
  18168. * ```
  18169. *
  18170. * - if on the other hand, you need the element to be cloned, the view reference from the original
  18171. * example would not point to the clone, but rather to the original template that was cloned. In
  18172. * this case, you can access the clone via the cloneAttachFn:
  18173. * ```js
  18174. * var templateElement = angular.element('<p>{{total}}</p>'),
  18175. * scope = ....;
  18176. *
  18177. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  18178. * //attach the clone to DOM document at the right place
  18179. * });
  18180. *
  18181. * //now we have reference to the cloned DOM via `clonedElement`
  18182. * ```
  18183. *
  18184. *
  18185. * For information on how the compiler works, see the
  18186. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  18187. */
  18188. var $compileMinErr = minErr('$compile');
  18189. /**
  18190. * @ngdoc provider
  18191. * @name $compileProvider
  18192. *
  18193. * @description
  18194. */
  18195. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  18196. function $CompileProvider($provide, $$sanitizeUriProvider) {
  18197. var hasDirectives = {},
  18198. Suffix = 'Directive',
  18199. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  18200. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  18201. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  18202. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  18203. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  18204. // The assumption is that future DOM event attribute names will begin with
  18205. // 'on' and be composed of only English letters.
  18206. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  18207. var bindingCache = createMap();
  18208. function parseIsolateBindings(scope, directiveName, isController) {
  18209. var LOCAL_REGEXP = /^\s*([@&<]|=(\*?))(\??)\s*(\w*)\s*$/;
  18210. var bindings = {};
  18211. forEach(scope, function(definition, scopeName) {
  18212. if (definition in bindingCache) {
  18213. bindings[scopeName] = bindingCache[definition];
  18214. return;
  18215. }
  18216. var match = definition.match(LOCAL_REGEXP);
  18217. if (!match) {
  18218. throw $compileMinErr('iscp',
  18219. "Invalid {3} for directive '{0}'." +
  18220. " Definition: {... {1}: '{2}' ...}",
  18221. directiveName, scopeName, definition,
  18222. (isController ? "controller bindings definition" :
  18223. "isolate scope definition"));
  18224. }
  18225. bindings[scopeName] = {
  18226. mode: match[1][0],
  18227. collection: match[2] === '*',
  18228. optional: match[3] === '?',
  18229. attrName: match[4] || scopeName
  18230. };
  18231. if (match[4]) {
  18232. bindingCache[definition] = bindings[scopeName];
  18233. }
  18234. });
  18235. return bindings;
  18236. }
  18237. function parseDirectiveBindings(directive, directiveName) {
  18238. var bindings = {
  18239. isolateScope: null,
  18240. bindToController: null
  18241. };
  18242. if (isObject(directive.scope)) {
  18243. if (directive.bindToController === true) {
  18244. bindings.bindToController = parseIsolateBindings(directive.scope,
  18245. directiveName, true);
  18246. bindings.isolateScope = {};
  18247. } else {
  18248. bindings.isolateScope = parseIsolateBindings(directive.scope,
  18249. directiveName, false);
  18250. }
  18251. }
  18252. if (isObject(directive.bindToController)) {
  18253. bindings.bindToController =
  18254. parseIsolateBindings(directive.bindToController, directiveName, true);
  18255. }
  18256. if (isObject(bindings.bindToController)) {
  18257. var controller = directive.controller;
  18258. var controllerAs = directive.controllerAs;
  18259. if (!controller) {
  18260. // There is no controller, there may or may not be a controllerAs property
  18261. throw $compileMinErr('noctrl',
  18262. "Cannot bind to controller without directive '{0}'s controller.",
  18263. directiveName);
  18264. } else if (!identifierForController(controller, controllerAs)) {
  18265. // There is a controller, but no identifier or controllerAs property
  18266. throw $compileMinErr('noident',
  18267. "Cannot bind to controller without identifier for directive '{0}'.",
  18268. directiveName);
  18269. }
  18270. }
  18271. return bindings;
  18272. }
  18273. function assertValidDirectiveName(name) {
  18274. var letter = name.charAt(0);
  18275. if (!letter || letter !== lowercase(letter)) {
  18276. throw $compileMinErr('baddir', "Directive/Component name '{0}' is invalid. The first character must be a lowercase letter", name);
  18277. }
  18278. if (name !== name.trim()) {
  18279. throw $compileMinErr('baddir',
  18280. "Directive/Component name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  18281. name);
  18282. }
  18283. }
  18284. /**
  18285. * @ngdoc method
  18286. * @name $compileProvider#directive
  18287. * @kind function
  18288. *
  18289. * @description
  18290. * Register a new directive with the compiler.
  18291. *
  18292. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  18293. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  18294. * names and the values are the factories.
  18295. * @param {Function|Array} directiveFactory An injectable directive factory function. See the
  18296. * {@link guide/directive directive guide} and the {@link $compile compile API} for more info.
  18297. * @returns {ng.$compileProvider} Self for chaining.
  18298. */
  18299. this.directive = function registerDirective(name, directiveFactory) {
  18300. assertNotHasOwnProperty(name, 'directive');
  18301. if (isString(name)) {
  18302. assertValidDirectiveName(name);
  18303. assertArg(directiveFactory, 'directiveFactory');
  18304. if (!hasDirectives.hasOwnProperty(name)) {
  18305. hasDirectives[name] = [];
  18306. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  18307. function($injector, $exceptionHandler) {
  18308. var directives = [];
  18309. forEach(hasDirectives[name], function(directiveFactory, index) {
  18310. try {
  18311. var directive = $injector.invoke(directiveFactory);
  18312. if (isFunction(directive)) {
  18313. directive = { compile: valueFn(directive) };
  18314. } else if (!directive.compile && directive.link) {
  18315. directive.compile = valueFn(directive.link);
  18316. }
  18317. directive.priority = directive.priority || 0;
  18318. directive.index = index;
  18319. directive.name = directive.name || name;
  18320. directive.require = directive.require || (directive.controller && directive.name);
  18321. directive.restrict = directive.restrict || 'EA';
  18322. directive.$$moduleName = directiveFactory.$$moduleName;
  18323. directives.push(directive);
  18324. } catch (e) {
  18325. $exceptionHandler(e);
  18326. }
  18327. });
  18328. return directives;
  18329. }]);
  18330. }
  18331. hasDirectives[name].push(directiveFactory);
  18332. } else {
  18333. forEach(name, reverseParams(registerDirective));
  18334. }
  18335. return this;
  18336. };
  18337. /**
  18338. * @ngdoc method
  18339. * @name $compileProvider#component
  18340. * @module ng
  18341. * @param {string} name Name of the component in camelCase (i.e. `myComp` which will match `<my-comp>`)
  18342. * @param {Object} options Component definition object (a simplified
  18343. * {@link ng.$compile#directive-definition-object directive definition object}),
  18344. * with the following properties (all optional):
  18345. *
  18346. * - `controller` – `{(string|function()=}` – controller constructor function that should be
  18347. * associated with newly created scope or the name of a {@link ng.$compile#-controller-
  18348. * registered controller} if passed as a string. An empty `noop` function by default.
  18349. * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope.
  18350. * If present, the controller will be published to scope under the `controllerAs` name.
  18351. * If not present, this will default to be `$ctrl`.
  18352. * - `template` – `{string=|function()=}` – html template as a string or a function that
  18353. * returns an html template as a string which should be used as the contents of this component.
  18354. * Empty string by default.
  18355. *
  18356. * If `template` is a function, then it is {@link auto.$injector#invoke injected} with
  18357. * the following locals:
  18358. *
  18359. * - `$element` - Current element
  18360. * - `$attrs` - Current attributes object for the element
  18361. *
  18362. * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
  18363. * template that should be used as the contents of this component.
  18364. *
  18365. * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with
  18366. * the following locals:
  18367. *
  18368. * - `$element` - Current element
  18369. * - `$attrs` - Current attributes object for the element
  18370. *
  18371. * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties.
  18372. * Component properties are always bound to the component controller and not to the scope.
  18373. * See {@link ng.$compile#-bindtocontroller- `bindToController`}.
  18374. * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled.
  18375. * Disabled by default.
  18376. * - `$...` – additional properties to attach to the directive factory function and the controller
  18377. * constructor function. (This is used by the component router to annotate)
  18378. *
  18379. * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls.
  18380. * @description
  18381. * Register a **component definition** with the compiler. This is a shorthand for registering a special
  18382. * type of directive, which represents a self-contained UI component in your application. Such components
  18383. * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`).
  18384. *
  18385. * Component definitions are very simple and do not require as much configuration as defining general
  18386. * directives. Component definitions usually consist only of a template and a controller backing it.
  18387. *
  18388. * In order to make the definition easier, components enforce best practices like use of `controllerAs`,
  18389. * `bindToController`. They always have **isolate scope** and are restricted to elements.
  18390. *
  18391. * Here are a few examples of how you would usually define components:
  18392. *
  18393. * ```js
  18394. * var myMod = angular.module(...);
  18395. * myMod.component('myComp', {
  18396. * template: '<div>My name is {{$ctrl.name}}</div>',
  18397. * controller: function() {
  18398. * this.name = 'shahar';
  18399. * }
  18400. * });
  18401. *
  18402. * myMod.component('myComp', {
  18403. * template: '<div>My name is {{$ctrl.name}}</div>',
  18404. * bindings: {name: '@'}
  18405. * });
  18406. *
  18407. * myMod.component('myComp', {
  18408. * templateUrl: 'views/my-comp.html',
  18409. * controller: 'MyCtrl',
  18410. * controllerAs: 'ctrl',
  18411. * bindings: {name: '@'}
  18412. * });
  18413. *
  18414. * ```
  18415. * For more examples, and an in-depth guide, see the {@link guide/component component guide}.
  18416. *
  18417. * <br />
  18418. * See also {@link ng.$compileProvider#directive $compileProvider.directive()}.
  18419. */
  18420. this.component = function registerComponent(name, options) {
  18421. var controller = options.controller || noop;
  18422. function factory($injector) {
  18423. function makeInjectable(fn) {
  18424. if (isFunction(fn) || isArray(fn)) {
  18425. return function(tElement, tAttrs) {
  18426. return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs});
  18427. };
  18428. } else {
  18429. return fn;
  18430. }
  18431. }
  18432. var template = (!options.template && !options.templateUrl ? '' : options.template);
  18433. return {
  18434. controller: controller,
  18435. controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl',
  18436. template: makeInjectable(template),
  18437. templateUrl: makeInjectable(options.templateUrl),
  18438. transclude: options.transclude,
  18439. scope: {},
  18440. bindToController: options.bindings || {},
  18441. restrict: 'E',
  18442. require: options.require
  18443. };
  18444. }
  18445. // Copy any annotation properties (starting with $) over to the factory function
  18446. // These could be used by libraries such as the new component router
  18447. forEach(options, function(val, key) {
  18448. if (key.charAt(0) === '$') {
  18449. factory[key] = val;
  18450. controller[key] = val;
  18451. }
  18452. });
  18453. factory.$inject = ['$injector'];
  18454. return this.directive(name, factory);
  18455. };
  18456. /**
  18457. * @ngdoc method
  18458. * @name $compileProvider#aHrefSanitizationWhitelist
  18459. * @kind function
  18460. *
  18461. * @description
  18462. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  18463. * urls during a[href] sanitization.
  18464. *
  18465. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  18466. *
  18467. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  18468. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  18469. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  18470. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  18471. *
  18472. * @param {RegExp=} regexp New regexp to whitelist urls with.
  18473. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18474. * chaining otherwise.
  18475. */
  18476. this.aHrefSanitizationWhitelist = function(regexp) {
  18477. if (isDefined(regexp)) {
  18478. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  18479. return this;
  18480. } else {
  18481. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  18482. }
  18483. };
  18484. /**
  18485. * @ngdoc method
  18486. * @name $compileProvider#imgSrcSanitizationWhitelist
  18487. * @kind function
  18488. *
  18489. * @description
  18490. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  18491. * urls during img[src] sanitization.
  18492. *
  18493. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  18494. *
  18495. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  18496. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  18497. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  18498. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  18499. *
  18500. * @param {RegExp=} regexp New regexp to whitelist urls with.
  18501. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  18502. * chaining otherwise.
  18503. */
  18504. this.imgSrcSanitizationWhitelist = function(regexp) {
  18505. if (isDefined(regexp)) {
  18506. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  18507. return this;
  18508. } else {
  18509. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  18510. }
  18511. };
  18512. /**
  18513. * @ngdoc method
  18514. * @name $compileProvider#debugInfoEnabled
  18515. *
  18516. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  18517. * current debugInfoEnabled state
  18518. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  18519. *
  18520. * @kind function
  18521. *
  18522. * @description
  18523. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  18524. * binding information and a reference to the current scope on to DOM elements.
  18525. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  18526. * * `ng-binding` CSS class
  18527. * * `$binding` data property containing an array of the binding expressions
  18528. *
  18529. * You may want to disable this in production for a significant performance boost. See
  18530. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  18531. *
  18532. * The default value is true.
  18533. */
  18534. var debugInfoEnabled = true;
  18535. this.debugInfoEnabled = function(enabled) {
  18536. if (isDefined(enabled)) {
  18537. debugInfoEnabled = enabled;
  18538. return this;
  18539. }
  18540. return debugInfoEnabled;
  18541. };
  18542. var TTL = 10;
  18543. /**
  18544. * @ngdoc method
  18545. * @name $compileProvider#onChangesTtl
  18546. * @description
  18547. *
  18548. * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and
  18549. * assuming that the model is unstable.
  18550. *
  18551. * The current default is 10 iterations.
  18552. *
  18553. * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result
  18554. * in several iterations of calls to these hooks. However if an application needs more than the default 10
  18555. * iterations to stabilize then you should investigate what is causing the model to continuously change during
  18556. * the `$onChanges` hook execution.
  18557. *
  18558. * Increasing the TTL could have performance implications, so you should not change it without proper justification.
  18559. *
  18560. * @param {number} limit The number of `$onChanges` hook iterations.
  18561. * @returns {number|object} the current limit (or `this` if called as a setter for chaining)
  18562. */
  18563. this.onChangesTtl = function(value) {
  18564. if (arguments.length) {
  18565. TTL = value;
  18566. return this;
  18567. }
  18568. return TTL;
  18569. };
  18570. this.$get = [
  18571. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  18572. '$controller', '$rootScope', '$sce', '$animate', '$$sanitizeUri',
  18573. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  18574. $controller, $rootScope, $sce, $animate, $$sanitizeUri) {
  18575. var SIMPLE_ATTR_NAME = /^\w/;
  18576. var specialAttrHolder = document.createElement('div');
  18577. var onChangesTtl = TTL;
  18578. // The onChanges hooks should all be run together in a single digest
  18579. // When changes occur, the call to trigger their hooks will be added to this queue
  18580. var onChangesQueue;
  18581. // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest
  18582. function flushOnChangesQueue() {
  18583. try {
  18584. if (!(--onChangesTtl)) {
  18585. // We have hit the TTL limit so reset everything
  18586. onChangesQueue = undefined;
  18587. throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL);
  18588. }
  18589. // We must run this hook in an apply since the $$postDigest runs outside apply
  18590. $rootScope.$apply(function() {
  18591. for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) {
  18592. onChangesQueue[i]();
  18593. }
  18594. // Reset the queue to trigger a new schedule next time there is a change
  18595. onChangesQueue = undefined;
  18596. });
  18597. } finally {
  18598. onChangesTtl++;
  18599. }
  18600. }
  18601. function Attributes(element, attributesToCopy) {
  18602. if (attributesToCopy) {
  18603. var keys = Object.keys(attributesToCopy);
  18604. var i, l, key;
  18605. for (i = 0, l = keys.length; i < l; i++) {
  18606. key = keys[i];
  18607. this[key] = attributesToCopy[key];
  18608. }
  18609. } else {
  18610. this.$attr = {};
  18611. }
  18612. this.$$element = element;
  18613. }
  18614. Attributes.prototype = {
  18615. /**
  18616. * @ngdoc method
  18617. * @name $compile.directive.Attributes#$normalize
  18618. * @kind function
  18619. *
  18620. * @description
  18621. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  18622. * `data-`) to its normalized, camelCase form.
  18623. *
  18624. * Also there is special case for Moz prefix starting with upper case letter.
  18625. *
  18626. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  18627. *
  18628. * @param {string} name Name to normalize
  18629. */
  18630. $normalize: directiveNormalize,
  18631. /**
  18632. * @ngdoc method
  18633. * @name $compile.directive.Attributes#$addClass
  18634. * @kind function
  18635. *
  18636. * @description
  18637. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  18638. * are enabled then an animation will be triggered for the class addition.
  18639. *
  18640. * @param {string} classVal The className value that will be added to the element
  18641. */
  18642. $addClass: function(classVal) {
  18643. if (classVal && classVal.length > 0) {
  18644. $animate.addClass(this.$$element, classVal);
  18645. }
  18646. },
  18647. /**
  18648. * @ngdoc method
  18649. * @name $compile.directive.Attributes#$removeClass
  18650. * @kind function
  18651. *
  18652. * @description
  18653. * Removes the CSS class value specified by the classVal parameter from the element. If
  18654. * animations are enabled then an animation will be triggered for the class removal.
  18655. *
  18656. * @param {string} classVal The className value that will be removed from the element
  18657. */
  18658. $removeClass: function(classVal) {
  18659. if (classVal && classVal.length > 0) {
  18660. $animate.removeClass(this.$$element, classVal);
  18661. }
  18662. },
  18663. /**
  18664. * @ngdoc method
  18665. * @name $compile.directive.Attributes#$updateClass
  18666. * @kind function
  18667. *
  18668. * @description
  18669. * Adds and removes the appropriate CSS class values to the element based on the difference
  18670. * between the new and old CSS class values (specified as newClasses and oldClasses).
  18671. *
  18672. * @param {string} newClasses The current CSS className value
  18673. * @param {string} oldClasses The former CSS className value
  18674. */
  18675. $updateClass: function(newClasses, oldClasses) {
  18676. var toAdd = tokenDifference(newClasses, oldClasses);
  18677. if (toAdd && toAdd.length) {
  18678. $animate.addClass(this.$$element, toAdd);
  18679. }
  18680. var toRemove = tokenDifference(oldClasses, newClasses);
  18681. if (toRemove && toRemove.length) {
  18682. $animate.removeClass(this.$$element, toRemove);
  18683. }
  18684. },
  18685. /**
  18686. * Set a normalized attribute on the element in a way such that all directives
  18687. * can share the attribute. This function properly handles boolean attributes.
  18688. * @param {string} key Normalized key. (ie ngAttribute)
  18689. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  18690. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  18691. * Defaults to true.
  18692. * @param {string=} attrName Optional none normalized name. Defaults to key.
  18693. */
  18694. $set: function(key, value, writeAttr, attrName) {
  18695. // TODO: decide whether or not to throw an error if "class"
  18696. //is set through this function since it may cause $updateClass to
  18697. //become unstable.
  18698. var node = this.$$element[0],
  18699. booleanKey = getBooleanAttrName(node, key),
  18700. aliasedKey = getAliasedAttrName(key),
  18701. observer = key,
  18702. nodeName;
  18703. if (booleanKey) {
  18704. this.$$element.prop(key, value);
  18705. attrName = booleanKey;
  18706. } else if (aliasedKey) {
  18707. this[aliasedKey] = value;
  18708. observer = aliasedKey;
  18709. }
  18710. this[key] = value;
  18711. // translate normalized key to actual key
  18712. if (attrName) {
  18713. this.$attr[key] = attrName;
  18714. } else {
  18715. attrName = this.$attr[key];
  18716. if (!attrName) {
  18717. this.$attr[key] = attrName = snake_case(key, '-');
  18718. }
  18719. }
  18720. nodeName = nodeName_(this.$$element);
  18721. if ((nodeName === 'a' && (key === 'href' || key === 'xlinkHref')) ||
  18722. (nodeName === 'img' && key === 'src')) {
  18723. // sanitize a[href] and img[src] values
  18724. this[key] = value = $$sanitizeUri(value, key === 'src');
  18725. } else if (nodeName === 'img' && key === 'srcset') {
  18726. // sanitize img[srcset] values
  18727. var result = "";
  18728. // first check if there are spaces because it's not the same pattern
  18729. var trimmedSrcset = trim(value);
  18730. // ( 999x ,| 999w ,| ,|, )
  18731. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  18732. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  18733. // split srcset into tuple of uri and descriptor except for the last item
  18734. var rawUris = trimmedSrcset.split(pattern);
  18735. // for each tuples
  18736. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  18737. for (var i = 0; i < nbrUrisWith2parts; i++) {
  18738. var innerIdx = i * 2;
  18739. // sanitize the uri
  18740. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  18741. // add the descriptor
  18742. result += (" " + trim(rawUris[innerIdx + 1]));
  18743. }
  18744. // split the last item into uri and descriptor
  18745. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  18746. // sanitize the last uri
  18747. result += $$sanitizeUri(trim(lastTuple[0]), true);
  18748. // and add the last descriptor if any
  18749. if (lastTuple.length === 2) {
  18750. result += (" " + trim(lastTuple[1]));
  18751. }
  18752. this[key] = value = result;
  18753. }
  18754. if (writeAttr !== false) {
  18755. if (value === null || isUndefined(value)) {
  18756. this.$$element.removeAttr(attrName);
  18757. } else {
  18758. if (SIMPLE_ATTR_NAME.test(attrName)) {
  18759. this.$$element.attr(attrName, value);
  18760. } else {
  18761. setSpecialAttr(this.$$element[0], attrName, value);
  18762. }
  18763. }
  18764. }
  18765. // fire observers
  18766. var $$observers = this.$$observers;
  18767. $$observers && forEach($$observers[observer], function(fn) {
  18768. try {
  18769. fn(value);
  18770. } catch (e) {
  18771. $exceptionHandler(e);
  18772. }
  18773. });
  18774. },
  18775. /**
  18776. * @ngdoc method
  18777. * @name $compile.directive.Attributes#$observe
  18778. * @kind function
  18779. *
  18780. * @description
  18781. * Observes an interpolated attribute.
  18782. *
  18783. * The observer function will be invoked once during the next `$digest` following
  18784. * compilation. The observer is then invoked whenever the interpolated value
  18785. * changes.
  18786. *
  18787. * @param {string} key Normalized key. (ie ngAttribute) .
  18788. * @param {function(interpolatedValue)} fn Function that will be called whenever
  18789. the interpolated value of the attribute changes.
  18790. * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation
  18791. * guide} for more info.
  18792. * @returns {function()} Returns a deregistration function for this observer.
  18793. */
  18794. $observe: function(key, fn) {
  18795. var attrs = this,
  18796. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  18797. listeners = ($$observers[key] || ($$observers[key] = []));
  18798. listeners.push(fn);
  18799. $rootScope.$evalAsync(function() {
  18800. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  18801. // no one registered attribute interpolation function, so lets call it manually
  18802. fn(attrs[key]);
  18803. }
  18804. });
  18805. return function() {
  18806. arrayRemove(listeners, fn);
  18807. };
  18808. }
  18809. };
  18810. function setSpecialAttr(element, attrName, value) {
  18811. // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute`
  18812. // so we have to jump through some hoops to get such an attribute
  18813. // https://github.com/angular/angular.js/pull/13318
  18814. specialAttrHolder.innerHTML = "<span " + attrName + ">";
  18815. var attributes = specialAttrHolder.firstChild.attributes;
  18816. var attribute = attributes[0];
  18817. // We have to remove the attribute from its container element before we can add it to the destination element
  18818. attributes.removeNamedItem(attribute.name);
  18819. attribute.value = value;
  18820. element.attributes.setNamedItem(attribute);
  18821. }
  18822. function safeAddClass($element, className) {
  18823. try {
  18824. $element.addClass(className);
  18825. } catch (e) {
  18826. // ignore, since it means that we are trying to set class on
  18827. // SVG element, where class name is read-only.
  18828. }
  18829. }
  18830. var startSymbol = $interpolate.startSymbol(),
  18831. endSymbol = $interpolate.endSymbol(),
  18832. denormalizeTemplate = (startSymbol == '{{' && endSymbol == '}}')
  18833. ? identity
  18834. : function denormalizeTemplate(template) {
  18835. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  18836. },
  18837. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  18838. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  18839. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  18840. var bindings = $element.data('$binding') || [];
  18841. if (isArray(binding)) {
  18842. bindings = bindings.concat(binding);
  18843. } else {
  18844. bindings.push(binding);
  18845. }
  18846. $element.data('$binding', bindings);
  18847. } : noop;
  18848. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  18849. safeAddClass($element, 'ng-binding');
  18850. } : noop;
  18851. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  18852. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  18853. $element.data(dataName, scope);
  18854. } : noop;
  18855. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  18856. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  18857. } : noop;
  18858. compile.$$createComment = function(directiveName, comment) {
  18859. var content = '';
  18860. if (debugInfoEnabled) {
  18861. content = ' ' + (directiveName || '') + ': ' + (comment || '') + ' ';
  18862. }
  18863. return document.createComment(content);
  18864. };
  18865. return compile;
  18866. //================================
  18867. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  18868. previousCompileContext) {
  18869. if (!($compileNodes instanceof jqLite)) {
  18870. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  18871. // modify it.
  18872. $compileNodes = jqLite($compileNodes);
  18873. }
  18874. var NOT_EMPTY = /\S+/;
  18875. // We can not compile top level text elements since text nodes can be merged and we will
  18876. // not be able to attach scope data to them, so we will wrap them in <span>
  18877. for (var i = 0, len = $compileNodes.length; i < len; i++) {
  18878. var domNode = $compileNodes[i];
  18879. if (domNode.nodeType === NODE_TYPE_TEXT && domNode.nodeValue.match(NOT_EMPTY) /* non-empty */) {
  18880. jqLiteWrapNode(domNode, $compileNodes[i] = document.createElement('span'));
  18881. }
  18882. }
  18883. var compositeLinkFn =
  18884. compileNodes($compileNodes, transcludeFn, $compileNodes,
  18885. maxPriority, ignoreDirective, previousCompileContext);
  18886. compile.$$addScopeClass($compileNodes);
  18887. var namespace = null;
  18888. return function publicLinkFn(scope, cloneConnectFn, options) {
  18889. assertArg(scope, 'scope');
  18890. if (previousCompileContext && previousCompileContext.needsNewScope) {
  18891. // A parent directive did a replace and a directive on this element asked
  18892. // for transclusion, which caused us to lose a layer of element on which
  18893. // we could hold the new transclusion scope, so we will create it manually
  18894. // here.
  18895. scope = scope.$parent.$new();
  18896. }
  18897. options = options || {};
  18898. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  18899. transcludeControllers = options.transcludeControllers,
  18900. futureParentElement = options.futureParentElement;
  18901. // When `parentBoundTranscludeFn` is passed, it is a
  18902. // `controllersBoundTransclude` function (it was previously passed
  18903. // as `transclude` to directive.link) so we must unwrap it to get
  18904. // its `boundTranscludeFn`
  18905. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  18906. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  18907. }
  18908. if (!namespace) {
  18909. namespace = detectNamespaceForChildElements(futureParentElement);
  18910. }
  18911. var $linkNode;
  18912. if (namespace !== 'html') {
  18913. // When using a directive with replace:true and templateUrl the $compileNodes
  18914. // (or a child element inside of them)
  18915. // might change, so we need to recreate the namespace adapted compileNodes
  18916. // for call to the link function.
  18917. // Note: This will already clone the nodes...
  18918. $linkNode = jqLite(
  18919. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  18920. );
  18921. } else if (cloneConnectFn) {
  18922. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  18923. // and sometimes changes the structure of the DOM.
  18924. $linkNode = JQLitePrototype.clone.call($compileNodes);
  18925. } else {
  18926. $linkNode = $compileNodes;
  18927. }
  18928. if (transcludeControllers) {
  18929. for (var controllerName in transcludeControllers) {
  18930. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  18931. }
  18932. }
  18933. compile.$$addScopeInfo($linkNode, scope);
  18934. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  18935. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  18936. return $linkNode;
  18937. };
  18938. }
  18939. function detectNamespaceForChildElements(parentElement) {
  18940. // TODO: Make this detect MathML as well...
  18941. var node = parentElement && parentElement[0];
  18942. if (!node) {
  18943. return 'html';
  18944. } else {
  18945. return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html';
  18946. }
  18947. }
  18948. /**
  18949. * Compile function matches each node in nodeList against the directives. Once all directives
  18950. * for a particular node are collected their compile functions are executed. The compile
  18951. * functions return values - the linking functions - are combined into a composite linking
  18952. * function, which is the a linking function for the node.
  18953. *
  18954. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  18955. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  18956. * scope argument is auto-generated to the new child of the transcluded parent scope.
  18957. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  18958. * the rootElement must be set the jqLite collection of the compile root. This is
  18959. * needed so that the jqLite collection items can be replaced with widgets.
  18960. * @param {number=} maxPriority Max directive priority.
  18961. * @returns {Function} A composite linking function of all of the matched directives or null.
  18962. */
  18963. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  18964. previousCompileContext) {
  18965. var linkFns = [],
  18966. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  18967. for (var i = 0; i < nodeList.length; i++) {
  18968. attrs = new Attributes();
  18969. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  18970. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  18971. ignoreDirective);
  18972. nodeLinkFn = (directives.length)
  18973. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  18974. null, [], [], previousCompileContext)
  18975. : null;
  18976. if (nodeLinkFn && nodeLinkFn.scope) {
  18977. compile.$$addScopeClass(attrs.$$element);
  18978. }
  18979. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  18980. !(childNodes = nodeList[i].childNodes) ||
  18981. !childNodes.length)
  18982. ? null
  18983. : compileNodes(childNodes,
  18984. nodeLinkFn ? (
  18985. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  18986. && nodeLinkFn.transclude) : transcludeFn);
  18987. if (nodeLinkFn || childLinkFn) {
  18988. linkFns.push(i, nodeLinkFn, childLinkFn);
  18989. linkFnFound = true;
  18990. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  18991. }
  18992. //use the previous context only for the first element in the virtual group
  18993. previousCompileContext = null;
  18994. }
  18995. // return a linking function if we have found anything, null otherwise
  18996. return linkFnFound ? compositeLinkFn : null;
  18997. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  18998. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  18999. var stableNodeList;
  19000. if (nodeLinkFnFound) {
  19001. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  19002. // offsets don't get screwed up
  19003. var nodeListLength = nodeList.length;
  19004. stableNodeList = new Array(nodeListLength);
  19005. // create a sparse array by only copying the elements which have a linkFn
  19006. for (i = 0; i < linkFns.length; i+=3) {
  19007. idx = linkFns[i];
  19008. stableNodeList[idx] = nodeList[idx];
  19009. }
  19010. } else {
  19011. stableNodeList = nodeList;
  19012. }
  19013. for (i = 0, ii = linkFns.length; i < ii;) {
  19014. node = stableNodeList[linkFns[i++]];
  19015. nodeLinkFn = linkFns[i++];
  19016. childLinkFn = linkFns[i++];
  19017. if (nodeLinkFn) {
  19018. if (nodeLinkFn.scope) {
  19019. childScope = scope.$new();
  19020. compile.$$addScopeInfo(jqLite(node), childScope);
  19021. } else {
  19022. childScope = scope;
  19023. }
  19024. if (nodeLinkFn.transcludeOnThisElement) {
  19025. childBoundTranscludeFn = createBoundTranscludeFn(
  19026. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  19027. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  19028. childBoundTranscludeFn = parentBoundTranscludeFn;
  19029. } else if (!parentBoundTranscludeFn && transcludeFn) {
  19030. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  19031. } else {
  19032. childBoundTranscludeFn = null;
  19033. }
  19034. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  19035. } else if (childLinkFn) {
  19036. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  19037. }
  19038. }
  19039. }
  19040. }
  19041. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  19042. function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  19043. if (!transcludedScope) {
  19044. transcludedScope = scope.$new(false, containingScope);
  19045. transcludedScope.$$transcluded = true;
  19046. }
  19047. return transcludeFn(transcludedScope, cloneFn, {
  19048. parentBoundTranscludeFn: previousBoundTranscludeFn,
  19049. transcludeControllers: controllers,
  19050. futureParentElement: futureParentElement
  19051. });
  19052. }
  19053. // We need to attach the transclusion slots onto the `boundTranscludeFn`
  19054. // so that they are available inside the `controllersBoundTransclude` function
  19055. var boundSlots = boundTranscludeFn.$$slots = createMap();
  19056. for (var slotName in transcludeFn.$$slots) {
  19057. if (transcludeFn.$$slots[slotName]) {
  19058. boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn);
  19059. } else {
  19060. boundSlots[slotName] = null;
  19061. }
  19062. }
  19063. return boundTranscludeFn;
  19064. }
  19065. /**
  19066. * Looks for directives on the given node and adds them to the directive collection which is
  19067. * sorted.
  19068. *
  19069. * @param node Node to search.
  19070. * @param directives An array to which the directives are added to. This array is sorted before
  19071. * the function returns.
  19072. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  19073. * @param {number=} maxPriority Max directive priority.
  19074. */
  19075. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  19076. var nodeType = node.nodeType,
  19077. attrsMap = attrs.$attr,
  19078. match,
  19079. className;
  19080. switch (nodeType) {
  19081. case NODE_TYPE_ELEMENT: /* Element */
  19082. // use the node name: <directive>
  19083. addDirective(directives,
  19084. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  19085. // iterate over the attributes
  19086. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  19087. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  19088. var attrStartName = false;
  19089. var attrEndName = false;
  19090. attr = nAttrs[j];
  19091. name = attr.name;
  19092. value = trim(attr.value);
  19093. // support ngAttr attribute binding
  19094. ngAttrName = directiveNormalize(name);
  19095. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  19096. name = name.replace(PREFIX_REGEXP, '')
  19097. .substr(8).replace(/_(.)/g, function(match, letter) {
  19098. return letter.toUpperCase();
  19099. });
  19100. }
  19101. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  19102. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  19103. attrStartName = name;
  19104. attrEndName = name.substr(0, name.length - 5) + 'end';
  19105. name = name.substr(0, name.length - 6);
  19106. }
  19107. nName = directiveNormalize(name.toLowerCase());
  19108. attrsMap[nName] = name;
  19109. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  19110. attrs[nName] = value;
  19111. if (getBooleanAttrName(node, nName)) {
  19112. attrs[nName] = true; // presence means true
  19113. }
  19114. }
  19115. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  19116. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  19117. attrEndName);
  19118. }
  19119. // use class as directive
  19120. className = node.className;
  19121. if (isObject(className)) {
  19122. // Maybe SVGAnimatedString
  19123. className = className.animVal;
  19124. }
  19125. if (isString(className) && className !== '') {
  19126. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  19127. nName = directiveNormalize(match[2]);
  19128. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  19129. attrs[nName] = trim(match[3]);
  19130. }
  19131. className = className.substr(match.index + match[0].length);
  19132. }
  19133. }
  19134. break;
  19135. case NODE_TYPE_TEXT: /* Text Node */
  19136. if (msie === 11) {
  19137. // Workaround for #11781
  19138. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  19139. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  19140. node.parentNode.removeChild(node.nextSibling);
  19141. }
  19142. }
  19143. addTextInterpolateDirective(directives, node.nodeValue);
  19144. break;
  19145. case NODE_TYPE_COMMENT: /* Comment */
  19146. try {
  19147. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  19148. if (match) {
  19149. nName = directiveNormalize(match[1]);
  19150. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  19151. attrs[nName] = trim(match[2]);
  19152. }
  19153. }
  19154. } catch (e) {
  19155. // turns out that under some circumstances IE9 throws errors when one attempts to read
  19156. // comment's node value.
  19157. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  19158. }
  19159. break;
  19160. }
  19161. directives.sort(byPriority);
  19162. return directives;
  19163. }
  19164. /**
  19165. * Given a node with an directive-start it collects all of the siblings until it finds
  19166. * directive-end.
  19167. * @param node
  19168. * @param attrStart
  19169. * @param attrEnd
  19170. * @returns {*}
  19171. */
  19172. function groupScan(node, attrStart, attrEnd) {
  19173. var nodes = [];
  19174. var depth = 0;
  19175. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  19176. do {
  19177. if (!node) {
  19178. throw $compileMinErr('uterdir',
  19179. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  19180. attrStart, attrEnd);
  19181. }
  19182. if (node.nodeType == NODE_TYPE_ELEMENT) {
  19183. if (node.hasAttribute(attrStart)) depth++;
  19184. if (node.hasAttribute(attrEnd)) depth--;
  19185. }
  19186. nodes.push(node);
  19187. node = node.nextSibling;
  19188. } while (depth > 0);
  19189. } else {
  19190. nodes.push(node);
  19191. }
  19192. return jqLite(nodes);
  19193. }
  19194. /**
  19195. * Wrapper for linking function which converts normal linking function into a grouped
  19196. * linking function.
  19197. * @param linkFn
  19198. * @param attrStart
  19199. * @param attrEnd
  19200. * @returns {Function}
  19201. */
  19202. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  19203. return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) {
  19204. element = groupScan(element[0], attrStart, attrEnd);
  19205. return linkFn(scope, element, attrs, controllers, transcludeFn);
  19206. };
  19207. }
  19208. /**
  19209. * A function generator that is used to support both eager and lazy compilation
  19210. * linking function.
  19211. * @param eager
  19212. * @param $compileNodes
  19213. * @param transcludeFn
  19214. * @param maxPriority
  19215. * @param ignoreDirective
  19216. * @param previousCompileContext
  19217. * @returns {Function}
  19218. */
  19219. function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) {
  19220. var compiled;
  19221. if (eager) {
  19222. return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  19223. }
  19224. return function lazyCompilation() {
  19225. if (!compiled) {
  19226. compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext);
  19227. // Null out all of these references in order to make them eligible for garbage collection
  19228. // since this is a potentially long lived closure
  19229. $compileNodes = transcludeFn = previousCompileContext = null;
  19230. }
  19231. return compiled.apply(this, arguments);
  19232. };
  19233. }
  19234. /**
  19235. * Once the directives have been collected, their compile functions are executed. This method
  19236. * is responsible for inlining directive templates as well as terminating the application
  19237. * of the directives if the terminal directive has been reached.
  19238. *
  19239. * @param {Array} directives Array of collected directives to execute their compile function.
  19240. * this needs to be pre-sorted by priority order.
  19241. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  19242. * @param {Object} templateAttrs The shared attribute function
  19243. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  19244. * scope argument is auto-generated to the new
  19245. * child of the transcluded parent scope.
  19246. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  19247. * argument has the root jqLite array so that we can replace nodes
  19248. * on it.
  19249. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  19250. * compiling the transclusion.
  19251. * @param {Array.<Function>} preLinkFns
  19252. * @param {Array.<Function>} postLinkFns
  19253. * @param {Object} previousCompileContext Context used for previous compilation of the current
  19254. * node
  19255. * @returns {Function} linkFn
  19256. */
  19257. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  19258. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  19259. previousCompileContext) {
  19260. previousCompileContext = previousCompileContext || {};
  19261. var terminalPriority = -Number.MAX_VALUE,
  19262. newScopeDirective = previousCompileContext.newScopeDirective,
  19263. controllerDirectives = previousCompileContext.controllerDirectives,
  19264. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  19265. templateDirective = previousCompileContext.templateDirective,
  19266. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  19267. hasTranscludeDirective = false,
  19268. hasTemplate = false,
  19269. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  19270. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  19271. directive,
  19272. directiveName,
  19273. $template,
  19274. replaceDirective = originalReplaceDirective,
  19275. childTranscludeFn = transcludeFn,
  19276. linkFn,
  19277. didScanForMultipleTransclusion = false,
  19278. mightHaveMultipleTransclusionError = false,
  19279. directiveValue;
  19280. // executes all directives on the current element
  19281. for (var i = 0, ii = directives.length; i < ii; i++) {
  19282. directive = directives[i];
  19283. var attrStart = directive.$$start;
  19284. var attrEnd = directive.$$end;
  19285. // collect multiblock sections
  19286. if (attrStart) {
  19287. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  19288. }
  19289. $template = undefined;
  19290. if (terminalPriority > directive.priority) {
  19291. break; // prevent further processing of directives
  19292. }
  19293. if (directiveValue = directive.scope) {
  19294. // skip the check for directives with async templates, we'll check the derived sync
  19295. // directive when the template arrives
  19296. if (!directive.templateUrl) {
  19297. if (isObject(directiveValue)) {
  19298. // This directive is trying to add an isolated scope.
  19299. // Check that there is no scope of any kind already
  19300. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  19301. directive, $compileNode);
  19302. newIsolateScopeDirective = directive;
  19303. } else {
  19304. // This directive is trying to add a child scope.
  19305. // Check that there is no isolated scope already
  19306. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  19307. $compileNode);
  19308. }
  19309. }
  19310. newScopeDirective = newScopeDirective || directive;
  19311. }
  19312. directiveName = directive.name;
  19313. // If we encounter a condition that can result in transclusion on the directive,
  19314. // then scan ahead in the remaining directives for others that may cause a multiple
  19315. // transclusion error to be thrown during the compilation process. If a matching directive
  19316. // is found, then we know that when we encounter a transcluded directive, we need to eagerly
  19317. // compile the `transclude` function rather than doing it lazily in order to throw
  19318. // exceptions at the correct time
  19319. if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template))
  19320. || (directive.transclude && !directive.$$tlb))) {
  19321. var candidateDirective;
  19322. for (var scanningIndex = i + 1; candidateDirective = directives[scanningIndex++];) {
  19323. if ((candidateDirective.transclude && !candidateDirective.$$tlb)
  19324. || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) {
  19325. mightHaveMultipleTransclusionError = true;
  19326. break;
  19327. }
  19328. }
  19329. didScanForMultipleTransclusion = true;
  19330. }
  19331. if (!directive.templateUrl && directive.controller) {
  19332. directiveValue = directive.controller;
  19333. controllerDirectives = controllerDirectives || createMap();
  19334. assertNoDuplicate("'" + directiveName + "' controller",
  19335. controllerDirectives[directiveName], directive, $compileNode);
  19336. controllerDirectives[directiveName] = directive;
  19337. }
  19338. if (directiveValue = directive.transclude) {
  19339. hasTranscludeDirective = true;
  19340. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  19341. // This option should only be used by directives that know how to safely handle element transclusion,
  19342. // where the transcluded nodes are added or replaced after linking.
  19343. if (!directive.$$tlb) {
  19344. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  19345. nonTlbTranscludeDirective = directive;
  19346. }
  19347. if (directiveValue == 'element') {
  19348. hasElementTranscludeDirective = true;
  19349. terminalPriority = directive.priority;
  19350. $template = $compileNode;
  19351. $compileNode = templateAttrs.$$element =
  19352. jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName]));
  19353. compileNode = $compileNode[0];
  19354. replaceWith(jqCollection, sliceArgs($template), compileNode);
  19355. // Support: Chrome < 50
  19356. // https://github.com/angular/angular.js/issues/14041
  19357. // In the versions of V8 prior to Chrome 50, the document fragment that is created
  19358. // in the `replaceWith` function is improperly garbage collected despite still
  19359. // being referenced by the `parentNode` property of all of the child nodes. By adding
  19360. // a reference to the fragment via a different property, we can avoid that incorrect
  19361. // behavior.
  19362. // TODO: remove this line after Chrome 50 has been released
  19363. $template[0].$$parentNode = $template[0].parentNode;
  19364. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority,
  19365. replaceDirective && replaceDirective.name, {
  19366. // Don't pass in:
  19367. // - controllerDirectives - otherwise we'll create duplicates controllers
  19368. // - newIsolateScopeDirective or templateDirective - combining templates with
  19369. // element transclusion doesn't make sense.
  19370. //
  19371. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  19372. // on the same element more than once.
  19373. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  19374. });
  19375. } else {
  19376. var slots = createMap();
  19377. $template = jqLite(jqLiteClone(compileNode)).contents();
  19378. if (isObject(directiveValue)) {
  19379. // We have transclusion slots,
  19380. // collect them up, compile them and store their transclusion functions
  19381. $template = [];
  19382. var slotMap = createMap();
  19383. var filledSlots = createMap();
  19384. // Parse the element selectors
  19385. forEach(directiveValue, function(elementSelector, slotName) {
  19386. // If an element selector starts with a ? then it is optional
  19387. var optional = (elementSelector.charAt(0) === '?');
  19388. elementSelector = optional ? elementSelector.substring(1) : elementSelector;
  19389. slotMap[elementSelector] = slotName;
  19390. // We explicitly assign `null` since this implies that a slot was defined but not filled.
  19391. // Later when calling boundTransclusion functions with a slot name we only error if the
  19392. // slot is `undefined`
  19393. slots[slotName] = null;
  19394. // filledSlots contains `true` for all slots that are either optional or have been
  19395. // filled. This is used to check that we have not missed any required slots
  19396. filledSlots[slotName] = optional;
  19397. });
  19398. // Add the matching elements into their slot
  19399. forEach($compileNode.contents(), function(node) {
  19400. var slotName = slotMap[directiveNormalize(nodeName_(node))];
  19401. if (slotName) {
  19402. filledSlots[slotName] = true;
  19403. slots[slotName] = slots[slotName] || [];
  19404. slots[slotName].push(node);
  19405. } else {
  19406. $template.push(node);
  19407. }
  19408. });
  19409. // Check for required slots that were not filled
  19410. forEach(filledSlots, function(filled, slotName) {
  19411. if (!filled) {
  19412. throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName);
  19413. }
  19414. });
  19415. for (var slotName in slots) {
  19416. if (slots[slotName]) {
  19417. // Only define a transclusion function if the slot was filled
  19418. slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slots[slotName], transcludeFn);
  19419. }
  19420. }
  19421. }
  19422. $compileNode.empty(); // clear contents
  19423. childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined,
  19424. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  19425. childTranscludeFn.$$slots = slots;
  19426. }
  19427. }
  19428. if (directive.template) {
  19429. hasTemplate = true;
  19430. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  19431. templateDirective = directive;
  19432. directiveValue = (isFunction(directive.template))
  19433. ? directive.template($compileNode, templateAttrs)
  19434. : directive.template;
  19435. directiveValue = denormalizeTemplate(directiveValue);
  19436. if (directive.replace) {
  19437. replaceDirective = directive;
  19438. if (jqLiteIsTextNode(directiveValue)) {
  19439. $template = [];
  19440. } else {
  19441. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  19442. }
  19443. compileNode = $template[0];
  19444. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  19445. throw $compileMinErr('tplrt',
  19446. "Template for directive '{0}' must have exactly one root element. {1}",
  19447. directiveName, '');
  19448. }
  19449. replaceWith(jqCollection, $compileNode, compileNode);
  19450. var newTemplateAttrs = {$attr: {}};
  19451. // combine directives from the original node and from the template:
  19452. // - take the array of directives for this element
  19453. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  19454. // - collect directives from the template and sort them by priority
  19455. // - combine directives as: processed + template + unprocessed
  19456. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  19457. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  19458. if (newIsolateScopeDirective || newScopeDirective) {
  19459. // The original directive caused the current element to be replaced but this element
  19460. // also needs to have a new scope, so we need to tell the template directives
  19461. // that they would need to get their scope from further up, if they require transclusion
  19462. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  19463. }
  19464. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  19465. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  19466. ii = directives.length;
  19467. } else {
  19468. $compileNode.html(directiveValue);
  19469. }
  19470. }
  19471. if (directive.templateUrl) {
  19472. hasTemplate = true;
  19473. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  19474. templateDirective = directive;
  19475. if (directive.replace) {
  19476. replaceDirective = directive;
  19477. }
  19478. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  19479. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  19480. controllerDirectives: controllerDirectives,
  19481. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  19482. newIsolateScopeDirective: newIsolateScopeDirective,
  19483. templateDirective: templateDirective,
  19484. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  19485. });
  19486. ii = directives.length;
  19487. } else if (directive.compile) {
  19488. try {
  19489. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  19490. if (isFunction(linkFn)) {
  19491. addLinkFns(null, linkFn, attrStart, attrEnd);
  19492. } else if (linkFn) {
  19493. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  19494. }
  19495. } catch (e) {
  19496. $exceptionHandler(e, startingTag($compileNode));
  19497. }
  19498. }
  19499. if (directive.terminal) {
  19500. nodeLinkFn.terminal = true;
  19501. terminalPriority = Math.max(terminalPriority, directive.priority);
  19502. }
  19503. }
  19504. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  19505. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  19506. nodeLinkFn.templateOnThisElement = hasTemplate;
  19507. nodeLinkFn.transclude = childTranscludeFn;
  19508. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  19509. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  19510. return nodeLinkFn;
  19511. ////////////////////
  19512. function addLinkFns(pre, post, attrStart, attrEnd) {
  19513. if (pre) {
  19514. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  19515. pre.require = directive.require;
  19516. pre.directiveName = directiveName;
  19517. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  19518. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  19519. }
  19520. preLinkFns.push(pre);
  19521. }
  19522. if (post) {
  19523. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  19524. post.require = directive.require;
  19525. post.directiveName = directiveName;
  19526. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  19527. post = cloneAndAnnotateFn(post, {isolateScope: true});
  19528. }
  19529. postLinkFns.push(post);
  19530. }
  19531. }
  19532. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  19533. var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  19534. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  19535. if (compileNode === linkNode) {
  19536. attrs = templateAttrs;
  19537. $element = templateAttrs.$$element;
  19538. } else {
  19539. $element = jqLite(linkNode);
  19540. attrs = new Attributes($element, templateAttrs);
  19541. }
  19542. controllerScope = scope;
  19543. if (newIsolateScopeDirective) {
  19544. isolateScope = scope.$new(true);
  19545. } else if (newScopeDirective) {
  19546. controllerScope = scope.$parent;
  19547. }
  19548. if (boundTranscludeFn) {
  19549. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  19550. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  19551. transcludeFn = controllersBoundTransclude;
  19552. transcludeFn.$$boundTransclude = boundTranscludeFn;
  19553. // expose the slots on the `$transclude` function
  19554. transcludeFn.isSlotFilled = function(slotName) {
  19555. return !!boundTranscludeFn.$$slots[slotName];
  19556. };
  19557. }
  19558. if (controllerDirectives) {
  19559. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective);
  19560. }
  19561. if (newIsolateScopeDirective) {
  19562. // Initialize isolate scope bindings for new isolate scope directive.
  19563. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  19564. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  19565. compile.$$addScopeClass($element, true);
  19566. isolateScope.$$isolateBindings =
  19567. newIsolateScopeDirective.$$isolateBindings;
  19568. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  19569. isolateScope.$$isolateBindings,
  19570. newIsolateScopeDirective);
  19571. if (removeScopeBindingWatches) {
  19572. isolateScope.$on('$destroy', removeScopeBindingWatches);
  19573. }
  19574. }
  19575. // Initialize bindToController bindings
  19576. for (var name in elementControllers) {
  19577. var controllerDirective = controllerDirectives[name];
  19578. var controller = elementControllers[name];
  19579. var bindings = controllerDirective.$$bindings.bindToController;
  19580. if (controller.identifier && bindings) {
  19581. removeControllerBindingWatches =
  19582. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  19583. }
  19584. var controllerResult = controller();
  19585. if (controllerResult !== controller.instance) {
  19586. // If the controller constructor has a return value, overwrite the instance
  19587. // from setupControllers
  19588. controller.instance = controllerResult;
  19589. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  19590. removeControllerBindingWatches && removeControllerBindingWatches();
  19591. removeControllerBindingWatches =
  19592. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  19593. }
  19594. }
  19595. // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy
  19596. forEach(controllerDirectives, function(controllerDirective, name) {
  19597. var require = controllerDirective.require;
  19598. if (controllerDirective.bindToController && !isArray(require) && isObject(require)) {
  19599. extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers));
  19600. }
  19601. });
  19602. // Handle the init and destroy lifecycle hooks on all controllers that have them
  19603. forEach(elementControllers, function(controller) {
  19604. var controllerInstance = controller.instance;
  19605. if (isFunction(controllerInstance.$onInit)) {
  19606. controllerInstance.$onInit();
  19607. }
  19608. if (isFunction(controllerInstance.$onDestroy)) {
  19609. controllerScope.$on('$destroy', function callOnDestroyHook() {
  19610. controllerInstance.$onDestroy();
  19611. });
  19612. }
  19613. });
  19614. // PRELINKING
  19615. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  19616. linkFn = preLinkFns[i];
  19617. invokeLinkFn(linkFn,
  19618. linkFn.isolateScope ? isolateScope : scope,
  19619. $element,
  19620. attrs,
  19621. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  19622. transcludeFn
  19623. );
  19624. }
  19625. // RECURSION
  19626. // We only pass the isolate scope, if the isolate directive has a template,
  19627. // otherwise the child elements do not belong to the isolate directive.
  19628. var scopeToChild = scope;
  19629. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  19630. scopeToChild = isolateScope;
  19631. }
  19632. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  19633. // POSTLINKING
  19634. for (i = postLinkFns.length - 1; i >= 0; i--) {
  19635. linkFn = postLinkFns[i];
  19636. invokeLinkFn(linkFn,
  19637. linkFn.isolateScope ? isolateScope : scope,
  19638. $element,
  19639. attrs,
  19640. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  19641. transcludeFn
  19642. );
  19643. }
  19644. // Trigger $postLink lifecycle hooks
  19645. forEach(elementControllers, function(controller) {
  19646. var controllerInstance = controller.instance;
  19647. if (isFunction(controllerInstance.$postLink)) {
  19648. controllerInstance.$postLink();
  19649. }
  19650. });
  19651. // This is the function that is injected as `$transclude`.
  19652. // Note: all arguments are optional!
  19653. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) {
  19654. var transcludeControllers;
  19655. // No scope passed in:
  19656. if (!isScope(scope)) {
  19657. slotName = futureParentElement;
  19658. futureParentElement = cloneAttachFn;
  19659. cloneAttachFn = scope;
  19660. scope = undefined;
  19661. }
  19662. if (hasElementTranscludeDirective) {
  19663. transcludeControllers = elementControllers;
  19664. }
  19665. if (!futureParentElement) {
  19666. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  19667. }
  19668. if (slotName) {
  19669. // slotTranscludeFn can be one of three things:
  19670. // * a transclude function - a filled slot
  19671. // * `null` - an optional slot that was not filled
  19672. // * `undefined` - a slot that was not declared (i.e. invalid)
  19673. var slotTranscludeFn = boundTranscludeFn.$$slots[slotName];
  19674. if (slotTranscludeFn) {
  19675. return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  19676. } else if (isUndefined(slotTranscludeFn)) {
  19677. throw $compileMinErr('noslot',
  19678. 'No parent directive that requires a transclusion with slot name "{0}". ' +
  19679. 'Element: {1}',
  19680. slotName, startingTag($element));
  19681. }
  19682. } else {
  19683. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  19684. }
  19685. }
  19686. }
  19687. }
  19688. function getControllers(directiveName, require, $element, elementControllers) {
  19689. var value;
  19690. if (isString(require)) {
  19691. var match = require.match(REQUIRE_PREFIX_REGEXP);
  19692. var name = require.substring(match[0].length);
  19693. var inheritType = match[1] || match[3];
  19694. var optional = match[2] === '?';
  19695. //If only parents then start at the parent element
  19696. if (inheritType === '^^') {
  19697. $element = $element.parent();
  19698. //Otherwise attempt getting the controller from elementControllers in case
  19699. //the element is transcluded (and has no data) and to avoid .data if possible
  19700. } else {
  19701. value = elementControllers && elementControllers[name];
  19702. value = value && value.instance;
  19703. }
  19704. if (!value) {
  19705. var dataName = '$' + name + 'Controller';
  19706. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  19707. }
  19708. if (!value && !optional) {
  19709. throw $compileMinErr('ctreq',
  19710. "Controller '{0}', required by directive '{1}', can't be found!",
  19711. name, directiveName);
  19712. }
  19713. } else if (isArray(require)) {
  19714. value = [];
  19715. for (var i = 0, ii = require.length; i < ii; i++) {
  19716. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  19717. }
  19718. } else if (isObject(require)) {
  19719. value = {};
  19720. forEach(require, function(controller, property) {
  19721. value[property] = getControllers(directiveName, controller, $element, elementControllers);
  19722. });
  19723. }
  19724. return value || null;
  19725. }
  19726. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) {
  19727. var elementControllers = createMap();
  19728. for (var controllerKey in controllerDirectives) {
  19729. var directive = controllerDirectives[controllerKey];
  19730. var locals = {
  19731. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  19732. $element: $element,
  19733. $attrs: attrs,
  19734. $transclude: transcludeFn
  19735. };
  19736. var controller = directive.controller;
  19737. if (controller == '@') {
  19738. controller = attrs[directive.name];
  19739. }
  19740. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  19741. // For directives with element transclusion the element is a comment.
  19742. // In this case .data will not attach any data.
  19743. // Instead, we save the controllers for the element in a local hash and attach to .data
  19744. // later, once we have the actual element.
  19745. elementControllers[directive.name] = controllerInstance;
  19746. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  19747. }
  19748. return elementControllers;
  19749. }
  19750. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  19751. // or child scope created. For instance:
  19752. // * if the directive has been pulled into a template because another directive with a higher priority
  19753. // asked for element transclusion
  19754. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  19755. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  19756. function markDirectiveScope(directives, isolateScope, newScope) {
  19757. for (var j = 0, jj = directives.length; j < jj; j++) {
  19758. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  19759. }
  19760. }
  19761. /**
  19762. * looks up the directive and decorates it with exception handling and proper parameters. We
  19763. * call this the boundDirective.
  19764. *
  19765. * @param {string} name name of the directive to look up.
  19766. * @param {string} location The directive must be found in specific format.
  19767. * String containing any of theses characters:
  19768. *
  19769. * * `E`: element name
  19770. * * `A': attribute
  19771. * * `C`: class
  19772. * * `M`: comment
  19773. * @returns {boolean} true if directive was added.
  19774. */
  19775. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  19776. endAttrName) {
  19777. if (name === ignoreDirective) return null;
  19778. var match = null;
  19779. if (hasDirectives.hasOwnProperty(name)) {
  19780. for (var directive, directives = $injector.get(name + Suffix),
  19781. i = 0, ii = directives.length; i < ii; i++) {
  19782. try {
  19783. directive = directives[i];
  19784. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  19785. directive.restrict.indexOf(location) != -1) {
  19786. if (startAttrName) {
  19787. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  19788. }
  19789. if (!directive.$$bindings) {
  19790. var bindings = directive.$$bindings =
  19791. parseDirectiveBindings(directive, directive.name);
  19792. if (isObject(bindings.isolateScope)) {
  19793. directive.$$isolateBindings = bindings.isolateScope;
  19794. }
  19795. }
  19796. tDirectives.push(directive);
  19797. match = directive;
  19798. }
  19799. } catch (e) { $exceptionHandler(e); }
  19800. }
  19801. }
  19802. return match;
  19803. }
  19804. /**
  19805. * looks up the directive and returns true if it is a multi-element directive,
  19806. * and therefore requires DOM nodes between -start and -end markers to be grouped
  19807. * together.
  19808. *
  19809. * @param {string} name name of the directive to look up.
  19810. * @returns true if directive was registered as multi-element.
  19811. */
  19812. function directiveIsMultiElement(name) {
  19813. if (hasDirectives.hasOwnProperty(name)) {
  19814. for (var directive, directives = $injector.get(name + Suffix),
  19815. i = 0, ii = directives.length; i < ii; i++) {
  19816. directive = directives[i];
  19817. if (directive.multiElement) {
  19818. return true;
  19819. }
  19820. }
  19821. }
  19822. return false;
  19823. }
  19824. /**
  19825. * When the element is replaced with HTML template then the new attributes
  19826. * on the template need to be merged with the existing attributes in the DOM.
  19827. * The desired effect is to have both of the attributes present.
  19828. *
  19829. * @param {object} dst destination attributes (original DOM)
  19830. * @param {object} src source attributes (from the directive template)
  19831. */
  19832. function mergeTemplateAttributes(dst, src) {
  19833. var srcAttr = src.$attr,
  19834. dstAttr = dst.$attr,
  19835. $element = dst.$$element;
  19836. // reapply the old attributes to the new element
  19837. forEach(dst, function(value, key) {
  19838. if (key.charAt(0) != '$') {
  19839. if (src[key] && src[key] !== value) {
  19840. value += (key === 'style' ? ';' : ' ') + src[key];
  19841. }
  19842. dst.$set(key, value, true, srcAttr[key]);
  19843. }
  19844. });
  19845. // copy the new attributes on the old attrs object
  19846. forEach(src, function(value, key) {
  19847. if (key == 'class') {
  19848. safeAddClass($element, value);
  19849. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  19850. } else if (key == 'style') {
  19851. $element.attr('style', $element.attr('style') + ';' + value);
  19852. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  19853. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  19854. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  19855. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  19856. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  19857. dst[key] = value;
  19858. dstAttr[key] = srcAttr[key];
  19859. }
  19860. });
  19861. }
  19862. function compileTemplateUrl(directives, $compileNode, tAttrs,
  19863. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  19864. var linkQueue = [],
  19865. afterTemplateNodeLinkFn,
  19866. afterTemplateChildLinkFn,
  19867. beforeTemplateCompileNode = $compileNode[0],
  19868. origAsyncDirective = directives.shift(),
  19869. derivedSyncDirective = inherit(origAsyncDirective, {
  19870. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  19871. }),
  19872. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  19873. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  19874. : origAsyncDirective.templateUrl,
  19875. templateNamespace = origAsyncDirective.templateNamespace;
  19876. $compileNode.empty();
  19877. $templateRequest(templateUrl)
  19878. .then(function(content) {
  19879. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  19880. content = denormalizeTemplate(content);
  19881. if (origAsyncDirective.replace) {
  19882. if (jqLiteIsTextNode(content)) {
  19883. $template = [];
  19884. } else {
  19885. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  19886. }
  19887. compileNode = $template[0];
  19888. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  19889. throw $compileMinErr('tplrt',
  19890. "Template for directive '{0}' must have exactly one root element. {1}",
  19891. origAsyncDirective.name, templateUrl);
  19892. }
  19893. tempTemplateAttrs = {$attr: {}};
  19894. replaceWith($rootElement, $compileNode, compileNode);
  19895. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  19896. if (isObject(origAsyncDirective.scope)) {
  19897. // the original directive that caused the template to be loaded async required
  19898. // an isolate scope
  19899. markDirectiveScope(templateDirectives, true);
  19900. }
  19901. directives = templateDirectives.concat(directives);
  19902. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  19903. } else {
  19904. compileNode = beforeTemplateCompileNode;
  19905. $compileNode.html(content);
  19906. }
  19907. directives.unshift(derivedSyncDirective);
  19908. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  19909. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  19910. previousCompileContext);
  19911. forEach($rootElement, function(node, i) {
  19912. if (node == compileNode) {
  19913. $rootElement[i] = $compileNode[0];
  19914. }
  19915. });
  19916. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  19917. while (linkQueue.length) {
  19918. var scope = linkQueue.shift(),
  19919. beforeTemplateLinkNode = linkQueue.shift(),
  19920. linkRootElement = linkQueue.shift(),
  19921. boundTranscludeFn = linkQueue.shift(),
  19922. linkNode = $compileNode[0];
  19923. if (scope.$$destroyed) continue;
  19924. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  19925. var oldClasses = beforeTemplateLinkNode.className;
  19926. if (!(previousCompileContext.hasElementTranscludeDirective &&
  19927. origAsyncDirective.replace)) {
  19928. // it was cloned therefore we have to clone as well.
  19929. linkNode = jqLiteClone(compileNode);
  19930. }
  19931. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  19932. // Copy in CSS classes from original node
  19933. safeAddClass(jqLite(linkNode), oldClasses);
  19934. }
  19935. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  19936. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  19937. } else {
  19938. childBoundTranscludeFn = boundTranscludeFn;
  19939. }
  19940. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  19941. childBoundTranscludeFn);
  19942. }
  19943. linkQueue = null;
  19944. });
  19945. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  19946. var childBoundTranscludeFn = boundTranscludeFn;
  19947. if (scope.$$destroyed) return;
  19948. if (linkQueue) {
  19949. linkQueue.push(scope,
  19950. node,
  19951. rootElement,
  19952. childBoundTranscludeFn);
  19953. } else {
  19954. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  19955. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  19956. }
  19957. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  19958. }
  19959. };
  19960. }
  19961. /**
  19962. * Sorting function for bound directives.
  19963. */
  19964. function byPriority(a, b) {
  19965. var diff = b.priority - a.priority;
  19966. if (diff !== 0) return diff;
  19967. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  19968. return a.index - b.index;
  19969. }
  19970. function assertNoDuplicate(what, previousDirective, directive, element) {
  19971. function wrapModuleNameIfDefined(moduleName) {
  19972. return moduleName ?
  19973. (' (module: ' + moduleName + ')') :
  19974. '';
  19975. }
  19976. if (previousDirective) {
  19977. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  19978. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  19979. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  19980. }
  19981. }
  19982. function addTextInterpolateDirective(directives, text) {
  19983. var interpolateFn = $interpolate(text, true);
  19984. if (interpolateFn) {
  19985. directives.push({
  19986. priority: 0,
  19987. compile: function textInterpolateCompileFn(templateNode) {
  19988. var templateNodeParent = templateNode.parent(),
  19989. hasCompileParent = !!templateNodeParent.length;
  19990. // When transcluding a template that has bindings in the root
  19991. // we don't have a parent and thus need to add the class during linking fn.
  19992. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  19993. return function textInterpolateLinkFn(scope, node) {
  19994. var parent = node.parent();
  19995. if (!hasCompileParent) compile.$$addBindingClass(parent);
  19996. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  19997. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  19998. node[0].nodeValue = value;
  19999. });
  20000. };
  20001. }
  20002. });
  20003. }
  20004. }
  20005. function wrapTemplate(type, template) {
  20006. type = lowercase(type || 'html');
  20007. switch (type) {
  20008. case 'svg':
  20009. case 'math':
  20010. var wrapper = document.createElement('div');
  20011. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  20012. return wrapper.childNodes[0].childNodes;
  20013. default:
  20014. return template;
  20015. }
  20016. }
  20017. function getTrustedContext(node, attrNormalizedName) {
  20018. if (attrNormalizedName == "srcdoc") {
  20019. return $sce.HTML;
  20020. }
  20021. var tag = nodeName_(node);
  20022. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  20023. if (attrNormalizedName == "xlinkHref" ||
  20024. (tag == "form" && attrNormalizedName == "action") ||
  20025. (tag != "img" && (attrNormalizedName == "src" ||
  20026. attrNormalizedName == "ngSrc"))) {
  20027. return $sce.RESOURCE_URL;
  20028. }
  20029. }
  20030. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  20031. var trustedContext = getTrustedContext(node, name);
  20032. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  20033. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  20034. // no interpolation found -> ignore
  20035. if (!interpolateFn) return;
  20036. if (name === "multiple" && nodeName_(node) === "select") {
  20037. throw $compileMinErr("selmulti",
  20038. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  20039. startingTag(node));
  20040. }
  20041. directives.push({
  20042. priority: 100,
  20043. compile: function() {
  20044. return {
  20045. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  20046. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  20047. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  20048. throw $compileMinErr('nodomevents',
  20049. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  20050. "ng- versions (such as ng-click instead of onclick) instead.");
  20051. }
  20052. // If the attribute has changed since last $interpolate()ed
  20053. var newValue = attr[name];
  20054. if (newValue !== value) {
  20055. // we need to interpolate again since the attribute value has been updated
  20056. // (e.g. by another directive's compile function)
  20057. // ensure unset/empty values make interpolateFn falsy
  20058. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  20059. value = newValue;
  20060. }
  20061. // if attribute was updated so that there is no interpolation going on we don't want to
  20062. // register any observers
  20063. if (!interpolateFn) return;
  20064. // initialize attr object so that it's ready in case we need the value for isolate
  20065. // scope initialization, otherwise the value would not be available from isolate
  20066. // directive's linking fn during linking phase
  20067. attr[name] = interpolateFn(scope);
  20068. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  20069. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  20070. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  20071. //special case for class attribute addition + removal
  20072. //so that class changes can tap into the animation
  20073. //hooks provided by the $animate service. Be sure to
  20074. //skip animations when the first digest occurs (when
  20075. //both the new and the old values are the same) since
  20076. //the CSS classes are the non-interpolated values
  20077. if (name === 'class' && newValue != oldValue) {
  20078. attr.$updateClass(newValue, oldValue);
  20079. } else {
  20080. attr.$set(name, newValue);
  20081. }
  20082. });
  20083. }
  20084. };
  20085. }
  20086. });
  20087. }
  20088. /**
  20089. * This is a special jqLite.replaceWith, which can replace items which
  20090. * have no parents, provided that the containing jqLite collection is provided.
  20091. *
  20092. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  20093. * in the root of the tree.
  20094. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  20095. * the shell, but replace its DOM node reference.
  20096. * @param {Node} newNode The new DOM node.
  20097. */
  20098. function replaceWith($rootElement, elementsToRemove, newNode) {
  20099. var firstElementToRemove = elementsToRemove[0],
  20100. removeCount = elementsToRemove.length,
  20101. parent = firstElementToRemove.parentNode,
  20102. i, ii;
  20103. if ($rootElement) {
  20104. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  20105. if ($rootElement[i] == firstElementToRemove) {
  20106. $rootElement[i++] = newNode;
  20107. for (var j = i, j2 = j + removeCount - 1,
  20108. jj = $rootElement.length;
  20109. j < jj; j++, j2++) {
  20110. if (j2 < jj) {
  20111. $rootElement[j] = $rootElement[j2];
  20112. } else {
  20113. delete $rootElement[j];
  20114. }
  20115. }
  20116. $rootElement.length -= removeCount - 1;
  20117. // If the replaced element is also the jQuery .context then replace it
  20118. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  20119. // http://api.jquery.com/context/
  20120. if ($rootElement.context === firstElementToRemove) {
  20121. $rootElement.context = newNode;
  20122. }
  20123. break;
  20124. }
  20125. }
  20126. }
  20127. if (parent) {
  20128. parent.replaceChild(newNode, firstElementToRemove);
  20129. }
  20130. // Append all the `elementsToRemove` to a fragment. This will...
  20131. // - remove them from the DOM
  20132. // - allow them to still be traversed with .nextSibling
  20133. // - allow a single fragment.qSA to fetch all elements being removed
  20134. var fragment = document.createDocumentFragment();
  20135. for (i = 0; i < removeCount; i++) {
  20136. fragment.appendChild(elementsToRemove[i]);
  20137. }
  20138. if (jqLite.hasData(firstElementToRemove)) {
  20139. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  20140. // data here because there's no public interface in jQuery to do that and copying over
  20141. // event listeners (which is the main use of private data) wouldn't work anyway.
  20142. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  20143. // Remove $destroy event listeners from `firstElementToRemove`
  20144. jqLite(firstElementToRemove).off('$destroy');
  20145. }
  20146. // Cleanup any data/listeners on the elements and children.
  20147. // This includes invoking the $destroy event on any elements with listeners.
  20148. jqLite.cleanData(fragment.querySelectorAll('*'));
  20149. // Update the jqLite collection to only contain the `newNode`
  20150. for (i = 1; i < removeCount; i++) {
  20151. delete elementsToRemove[i];
  20152. }
  20153. elementsToRemove[0] = newNode;
  20154. elementsToRemove.length = 1;
  20155. }
  20156. function cloneAndAnnotateFn(fn, annotation) {
  20157. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  20158. }
  20159. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  20160. try {
  20161. linkFn(scope, $element, attrs, controllers, transcludeFn);
  20162. } catch (e) {
  20163. $exceptionHandler(e, startingTag($element));
  20164. }
  20165. }
  20166. // Set up $watches for isolate scope and controller bindings. This process
  20167. // only occurs for isolate scopes and new scopes with controllerAs.
  20168. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  20169. var removeWatchCollection = [];
  20170. var changes;
  20171. forEach(bindings, function initializeBinding(definition, scopeName) {
  20172. var attrName = definition.attrName,
  20173. optional = definition.optional,
  20174. mode = definition.mode, // @, =, or &
  20175. lastValue,
  20176. parentGet, parentSet, compare, removeWatch;
  20177. switch (mode) {
  20178. case '@':
  20179. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  20180. destination[scopeName] = attrs[attrName] = void 0;
  20181. }
  20182. attrs.$observe(attrName, function(value) {
  20183. if (isString(value)) {
  20184. var oldValue = destination[scopeName];
  20185. recordChanges(scopeName, value, oldValue);
  20186. destination[scopeName] = value;
  20187. }
  20188. });
  20189. attrs.$$observers[attrName].$$scope = scope;
  20190. lastValue = attrs[attrName];
  20191. if (isString(lastValue)) {
  20192. // If the attribute has been provided then we trigger an interpolation to ensure
  20193. // the value is there for use in the link fn
  20194. destination[scopeName] = $interpolate(lastValue)(scope);
  20195. } else if (isBoolean(lastValue)) {
  20196. // If the attributes is one of the BOOLEAN_ATTR then Angular will have converted
  20197. // the value to boolean rather than a string, so we special case this situation
  20198. destination[scopeName] = lastValue;
  20199. }
  20200. break;
  20201. case '=':
  20202. if (!hasOwnProperty.call(attrs, attrName)) {
  20203. if (optional) break;
  20204. attrs[attrName] = void 0;
  20205. }
  20206. if (optional && !attrs[attrName]) break;
  20207. parentGet = $parse(attrs[attrName]);
  20208. if (parentGet.literal) {
  20209. compare = equals;
  20210. } else {
  20211. compare = function simpleCompare(a, b) { return a === b || (a !== a && b !== b); };
  20212. }
  20213. parentSet = parentGet.assign || function() {
  20214. // reset the change, or we will throw this exception on every $digest
  20215. lastValue = destination[scopeName] = parentGet(scope);
  20216. throw $compileMinErr('nonassign',
  20217. "Expression '{0}' in attribute '{1}' used with directive '{2}' is non-assignable!",
  20218. attrs[attrName], attrName, directive.name);
  20219. };
  20220. lastValue = destination[scopeName] = parentGet(scope);
  20221. var parentValueWatch = function parentValueWatch(parentValue) {
  20222. if (!compare(parentValue, destination[scopeName])) {
  20223. // we are out of sync and need to copy
  20224. if (!compare(parentValue, lastValue)) {
  20225. // parent changed and it has precedence
  20226. destination[scopeName] = parentValue;
  20227. } else {
  20228. // if the parent can be assigned then do so
  20229. parentSet(scope, parentValue = destination[scopeName]);
  20230. }
  20231. }
  20232. return lastValue = parentValue;
  20233. };
  20234. parentValueWatch.$stateful = true;
  20235. if (definition.collection) {
  20236. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  20237. } else {
  20238. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  20239. }
  20240. removeWatchCollection.push(removeWatch);
  20241. break;
  20242. case '<':
  20243. if (!hasOwnProperty.call(attrs, attrName)) {
  20244. if (optional) break;
  20245. attrs[attrName] = void 0;
  20246. }
  20247. if (optional && !attrs[attrName]) break;
  20248. parentGet = $parse(attrs[attrName]);
  20249. destination[scopeName] = parentGet(scope);
  20250. removeWatch = scope.$watch(parentGet, function parentValueWatchAction(newParentValue) {
  20251. var oldValue = destination[scopeName];
  20252. recordChanges(scopeName, newParentValue, oldValue);
  20253. destination[scopeName] = newParentValue;
  20254. }, parentGet.literal);
  20255. removeWatchCollection.push(removeWatch);
  20256. break;
  20257. case '&':
  20258. // Don't assign Object.prototype method to scope
  20259. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  20260. // Don't assign noop to destination if expression is not valid
  20261. if (parentGet === noop && optional) break;
  20262. destination[scopeName] = function(locals) {
  20263. return parentGet(scope, locals);
  20264. };
  20265. break;
  20266. }
  20267. });
  20268. function recordChanges(key, currentValue, previousValue) {
  20269. if (isFunction(destination.$onChanges) && currentValue !== previousValue) {
  20270. // If we have not already scheduled the top level onChangesQueue handler then do so now
  20271. if (!onChangesQueue) {
  20272. scope.$$postDigest(flushOnChangesQueue);
  20273. onChangesQueue = [];
  20274. }
  20275. // If we have not already queued a trigger of onChanges for this controller then do so now
  20276. if (!changes) {
  20277. changes = {};
  20278. onChangesQueue.push(triggerOnChangesHook);
  20279. }
  20280. // If the has been a change on this property already then we need to reuse the previous value
  20281. if (changes[key]) {
  20282. previousValue = changes[key].previousValue;
  20283. }
  20284. // Store this change
  20285. changes[key] = {previousValue: previousValue, currentValue: currentValue};
  20286. }
  20287. }
  20288. function triggerOnChangesHook() {
  20289. destination.$onChanges(changes);
  20290. // Now clear the changes so that we schedule onChanges when more changes arrive
  20291. changes = undefined;
  20292. }
  20293. return removeWatchCollection.length && function removeWatches() {
  20294. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  20295. removeWatchCollection[i]();
  20296. }
  20297. };
  20298. }
  20299. }];
  20300. }
  20301. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  20302. /**
  20303. * Converts all accepted directives format into proper directive name.
  20304. * @param name Name to normalize
  20305. */
  20306. function directiveNormalize(name) {
  20307. return camelCase(name.replace(PREFIX_REGEXP, ''));
  20308. }
  20309. /**
  20310. * @ngdoc type
  20311. * @name $compile.directive.Attributes
  20312. *
  20313. * @description
  20314. * A shared object between directive compile / linking functions which contains normalized DOM
  20315. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  20316. * needed since all of these are treated as equivalent in Angular:
  20317. *
  20318. * ```
  20319. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  20320. * ```
  20321. */
  20322. /**
  20323. * @ngdoc property
  20324. * @name $compile.directive.Attributes#$attr
  20325. *
  20326. * @description
  20327. * A map of DOM element attribute names to the normalized name. This is
  20328. * needed to do reverse lookup from normalized name back to actual name.
  20329. */
  20330. /**
  20331. * @ngdoc method
  20332. * @name $compile.directive.Attributes#$set
  20333. * @kind function
  20334. *
  20335. * @description
  20336. * Set DOM element attribute value.
  20337. *
  20338. *
  20339. * @param {string} name Normalized element attribute name of the property to modify. The name is
  20340. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  20341. * property to the original name.
  20342. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  20343. */
  20344. /**
  20345. * Closure compiler type information
  20346. */
  20347. function nodesetLinkingFn(
  20348. /* angular.Scope */ scope,
  20349. /* NodeList */ nodeList,
  20350. /* Element */ rootElement,
  20351. /* function(Function) */ boundTranscludeFn
  20352. ) {}
  20353. function directiveLinkingFn(
  20354. /* nodesetLinkingFn */ nodesetLinkingFn,
  20355. /* angular.Scope */ scope,
  20356. /* Node */ node,
  20357. /* Element */ rootElement,
  20358. /* function(Function) */ boundTranscludeFn
  20359. ) {}
  20360. function tokenDifference(str1, str2) {
  20361. var values = '',
  20362. tokens1 = str1.split(/\s+/),
  20363. tokens2 = str2.split(/\s+/);
  20364. outer:
  20365. for (var i = 0; i < tokens1.length; i++) {
  20366. var token = tokens1[i];
  20367. for (var j = 0; j < tokens2.length; j++) {
  20368. if (token == tokens2[j]) continue outer;
  20369. }
  20370. values += (values.length > 0 ? ' ' : '') + token;
  20371. }
  20372. return values;
  20373. }
  20374. function removeComments(jqNodes) {
  20375. jqNodes = jqLite(jqNodes);
  20376. var i = jqNodes.length;
  20377. if (i <= 1) {
  20378. return jqNodes;
  20379. }
  20380. while (i--) {
  20381. var node = jqNodes[i];
  20382. if (node.nodeType === NODE_TYPE_COMMENT) {
  20383. splice.call(jqNodes, i, 1);
  20384. }
  20385. }
  20386. return jqNodes;
  20387. }
  20388. var $controllerMinErr = minErr('$controller');
  20389. var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/;
  20390. function identifierForController(controller, ident) {
  20391. if (ident && isString(ident)) return ident;
  20392. if (isString(controller)) {
  20393. var match = CNTRL_REG.exec(controller);
  20394. if (match) return match[3];
  20395. }
  20396. }
  20397. /**
  20398. * @ngdoc provider
  20399. * @name $controllerProvider
  20400. * @description
  20401. * The {@link ng.$controller $controller service} is used by Angular to create new
  20402. * controllers.
  20403. *
  20404. * This provider allows controller registration via the
  20405. * {@link ng.$controllerProvider#register register} method.
  20406. */
  20407. function $ControllerProvider() {
  20408. var controllers = {},
  20409. globals = false;
  20410. /**
  20411. * @ngdoc method
  20412. * @name $controllerProvider#has
  20413. * @param {string} name Controller name to check.
  20414. */
  20415. this.has = function(name) {
  20416. return controllers.hasOwnProperty(name);
  20417. };
  20418. /**
  20419. * @ngdoc method
  20420. * @name $controllerProvider#register
  20421. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  20422. * the names and the values are the constructors.
  20423. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  20424. * annotations in the array notation).
  20425. */
  20426. this.register = function(name, constructor) {
  20427. assertNotHasOwnProperty(name, 'controller');
  20428. if (isObject(name)) {
  20429. extend(controllers, name);
  20430. } else {
  20431. controllers[name] = constructor;
  20432. }
  20433. };
  20434. /**
  20435. * @ngdoc method
  20436. * @name $controllerProvider#allowGlobals
  20437. * @description If called, allows `$controller` to find controller constructors on `window`
  20438. */
  20439. this.allowGlobals = function() {
  20440. globals = true;
  20441. };
  20442. this.$get = ['$injector', '$window', function($injector, $window) {
  20443. /**
  20444. * @ngdoc service
  20445. * @name $controller
  20446. * @requires $injector
  20447. *
  20448. * @param {Function|string} constructor If called with a function then it's considered to be the
  20449. * controller constructor function. Otherwise it's considered to be a string which is used
  20450. * to retrieve the controller constructor using the following steps:
  20451. *
  20452. * * check if a controller with given name is registered via `$controllerProvider`
  20453. * * check if evaluating the string on the current scope returns a constructor
  20454. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  20455. * `window` object (not recommended)
  20456. *
  20457. * The string can use the `controller as property` syntax, where the controller instance is published
  20458. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  20459. * to work correctly.
  20460. *
  20461. * @param {Object} locals Injection locals for Controller.
  20462. * @return {Object} Instance of given controller.
  20463. *
  20464. * @description
  20465. * `$controller` service is responsible for instantiating controllers.
  20466. *
  20467. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  20468. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  20469. */
  20470. return function $controller(expression, locals, later, ident) {
  20471. // PRIVATE API:
  20472. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  20473. // If true, $controller will allocate the object with the correct
  20474. // prototype chain, but will not invoke the controller until a returned
  20475. // callback is invoked.
  20476. // param `ident` --- An optional label which overrides the label parsed from the controller
  20477. // expression, if any.
  20478. var instance, match, constructor, identifier;
  20479. later = later === true;
  20480. if (ident && isString(ident)) {
  20481. identifier = ident;
  20482. }
  20483. if (isString(expression)) {
  20484. match = expression.match(CNTRL_REG);
  20485. if (!match) {
  20486. throw $controllerMinErr('ctrlfmt',
  20487. "Badly formed controller string '{0}'. " +
  20488. "Must match `__name__ as __id__` or `__name__`.", expression);
  20489. }
  20490. constructor = match[1],
  20491. identifier = identifier || match[3];
  20492. expression = controllers.hasOwnProperty(constructor)
  20493. ? controllers[constructor]
  20494. : getter(locals.$scope, constructor, true) ||
  20495. (globals ? getter($window, constructor, true) : undefined);
  20496. assertArgFn(expression, constructor, true);
  20497. }
  20498. if (later) {
  20499. // Instantiate controller later:
  20500. // This machinery is used to create an instance of the object before calling the
  20501. // controller's constructor itself.
  20502. //
  20503. // This allows properties to be added to the controller before the constructor is
  20504. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  20505. //
  20506. // This feature is not intended for use by applications, and is thus not documented
  20507. // publicly.
  20508. // Object creation: http://jsperf.com/create-constructor/2
  20509. var controllerPrototype = (isArray(expression) ?
  20510. expression[expression.length - 1] : expression).prototype;
  20511. instance = Object.create(controllerPrototype || null);
  20512. if (identifier) {
  20513. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20514. }
  20515. var instantiate;
  20516. return instantiate = extend(function $controllerInit() {
  20517. var result = $injector.invoke(expression, instance, locals, constructor);
  20518. if (result !== instance && (isObject(result) || isFunction(result))) {
  20519. instance = result;
  20520. if (identifier) {
  20521. // If result changed, re-assign controllerAs value to scope.
  20522. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20523. }
  20524. }
  20525. return instance;
  20526. }, {
  20527. instance: instance,
  20528. identifier: identifier
  20529. });
  20530. }
  20531. instance = $injector.instantiate(expression, locals, constructor);
  20532. if (identifier) {
  20533. addIdentifier(locals, identifier, instance, constructor || expression.name);
  20534. }
  20535. return instance;
  20536. };
  20537. function addIdentifier(locals, identifier, instance, name) {
  20538. if (!(locals && isObject(locals.$scope))) {
  20539. throw minErr('$controller')('noscp',
  20540. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  20541. name, identifier);
  20542. }
  20543. locals.$scope[identifier] = instance;
  20544. }
  20545. }];
  20546. }
  20547. /**
  20548. * @ngdoc service
  20549. * @name $document
  20550. * @requires $window
  20551. *
  20552. * @description
  20553. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  20554. *
  20555. * @example
  20556. <example module="documentExample">
  20557. <file name="index.html">
  20558. <div ng-controller="ExampleController">
  20559. <p>$document title: <b ng-bind="title"></b></p>
  20560. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  20561. </div>
  20562. </file>
  20563. <file name="script.js">
  20564. angular.module('documentExample', [])
  20565. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  20566. $scope.title = $document[0].title;
  20567. $scope.windowTitle = angular.element(window.document)[0].title;
  20568. }]);
  20569. </file>
  20570. </example>
  20571. */
  20572. function $DocumentProvider() {
  20573. this.$get = ['$window', function(window) {
  20574. return jqLite(window.document);
  20575. }];
  20576. }
  20577. /**
  20578. * @ngdoc service
  20579. * @name $exceptionHandler
  20580. * @requires ng.$log
  20581. *
  20582. * @description
  20583. * Any uncaught exception in angular expressions is delegated to this service.
  20584. * The default implementation simply delegates to `$log.error` which logs it into
  20585. * the browser console.
  20586. *
  20587. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  20588. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  20589. *
  20590. * ## Example:
  20591. *
  20592. * ```js
  20593. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  20594. * return function(exception, cause) {
  20595. * exception.message += ' (caused by "' + cause + '")';
  20596. * throw exception;
  20597. * };
  20598. * });
  20599. * ```
  20600. *
  20601. * This example will override the normal action of `$exceptionHandler`, to make angular
  20602. * exceptions fail hard when they happen, instead of just logging to the console.
  20603. *
  20604. * <hr />
  20605. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  20606. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  20607. * (unless executed during a digest).
  20608. *
  20609. * If you wish, you can manually delegate exceptions, e.g.
  20610. * `try { ... } catch(e) { $exceptionHandler(e); }`
  20611. *
  20612. * @param {Error} exception Exception associated with the error.
  20613. * @param {string=} cause optional information about the context in which
  20614. * the error was thrown.
  20615. *
  20616. */
  20617. function $ExceptionHandlerProvider() {
  20618. this.$get = ['$log', function($log) {
  20619. return function(exception, cause) {
  20620. $log.error.apply($log, arguments);
  20621. };
  20622. }];
  20623. }
  20624. var $$ForceReflowProvider = function() {
  20625. this.$get = ['$document', function($document) {
  20626. return function(domNode) {
  20627. //the line below will force the browser to perform a repaint so
  20628. //that all the animated elements within the animation frame will
  20629. //be properly updated and drawn on screen. This is required to
  20630. //ensure that the preparation animation is properly flushed so that
  20631. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  20632. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  20633. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  20634. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  20635. if (domNode) {
  20636. if (!domNode.nodeType && domNode instanceof jqLite) {
  20637. domNode = domNode[0];
  20638. }
  20639. } else {
  20640. domNode = $document[0].body;
  20641. }
  20642. return domNode.offsetWidth + 1;
  20643. };
  20644. }];
  20645. };
  20646. var APPLICATION_JSON = 'application/json';
  20647. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  20648. var JSON_START = /^\[|^\{(?!\{)/;
  20649. var JSON_ENDS = {
  20650. '[': /]$/,
  20651. '{': /}$/
  20652. };
  20653. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  20654. var $httpMinErr = minErr('$http');
  20655. var $httpMinErrLegacyFn = function(method) {
  20656. return function() {
  20657. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  20658. };
  20659. };
  20660. function serializeValue(v) {
  20661. if (isObject(v)) {
  20662. return isDate(v) ? v.toISOString() : toJson(v);
  20663. }
  20664. return v;
  20665. }
  20666. function $HttpParamSerializerProvider() {
  20667. /**
  20668. * @ngdoc service
  20669. * @name $httpParamSerializer
  20670. * @description
  20671. *
  20672. * Default {@link $http `$http`} params serializer that converts objects to strings
  20673. * according to the following rules:
  20674. *
  20675. * * `{'foo': 'bar'}` results in `foo=bar`
  20676. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  20677. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  20678. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  20679. *
  20680. * Note that serializer will sort the request parameters alphabetically.
  20681. * */
  20682. this.$get = function() {
  20683. return function ngParamSerializer(params) {
  20684. if (!params) return '';
  20685. var parts = [];
  20686. forEachSorted(params, function(value, key) {
  20687. if (value === null || isUndefined(value)) return;
  20688. if (isArray(value)) {
  20689. forEach(value, function(v) {
  20690. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  20691. });
  20692. } else {
  20693. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  20694. }
  20695. });
  20696. return parts.join('&');
  20697. };
  20698. };
  20699. }
  20700. function $HttpParamSerializerJQLikeProvider() {
  20701. /**
  20702. * @ngdoc service
  20703. * @name $httpParamSerializerJQLike
  20704. * @description
  20705. *
  20706. * Alternative {@link $http `$http`} params serializer that follows
  20707. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  20708. * The serializer will also sort the params alphabetically.
  20709. *
  20710. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  20711. *
  20712. * ```js
  20713. * $http({
  20714. * url: myUrl,
  20715. * method: 'GET',
  20716. * params: myParams,
  20717. * paramSerializer: '$httpParamSerializerJQLike'
  20718. * });
  20719. * ```
  20720. *
  20721. * It is also possible to set it as the default `paramSerializer` in the
  20722. * {@link $httpProvider#defaults `$httpProvider`}.
  20723. *
  20724. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  20725. * form data for submission:
  20726. *
  20727. * ```js
  20728. * .controller(function($http, $httpParamSerializerJQLike) {
  20729. * //...
  20730. *
  20731. * $http({
  20732. * url: myUrl,
  20733. * method: 'POST',
  20734. * data: $httpParamSerializerJQLike(myData),
  20735. * headers: {
  20736. * 'Content-Type': 'application/x-www-form-urlencoded'
  20737. * }
  20738. * });
  20739. *
  20740. * });
  20741. * ```
  20742. *
  20743. * */
  20744. this.$get = function() {
  20745. return function jQueryLikeParamSerializer(params) {
  20746. if (!params) return '';
  20747. var parts = [];
  20748. serialize(params, '', true);
  20749. return parts.join('&');
  20750. function serialize(toSerialize, prefix, topLevel) {
  20751. if (toSerialize === null || isUndefined(toSerialize)) return;
  20752. if (isArray(toSerialize)) {
  20753. forEach(toSerialize, function(value, index) {
  20754. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  20755. });
  20756. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  20757. forEachSorted(toSerialize, function(value, key) {
  20758. serialize(value, prefix +
  20759. (topLevel ? '' : '[') +
  20760. key +
  20761. (topLevel ? '' : ']'));
  20762. });
  20763. } else {
  20764. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  20765. }
  20766. }
  20767. };
  20768. };
  20769. }
  20770. function defaultHttpResponseTransform(data, headers) {
  20771. if (isString(data)) {
  20772. // Strip json vulnerability protection prefix and trim whitespace
  20773. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  20774. if (tempData) {
  20775. var contentType = headers('Content-Type');
  20776. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  20777. data = fromJson(tempData);
  20778. }
  20779. }
  20780. }
  20781. return data;
  20782. }
  20783. function isJsonLike(str) {
  20784. var jsonStart = str.match(JSON_START);
  20785. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  20786. }
  20787. /**
  20788. * Parse headers into key value object
  20789. *
  20790. * @param {string} headers Raw headers as a string
  20791. * @returns {Object} Parsed headers as key value object
  20792. */
  20793. function parseHeaders(headers) {
  20794. var parsed = createMap(), i;
  20795. function fillInParsed(key, val) {
  20796. if (key) {
  20797. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  20798. }
  20799. }
  20800. if (isString(headers)) {
  20801. forEach(headers.split('\n'), function(line) {
  20802. i = line.indexOf(':');
  20803. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  20804. });
  20805. } else if (isObject(headers)) {
  20806. forEach(headers, function(headerVal, headerKey) {
  20807. fillInParsed(lowercase(headerKey), trim(headerVal));
  20808. });
  20809. }
  20810. return parsed;
  20811. }
  20812. /**
  20813. * Returns a function that provides access to parsed headers.
  20814. *
  20815. * Headers are lazy parsed when first requested.
  20816. * @see parseHeaders
  20817. *
  20818. * @param {(string|Object)} headers Headers to provide access to.
  20819. * @returns {function(string=)} Returns a getter function which if called with:
  20820. *
  20821. * - if called with single an argument returns a single header value or null
  20822. * - if called with no arguments returns an object containing all headers.
  20823. */
  20824. function headersGetter(headers) {
  20825. var headersObj;
  20826. return function(name) {
  20827. if (!headersObj) headersObj = parseHeaders(headers);
  20828. if (name) {
  20829. var value = headersObj[lowercase(name)];
  20830. if (value === void 0) {
  20831. value = null;
  20832. }
  20833. return value;
  20834. }
  20835. return headersObj;
  20836. };
  20837. }
  20838. /**
  20839. * Chain all given functions
  20840. *
  20841. * This function is used for both request and response transforming
  20842. *
  20843. * @param {*} data Data to transform.
  20844. * @param {function(string=)} headers HTTP headers getter fn.
  20845. * @param {number} status HTTP status code of the response.
  20846. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  20847. * @returns {*} Transformed data.
  20848. */
  20849. function transformData(data, headers, status, fns) {
  20850. if (isFunction(fns)) {
  20851. return fns(data, headers, status);
  20852. }
  20853. forEach(fns, function(fn) {
  20854. data = fn(data, headers, status);
  20855. });
  20856. return data;
  20857. }
  20858. function isSuccess(status) {
  20859. return 200 <= status && status < 300;
  20860. }
  20861. /**
  20862. * @ngdoc provider
  20863. * @name $httpProvider
  20864. * @description
  20865. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  20866. * */
  20867. function $HttpProvider() {
  20868. /**
  20869. * @ngdoc property
  20870. * @name $httpProvider#defaults
  20871. * @description
  20872. *
  20873. * Object containing default values for all {@link ng.$http $http} requests.
  20874. *
  20875. * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with
  20876. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses
  20877. * by default. See {@link $http#caching $http Caching} for more information.
  20878. *
  20879. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  20880. * Defaults value is `'XSRF-TOKEN'`.
  20881. *
  20882. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  20883. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  20884. *
  20885. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  20886. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  20887. * setting default headers.
  20888. * - **`defaults.headers.common`**
  20889. * - **`defaults.headers.post`**
  20890. * - **`defaults.headers.put`**
  20891. * - **`defaults.headers.patch`**
  20892. *
  20893. *
  20894. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  20895. * used to the prepare string representation of request parameters (specified as an object).
  20896. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  20897. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  20898. *
  20899. **/
  20900. var defaults = this.defaults = {
  20901. // transform incoming response data
  20902. transformResponse: [defaultHttpResponseTransform],
  20903. // transform outgoing request data
  20904. transformRequest: [function(d) {
  20905. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  20906. }],
  20907. // default headers
  20908. headers: {
  20909. common: {
  20910. 'Accept': 'application/json, text/plain, */*'
  20911. },
  20912. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  20913. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  20914. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  20915. },
  20916. xsrfCookieName: 'XSRF-TOKEN',
  20917. xsrfHeaderName: 'X-XSRF-TOKEN',
  20918. paramSerializer: '$httpParamSerializer'
  20919. };
  20920. var useApplyAsync = false;
  20921. /**
  20922. * @ngdoc method
  20923. * @name $httpProvider#useApplyAsync
  20924. * @description
  20925. *
  20926. * Configure $http service to combine processing of multiple http responses received at around
  20927. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  20928. * significant performance improvement for bigger applications that make many HTTP requests
  20929. * concurrently (common during application bootstrap).
  20930. *
  20931. * Defaults to false. If no value is specified, returns the current configured value.
  20932. *
  20933. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  20934. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  20935. * to load and share the same digest cycle.
  20936. *
  20937. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  20938. * otherwise, returns the current configured value.
  20939. **/
  20940. this.useApplyAsync = function(value) {
  20941. if (isDefined(value)) {
  20942. useApplyAsync = !!value;
  20943. return this;
  20944. }
  20945. return useApplyAsync;
  20946. };
  20947. var useLegacyPromise = true;
  20948. /**
  20949. * @ngdoc method
  20950. * @name $httpProvider#useLegacyPromiseExtensions
  20951. * @description
  20952. *
  20953. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  20954. * This should be used to make sure that applications work without these methods.
  20955. *
  20956. * Defaults to true. If no value is specified, returns the current configured value.
  20957. *
  20958. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  20959. *
  20960. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  20961. * otherwise, returns the current configured value.
  20962. **/
  20963. this.useLegacyPromiseExtensions = function(value) {
  20964. if (isDefined(value)) {
  20965. useLegacyPromise = !!value;
  20966. return this;
  20967. }
  20968. return useLegacyPromise;
  20969. };
  20970. /**
  20971. * @ngdoc property
  20972. * @name $httpProvider#interceptors
  20973. * @description
  20974. *
  20975. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  20976. * pre-processing of request or postprocessing of responses.
  20977. *
  20978. * These service factories are ordered by request, i.e. they are applied in the same order as the
  20979. * array, on request, but reverse order, on response.
  20980. *
  20981. * {@link ng.$http#interceptors Interceptors detailed info}
  20982. **/
  20983. var interceptorFactories = this.interceptors = [];
  20984. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  20985. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  20986. var defaultCache = $cacheFactory('$http');
  20987. /**
  20988. * Make sure that default param serializer is exposed as a function
  20989. */
  20990. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  20991. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  20992. /**
  20993. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  20994. * The reversal is needed so that we can build up the interception chain around the
  20995. * server request.
  20996. */
  20997. var reversedInterceptors = [];
  20998. forEach(interceptorFactories, function(interceptorFactory) {
  20999. reversedInterceptors.unshift(isString(interceptorFactory)
  21000. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  21001. });
  21002. /**
  21003. * @ngdoc service
  21004. * @kind function
  21005. * @name $http
  21006. * @requires ng.$httpBackend
  21007. * @requires $cacheFactory
  21008. * @requires $rootScope
  21009. * @requires $q
  21010. * @requires $injector
  21011. *
  21012. * @description
  21013. * The `$http` service is a core Angular service that facilitates communication with the remote
  21014. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  21015. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  21016. *
  21017. * For unit testing applications that use `$http` service, see
  21018. * {@link ngMock.$httpBackend $httpBackend mock}.
  21019. *
  21020. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  21021. * $resource} service.
  21022. *
  21023. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  21024. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  21025. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  21026. *
  21027. *
  21028. * ## General usage
  21029. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  21030. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  21031. *
  21032. * ```js
  21033. * // Simple GET request example:
  21034. * $http({
  21035. * method: 'GET',
  21036. * url: '/someUrl'
  21037. * }).then(function successCallback(response) {
  21038. * // this callback will be called asynchronously
  21039. * // when the response is available
  21040. * }, function errorCallback(response) {
  21041. * // called asynchronously if an error occurs
  21042. * // or server returns response with an error status.
  21043. * });
  21044. * ```
  21045. *
  21046. * The response object has these properties:
  21047. *
  21048. * - **data** – `{string|Object}` – The response body transformed with the transform
  21049. * functions.
  21050. * - **status** – `{number}` – HTTP status code of the response.
  21051. * - **headers** – `{function([headerName])}` – Header getter function.
  21052. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  21053. * - **statusText** – `{string}` – HTTP status text of the response.
  21054. *
  21055. * A response status code between 200 and 299 is considered a success status and
  21056. * will result in the success callback being called. Note that if the response is a redirect,
  21057. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  21058. * called for such responses.
  21059. *
  21060. *
  21061. * ## Shortcut methods
  21062. *
  21063. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  21064. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  21065. * last argument.
  21066. *
  21067. * ```js
  21068. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  21069. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  21070. * ```
  21071. *
  21072. * Complete list of shortcut methods:
  21073. *
  21074. * - {@link ng.$http#get $http.get}
  21075. * - {@link ng.$http#head $http.head}
  21076. * - {@link ng.$http#post $http.post}
  21077. * - {@link ng.$http#put $http.put}
  21078. * - {@link ng.$http#delete $http.delete}
  21079. * - {@link ng.$http#jsonp $http.jsonp}
  21080. * - {@link ng.$http#patch $http.patch}
  21081. *
  21082. *
  21083. * ## Writing Unit Tests that use $http
  21084. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  21085. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  21086. * request using trained responses.
  21087. *
  21088. * ```
  21089. * $httpBackend.expectGET(...);
  21090. * $http.get(...);
  21091. * $httpBackend.flush();
  21092. * ```
  21093. *
  21094. * ## Deprecation Notice
  21095. * <div class="alert alert-danger">
  21096. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  21097. * Use the standard `then` method instead.
  21098. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  21099. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  21100. * </div>
  21101. *
  21102. * ## Setting HTTP Headers
  21103. *
  21104. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  21105. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  21106. * object, which currently contains this default configuration:
  21107. *
  21108. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  21109. * - `Accept: application/json, text/plain, * / *`
  21110. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  21111. * - `Content-Type: application/json`
  21112. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  21113. * - `Content-Type: application/json`
  21114. *
  21115. * To add or overwrite these defaults, simply add or remove a property from these configuration
  21116. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  21117. * with the lowercased HTTP method name as the key, e.g.
  21118. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  21119. *
  21120. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  21121. * fashion. For example:
  21122. *
  21123. * ```
  21124. * module.run(function($http) {
  21125. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
  21126. * });
  21127. * ```
  21128. *
  21129. * In addition, you can supply a `headers` property in the config object passed when
  21130. * calling `$http(config)`, which overrides the defaults without changing them globally.
  21131. *
  21132. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  21133. * Use the `headers` property, setting the desired header to `undefined`. For example:
  21134. *
  21135. * ```js
  21136. * var req = {
  21137. * method: 'POST',
  21138. * url: 'http://example.com',
  21139. * headers: {
  21140. * 'Content-Type': undefined
  21141. * },
  21142. * data: { test: 'test' }
  21143. * }
  21144. *
  21145. * $http(req).then(function(){...}, function(){...});
  21146. * ```
  21147. *
  21148. * ## Transforming Requests and Responses
  21149. *
  21150. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  21151. * and `transformResponse`. These properties can be a single function that returns
  21152. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  21153. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  21154. *
  21155. * <div class="alert alert-warning">
  21156. * **Note:** Angular does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline.
  21157. * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference).
  21158. * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest
  21159. * function will be reflected on the scope and in any templates where the object is data-bound.
  21160. * To prevent his, transform functions should have no side-effects.
  21161. * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return.
  21162. * </div>
  21163. *
  21164. * ### Default Transformations
  21165. *
  21166. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  21167. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  21168. * then these will be applied.
  21169. *
  21170. * You can augment or replace the default transformations by modifying these properties by adding to or
  21171. * replacing the array.
  21172. *
  21173. * Angular provides the following default transformations:
  21174. *
  21175. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  21176. *
  21177. * - If the `data` property of the request configuration object contains an object, serialize it
  21178. * into JSON format.
  21179. *
  21180. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  21181. *
  21182. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  21183. * - If JSON response is detected, deserialize it using a JSON parser.
  21184. *
  21185. *
  21186. * ### Overriding the Default Transformations Per Request
  21187. *
  21188. * If you wish override the request/response transformations only for a single request then provide
  21189. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  21190. * into `$http`.
  21191. *
  21192. * Note that if you provide these properties on the config object the default transformations will be
  21193. * overwritten. If you wish to augment the default transformations then you must include them in your
  21194. * local transformation array.
  21195. *
  21196. * The following code demonstrates adding a new response transformation to be run after the default response
  21197. * transformations have been run.
  21198. *
  21199. * ```js
  21200. * function appendTransform(defaults, transform) {
  21201. *
  21202. * // We can't guarantee that the default transformation is an array
  21203. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  21204. *
  21205. * // Append the new transformation to the defaults
  21206. * return defaults.concat(transform);
  21207. * }
  21208. *
  21209. * $http({
  21210. * url: '...',
  21211. * method: 'GET',
  21212. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  21213. * return doTransform(value);
  21214. * })
  21215. * });
  21216. * ```
  21217. *
  21218. *
  21219. * ## Caching
  21220. *
  21221. * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must
  21222. * set the config.cache value or the default cache value to TRUE or to a cache object (created
  21223. * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes
  21224. * precedence over the default cache value.
  21225. *
  21226. * In order to:
  21227. * * cache all responses - set the default cache value to TRUE or to a cache object
  21228. * * cache a specific response - set config.cache value to TRUE or to a cache object
  21229. *
  21230. * If caching is enabled, but neither the default cache nor config.cache are set to a cache object,
  21231. * then the default `$cacheFactory($http)` object is used.
  21232. *
  21233. * The default cache value can be set by updating the
  21234. * {@link ng.$http#defaults `$http.defaults.cache`} property or the
  21235. * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property.
  21236. *
  21237. * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using
  21238. * the relevant cache object. The next time the same request is made, the response is returned
  21239. * from the cache without sending a request to the server.
  21240. *
  21241. * Take note that:
  21242. *
  21243. * * Only GET and JSONP requests are cached.
  21244. * * The cache key is the request URL including search parameters; headers are not considered.
  21245. * * Cached responses are returned asynchronously, in the same way as responses from the server.
  21246. * * If multiple identical requests are made using the same cache, which is not yet populated,
  21247. * one request will be made to the server and remaining requests will return the same response.
  21248. * * A cache-control header on the response does not affect if or how responses are cached.
  21249. *
  21250. *
  21251. * ## Interceptors
  21252. *
  21253. * Before you start creating interceptors, be sure to understand the
  21254. * {@link ng.$q $q and deferred/promise APIs}.
  21255. *
  21256. * For purposes of global error handling, authentication, or any kind of synchronous or
  21257. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  21258. * able to intercept requests before they are handed to the server and
  21259. * responses before they are handed over to the application code that
  21260. * initiated these requests. The interceptors leverage the {@link ng.$q
  21261. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  21262. *
  21263. * The interceptors are service factories that are registered with the `$httpProvider` by
  21264. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  21265. * injected with dependencies (if specified) and returns the interceptor.
  21266. *
  21267. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  21268. *
  21269. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  21270. * modify the `config` object or create a new one. The function needs to return the `config`
  21271. * object directly, or a promise containing the `config` or a new `config` object.
  21272. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  21273. * resolved with a rejection.
  21274. * * `response`: interceptors get called with http `response` object. The function is free to
  21275. * modify the `response` object or create a new one. The function needs to return the `response`
  21276. * object directly, or as a promise containing the `response` or a new `response` object.
  21277. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  21278. * resolved with a rejection.
  21279. *
  21280. *
  21281. * ```js
  21282. * // register the interceptor as a service
  21283. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  21284. * return {
  21285. * // optional method
  21286. * 'request': function(config) {
  21287. * // do something on success
  21288. * return config;
  21289. * },
  21290. *
  21291. * // optional method
  21292. * 'requestError': function(rejection) {
  21293. * // do something on error
  21294. * if (canRecover(rejection)) {
  21295. * return responseOrNewPromise
  21296. * }
  21297. * return $q.reject(rejection);
  21298. * },
  21299. *
  21300. *
  21301. *
  21302. * // optional method
  21303. * 'response': function(response) {
  21304. * // do something on success
  21305. * return response;
  21306. * },
  21307. *
  21308. * // optional method
  21309. * 'responseError': function(rejection) {
  21310. * // do something on error
  21311. * if (canRecover(rejection)) {
  21312. * return responseOrNewPromise
  21313. * }
  21314. * return $q.reject(rejection);
  21315. * }
  21316. * };
  21317. * });
  21318. *
  21319. * $httpProvider.interceptors.push('myHttpInterceptor');
  21320. *
  21321. *
  21322. * // alternatively, register the interceptor via an anonymous factory
  21323. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  21324. * return {
  21325. * 'request': function(config) {
  21326. * // same as above
  21327. * },
  21328. *
  21329. * 'response': function(response) {
  21330. * // same as above
  21331. * }
  21332. * };
  21333. * });
  21334. * ```
  21335. *
  21336. * ## Security Considerations
  21337. *
  21338. * When designing web applications, consider security threats from:
  21339. *
  21340. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  21341. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  21342. *
  21343. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  21344. * pre-configured with strategies that address these issues, but for this to work backend server
  21345. * cooperation is required.
  21346. *
  21347. * ### JSON Vulnerability Protection
  21348. *
  21349. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  21350. * allows third party website to turn your JSON resource URL into
  21351. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  21352. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  21353. * Angular will automatically strip the prefix before processing it as JSON.
  21354. *
  21355. * For example if your server needs to return:
  21356. * ```js
  21357. * ['one','two']
  21358. * ```
  21359. *
  21360. * which is vulnerable to attack, your server can return:
  21361. * ```js
  21362. * )]}',
  21363. * ['one','two']
  21364. * ```
  21365. *
  21366. * Angular will strip the prefix, before processing the JSON.
  21367. *
  21368. *
  21369. * ### Cross Site Request Forgery (XSRF) Protection
  21370. *
  21371. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by
  21372. * which the attacker can trick an authenticated user into unknowingly executing actions on your
  21373. * website. Angular provides a mechanism to counter XSRF. When performing XHR requests, the
  21374. * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP
  21375. * header (`X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read the
  21376. * cookie, your server can be assured that the XHR came from JavaScript running on your domain.
  21377. * The header will not be set for cross-domain requests.
  21378. *
  21379. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  21380. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  21381. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  21382. * that only JavaScript running on your domain could have sent the request. The token must be
  21383. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  21384. * making up its own tokens). We recommend that the token is a digest of your site's
  21385. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  21386. * for added security.
  21387. *
  21388. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  21389. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  21390. * or the per-request config object.
  21391. *
  21392. * In order to prevent collisions in environments where multiple Angular apps share the
  21393. * same domain or subdomain, we recommend that each application uses unique cookie name.
  21394. *
  21395. * @param {object} config Object describing the request to be made and how it should be
  21396. * processed. The object has following properties:
  21397. *
  21398. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  21399. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  21400. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  21401. * with the `paramSerializer` and appended as GET parameters.
  21402. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  21403. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  21404. * HTTP headers to send to the server. If the return value of a function is null, the
  21405. * header will not be sent. Functions accept a config object as an argument.
  21406. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  21407. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  21408. * - **transformRequest** –
  21409. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  21410. * transform function or an array of such functions. The transform function takes the http
  21411. * request body and headers and returns its transformed (typically serialized) version.
  21412. * See {@link ng.$http#overriding-the-default-transformations-per-request
  21413. * Overriding the Default Transformations}
  21414. * - **transformResponse** –
  21415. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  21416. * transform function or an array of such functions. The transform function takes the http
  21417. * response body, headers and status and returns its transformed (typically deserialized) version.
  21418. * See {@link ng.$http#overriding-the-default-transformations-per-request
  21419. * Overriding the Default Transformations}
  21420. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  21421. * prepare the string representation of request parameters (specified as an object).
  21422. * If specified as string, it is interpreted as function registered with the
  21423. * {@link $injector $injector}, which means you can create your own serializer
  21424. * by registering it as a {@link auto.$provide#service service}.
  21425. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  21426. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  21427. * - **cache** – `{boolean|Object}` – A boolean value or object created with
  21428. * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response.
  21429. * See {@link $http#caching $http Caching} for more information.
  21430. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  21431. * that should abort the request when resolved.
  21432. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  21433. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  21434. * for more information.
  21435. * - **responseType** - `{string}` - see
  21436. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  21437. *
  21438. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  21439. * when the request succeeds or fails.
  21440. *
  21441. *
  21442. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  21443. * requests. This is primarily meant to be used for debugging purposes.
  21444. *
  21445. *
  21446. * @example
  21447. <example module="httpExample">
  21448. <file name="index.html">
  21449. <div ng-controller="FetchController">
  21450. <select ng-model="method" aria-label="Request method">
  21451. <option>GET</option>
  21452. <option>JSONP</option>
  21453. </select>
  21454. <input type="text" ng-model="url" size="80" aria-label="URL" />
  21455. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  21456. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  21457. <button id="samplejsonpbtn"
  21458. ng-click="updateModel('JSONP',
  21459. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  21460. Sample JSONP
  21461. </button>
  21462. <button id="invalidjsonpbtn"
  21463. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  21464. Invalid JSONP
  21465. </button>
  21466. <pre>http status code: {{status}}</pre>
  21467. <pre>http response data: {{data}}</pre>
  21468. </div>
  21469. </file>
  21470. <file name="script.js">
  21471. angular.module('httpExample', [])
  21472. .controller('FetchController', ['$scope', '$http', '$templateCache',
  21473. function($scope, $http, $templateCache) {
  21474. $scope.method = 'GET';
  21475. $scope.url = 'http-hello.html';
  21476. $scope.fetch = function() {
  21477. $scope.code = null;
  21478. $scope.response = null;
  21479. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  21480. then(function(response) {
  21481. $scope.status = response.status;
  21482. $scope.data = response.data;
  21483. }, function(response) {
  21484. $scope.data = response.data || "Request failed";
  21485. $scope.status = response.status;
  21486. });
  21487. };
  21488. $scope.updateModel = function(method, url) {
  21489. $scope.method = method;
  21490. $scope.url = url;
  21491. };
  21492. }]);
  21493. </file>
  21494. <file name="http-hello.html">
  21495. Hello, $http!
  21496. </file>
  21497. <file name="protractor.js" type="protractor">
  21498. var status = element(by.binding('status'));
  21499. var data = element(by.binding('data'));
  21500. var fetchBtn = element(by.id('fetchbtn'));
  21501. var sampleGetBtn = element(by.id('samplegetbtn'));
  21502. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  21503. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  21504. it('should make an xhr GET request', function() {
  21505. sampleGetBtn.click();
  21506. fetchBtn.click();
  21507. expect(status.getText()).toMatch('200');
  21508. expect(data.getText()).toMatch(/Hello, \$http!/);
  21509. });
  21510. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  21511. // it('should make a JSONP request to angularjs.org', function() {
  21512. // sampleJsonpBtn.click();
  21513. // fetchBtn.click();
  21514. // expect(status.getText()).toMatch('200');
  21515. // expect(data.getText()).toMatch(/Super Hero!/);
  21516. // });
  21517. it('should make JSONP request to invalid URL and invoke the error handler',
  21518. function() {
  21519. invalidJsonpBtn.click();
  21520. fetchBtn.click();
  21521. expect(status.getText()).toMatch('0');
  21522. expect(data.getText()).toMatch('Request failed');
  21523. });
  21524. </file>
  21525. </example>
  21526. */
  21527. function $http(requestConfig) {
  21528. if (!isObject(requestConfig)) {
  21529. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  21530. }
  21531. if (!isString(requestConfig.url)) {
  21532. throw minErr('$http')('badreq', 'Http request configuration url must be a string. Received: {0}', requestConfig.url);
  21533. }
  21534. var config = extend({
  21535. method: 'get',
  21536. transformRequest: defaults.transformRequest,
  21537. transformResponse: defaults.transformResponse,
  21538. paramSerializer: defaults.paramSerializer
  21539. }, requestConfig);
  21540. config.headers = mergeHeaders(requestConfig);
  21541. config.method = uppercase(config.method);
  21542. config.paramSerializer = isString(config.paramSerializer) ?
  21543. $injector.get(config.paramSerializer) : config.paramSerializer;
  21544. var serverRequest = function(config) {
  21545. var headers = config.headers;
  21546. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  21547. // strip content-type if data is undefined
  21548. if (isUndefined(reqData)) {
  21549. forEach(headers, function(value, header) {
  21550. if (lowercase(header) === 'content-type') {
  21551. delete headers[header];
  21552. }
  21553. });
  21554. }
  21555. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  21556. config.withCredentials = defaults.withCredentials;
  21557. }
  21558. // send request
  21559. return sendReq(config, reqData).then(transformResponse, transformResponse);
  21560. };
  21561. var chain = [serverRequest, undefined];
  21562. var promise = $q.when(config);
  21563. // apply interceptors
  21564. forEach(reversedInterceptors, function(interceptor) {
  21565. if (interceptor.request || interceptor.requestError) {
  21566. chain.unshift(interceptor.request, interceptor.requestError);
  21567. }
  21568. if (interceptor.response || interceptor.responseError) {
  21569. chain.push(interceptor.response, interceptor.responseError);
  21570. }
  21571. });
  21572. while (chain.length) {
  21573. var thenFn = chain.shift();
  21574. var rejectFn = chain.shift();
  21575. promise = promise.then(thenFn, rejectFn);
  21576. }
  21577. if (useLegacyPromise) {
  21578. promise.success = function(fn) {
  21579. assertArgFn(fn, 'fn');
  21580. promise.then(function(response) {
  21581. fn(response.data, response.status, response.headers, config);
  21582. });
  21583. return promise;
  21584. };
  21585. promise.error = function(fn) {
  21586. assertArgFn(fn, 'fn');
  21587. promise.then(null, function(response) {
  21588. fn(response.data, response.status, response.headers, config);
  21589. });
  21590. return promise;
  21591. };
  21592. } else {
  21593. promise.success = $httpMinErrLegacyFn('success');
  21594. promise.error = $httpMinErrLegacyFn('error');
  21595. }
  21596. return promise;
  21597. function transformResponse(response) {
  21598. // make a copy since the response must be cacheable
  21599. var resp = extend({}, response);
  21600. resp.data = transformData(response.data, response.headers, response.status,
  21601. config.transformResponse);
  21602. return (isSuccess(response.status))
  21603. ? resp
  21604. : $q.reject(resp);
  21605. }
  21606. function executeHeaderFns(headers, config) {
  21607. var headerContent, processedHeaders = {};
  21608. forEach(headers, function(headerFn, header) {
  21609. if (isFunction(headerFn)) {
  21610. headerContent = headerFn(config);
  21611. if (headerContent != null) {
  21612. processedHeaders[header] = headerContent;
  21613. }
  21614. } else {
  21615. processedHeaders[header] = headerFn;
  21616. }
  21617. });
  21618. return processedHeaders;
  21619. }
  21620. function mergeHeaders(config) {
  21621. var defHeaders = defaults.headers,
  21622. reqHeaders = extend({}, config.headers),
  21623. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  21624. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  21625. // using for-in instead of forEach to avoid unnecessary iteration after header has been found
  21626. defaultHeadersIteration:
  21627. for (defHeaderName in defHeaders) {
  21628. lowercaseDefHeaderName = lowercase(defHeaderName);
  21629. for (reqHeaderName in reqHeaders) {
  21630. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  21631. continue defaultHeadersIteration;
  21632. }
  21633. }
  21634. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  21635. }
  21636. // execute if header value is a function for merged headers
  21637. return executeHeaderFns(reqHeaders, shallowCopy(config));
  21638. }
  21639. }
  21640. $http.pendingRequests = [];
  21641. /**
  21642. * @ngdoc method
  21643. * @name $http#get
  21644. *
  21645. * @description
  21646. * Shortcut method to perform `GET` request.
  21647. *
  21648. * @param {string} url Relative or absolute URL specifying the destination of the request
  21649. * @param {Object=} config Optional configuration object
  21650. * @returns {HttpPromise} Future object
  21651. */
  21652. /**
  21653. * @ngdoc method
  21654. * @name $http#delete
  21655. *
  21656. * @description
  21657. * Shortcut method to perform `DELETE` request.
  21658. *
  21659. * @param {string} url Relative or absolute URL specifying the destination of the request
  21660. * @param {Object=} config Optional configuration object
  21661. * @returns {HttpPromise} Future object
  21662. */
  21663. /**
  21664. * @ngdoc method
  21665. * @name $http#head
  21666. *
  21667. * @description
  21668. * Shortcut method to perform `HEAD` request.
  21669. *
  21670. * @param {string} url Relative or absolute URL specifying the destination of the request
  21671. * @param {Object=} config Optional configuration object
  21672. * @returns {HttpPromise} Future object
  21673. */
  21674. /**
  21675. * @ngdoc method
  21676. * @name $http#jsonp
  21677. *
  21678. * @description
  21679. * Shortcut method to perform `JSONP` request.
  21680. *
  21681. * @param {string} url Relative or absolute URL specifying the destination of the request.
  21682. * The name of the callback should be the string `JSON_CALLBACK`.
  21683. * @param {Object=} config Optional configuration object
  21684. * @returns {HttpPromise} Future object
  21685. */
  21686. createShortMethods('get', 'delete', 'head', 'jsonp');
  21687. /**
  21688. * @ngdoc method
  21689. * @name $http#post
  21690. *
  21691. * @description
  21692. * Shortcut method to perform `POST` request.
  21693. *
  21694. * @param {string} url Relative or absolute URL specifying the destination of the request
  21695. * @param {*} data Request content
  21696. * @param {Object=} config Optional configuration object
  21697. * @returns {HttpPromise} Future object
  21698. */
  21699. /**
  21700. * @ngdoc method
  21701. * @name $http#put
  21702. *
  21703. * @description
  21704. * Shortcut method to perform `PUT` request.
  21705. *
  21706. * @param {string} url Relative or absolute URL specifying the destination of the request
  21707. * @param {*} data Request content
  21708. * @param {Object=} config Optional configuration object
  21709. * @returns {HttpPromise} Future object
  21710. */
  21711. /**
  21712. * @ngdoc method
  21713. * @name $http#patch
  21714. *
  21715. * @description
  21716. * Shortcut method to perform `PATCH` request.
  21717. *
  21718. * @param {string} url Relative or absolute URL specifying the destination of the request
  21719. * @param {*} data Request content
  21720. * @param {Object=} config Optional configuration object
  21721. * @returns {HttpPromise} Future object
  21722. */
  21723. createShortMethodsWithData('post', 'put', 'patch');
  21724. /**
  21725. * @ngdoc property
  21726. * @name $http#defaults
  21727. *
  21728. * @description
  21729. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  21730. * default headers, withCredentials as well as request and response transformations.
  21731. *
  21732. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  21733. */
  21734. $http.defaults = defaults;
  21735. return $http;
  21736. function createShortMethods(names) {
  21737. forEach(arguments, function(name) {
  21738. $http[name] = function(url, config) {
  21739. return $http(extend({}, config || {}, {
  21740. method: name,
  21741. url: url
  21742. }));
  21743. };
  21744. });
  21745. }
  21746. function createShortMethodsWithData(name) {
  21747. forEach(arguments, function(name) {
  21748. $http[name] = function(url, data, config) {
  21749. return $http(extend({}, config || {}, {
  21750. method: name,
  21751. url: url,
  21752. data: data
  21753. }));
  21754. };
  21755. });
  21756. }
  21757. /**
  21758. * Makes the request.
  21759. *
  21760. * !!! ACCESSES CLOSURE VARS:
  21761. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  21762. */
  21763. function sendReq(config, reqData) {
  21764. var deferred = $q.defer(),
  21765. promise = deferred.promise,
  21766. cache,
  21767. cachedResp,
  21768. reqHeaders = config.headers,
  21769. url = buildUrl(config.url, config.paramSerializer(config.params));
  21770. $http.pendingRequests.push(config);
  21771. promise.then(removePendingReq, removePendingReq);
  21772. if ((config.cache || defaults.cache) && config.cache !== false &&
  21773. (config.method === 'GET' || config.method === 'JSONP')) {
  21774. cache = isObject(config.cache) ? config.cache
  21775. : isObject(defaults.cache) ? defaults.cache
  21776. : defaultCache;
  21777. }
  21778. if (cache) {
  21779. cachedResp = cache.get(url);
  21780. if (isDefined(cachedResp)) {
  21781. if (isPromiseLike(cachedResp)) {
  21782. // cached request has already been sent, but there is no response yet
  21783. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  21784. } else {
  21785. // serving from cache
  21786. if (isArray(cachedResp)) {
  21787. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  21788. } else {
  21789. resolvePromise(cachedResp, 200, {}, 'OK');
  21790. }
  21791. }
  21792. } else {
  21793. // put the promise for the non-transformed response into cache as a placeholder
  21794. cache.put(url, promise);
  21795. }
  21796. }
  21797. // if we won't have the response in cache, set the xsrf headers and
  21798. // send the request to the backend
  21799. if (isUndefined(cachedResp)) {
  21800. var xsrfValue = urlIsSameOrigin(config.url)
  21801. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  21802. : undefined;
  21803. if (xsrfValue) {
  21804. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  21805. }
  21806. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  21807. config.withCredentials, config.responseType);
  21808. }
  21809. return promise;
  21810. /**
  21811. * Callback registered to $httpBackend():
  21812. * - caches the response if desired
  21813. * - resolves the raw $http promise
  21814. * - calls $apply
  21815. */
  21816. function done(status, response, headersString, statusText) {
  21817. if (cache) {
  21818. if (isSuccess(status)) {
  21819. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  21820. } else {
  21821. // remove promise from the cache
  21822. cache.remove(url);
  21823. }
  21824. }
  21825. function resolveHttpPromise() {
  21826. resolvePromise(response, status, headersString, statusText);
  21827. }
  21828. if (useApplyAsync) {
  21829. $rootScope.$applyAsync(resolveHttpPromise);
  21830. } else {
  21831. resolveHttpPromise();
  21832. if (!$rootScope.$$phase) $rootScope.$apply();
  21833. }
  21834. }
  21835. /**
  21836. * Resolves the raw $http promise.
  21837. */
  21838. function resolvePromise(response, status, headers, statusText) {
  21839. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  21840. status = status >= -1 ? status : 0;
  21841. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  21842. data: response,
  21843. status: status,
  21844. headers: headersGetter(headers),
  21845. config: config,
  21846. statusText: statusText
  21847. });
  21848. }
  21849. function resolvePromiseWithResult(result) {
  21850. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  21851. }
  21852. function removePendingReq() {
  21853. var idx = $http.pendingRequests.indexOf(config);
  21854. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  21855. }
  21856. }
  21857. function buildUrl(url, serializedParams) {
  21858. if (serializedParams.length > 0) {
  21859. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  21860. }
  21861. return url;
  21862. }
  21863. }];
  21864. }
  21865. /**
  21866. * @ngdoc service
  21867. * @name $xhrFactory
  21868. *
  21869. * @description
  21870. * Factory function used to create XMLHttpRequest objects.
  21871. *
  21872. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  21873. *
  21874. * ```
  21875. * angular.module('myApp', [])
  21876. * .factory('$xhrFactory', function() {
  21877. * return function createXhr(method, url) {
  21878. * return new window.XMLHttpRequest({mozSystem: true});
  21879. * };
  21880. * });
  21881. * ```
  21882. *
  21883. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  21884. * @param {string} url URL of the request.
  21885. */
  21886. function $xhrFactoryProvider() {
  21887. this.$get = function() {
  21888. return function createXhr() {
  21889. return new window.XMLHttpRequest();
  21890. };
  21891. };
  21892. }
  21893. /**
  21894. * @ngdoc service
  21895. * @name $httpBackend
  21896. * @requires $window
  21897. * @requires $document
  21898. * @requires $xhrFactory
  21899. *
  21900. * @description
  21901. * HTTP backend used by the {@link ng.$http service} that delegates to
  21902. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  21903. *
  21904. * You should never need to use this service directly, instead use the higher-level abstractions:
  21905. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  21906. *
  21907. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  21908. * $httpBackend} which can be trained with responses.
  21909. */
  21910. function $HttpBackendProvider() {
  21911. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  21912. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  21913. }];
  21914. }
  21915. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  21916. // TODO(vojta): fix the signature
  21917. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  21918. $browser.$$incOutstandingRequestCount();
  21919. url = url || $browser.url();
  21920. if (lowercase(method) == 'jsonp') {
  21921. var callbackId = '_' + (callbacks.counter++).toString(36);
  21922. callbacks[callbackId] = function(data) {
  21923. callbacks[callbackId].data = data;
  21924. callbacks[callbackId].called = true;
  21925. };
  21926. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  21927. callbackId, function(status, text) {
  21928. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  21929. callbacks[callbackId] = noop;
  21930. });
  21931. } else {
  21932. var xhr = createXhr(method, url);
  21933. xhr.open(method, url, true);
  21934. forEach(headers, function(value, key) {
  21935. if (isDefined(value)) {
  21936. xhr.setRequestHeader(key, value);
  21937. }
  21938. });
  21939. xhr.onload = function requestLoaded() {
  21940. var statusText = xhr.statusText || '';
  21941. // responseText is the old-school way of retrieving response (supported by IE9)
  21942. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  21943. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  21944. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  21945. var status = xhr.status === 1223 ? 204 : xhr.status;
  21946. // fix status code when it is 0 (0 status is undocumented).
  21947. // Occurs when accessing file resources or on Android 4.1 stock browser
  21948. // while retrieving files from application cache.
  21949. if (status === 0) {
  21950. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  21951. }
  21952. completeRequest(callback,
  21953. status,
  21954. response,
  21955. xhr.getAllResponseHeaders(),
  21956. statusText);
  21957. };
  21958. var requestError = function() {
  21959. // The response is always empty
  21960. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  21961. completeRequest(callback, -1, null, null, '');
  21962. };
  21963. xhr.onerror = requestError;
  21964. xhr.onabort = requestError;
  21965. if (withCredentials) {
  21966. xhr.withCredentials = true;
  21967. }
  21968. if (responseType) {
  21969. try {
  21970. xhr.responseType = responseType;
  21971. } catch (e) {
  21972. // WebKit added support for the json responseType value on 09/03/2013
  21973. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  21974. // known to throw when setting the value "json" as the response type. Other older
  21975. // browsers implementing the responseType
  21976. //
  21977. // The json response type can be ignored if not supported, because JSON payloads are
  21978. // parsed on the client-side regardless.
  21979. if (responseType !== 'json') {
  21980. throw e;
  21981. }
  21982. }
  21983. }
  21984. xhr.send(isUndefined(post) ? null : post);
  21985. }
  21986. if (timeout > 0) {
  21987. var timeoutId = $browserDefer(timeoutRequest, timeout);
  21988. } else if (isPromiseLike(timeout)) {
  21989. timeout.then(timeoutRequest);
  21990. }
  21991. function timeoutRequest() {
  21992. jsonpDone && jsonpDone();
  21993. xhr && xhr.abort();
  21994. }
  21995. function completeRequest(callback, status, response, headersString, statusText) {
  21996. // cancel timeout and subsequent timeout promise resolution
  21997. if (isDefined(timeoutId)) {
  21998. $browserDefer.cancel(timeoutId);
  21999. }
  22000. jsonpDone = xhr = null;
  22001. callback(status, response, headersString, statusText);
  22002. $browser.$$completeOutstandingRequest(noop);
  22003. }
  22004. };
  22005. function jsonpReq(url, callbackId, done) {
  22006. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  22007. // - fetches local scripts via XHR and evals them
  22008. // - adds and immediately removes script elements from the document
  22009. var script = rawDocument.createElement('script'), callback = null;
  22010. script.type = "text/javascript";
  22011. script.src = url;
  22012. script.async = true;
  22013. callback = function(event) {
  22014. removeEventListenerFn(script, "load", callback);
  22015. removeEventListenerFn(script, "error", callback);
  22016. rawDocument.body.removeChild(script);
  22017. script = null;
  22018. var status = -1;
  22019. var text = "unknown";
  22020. if (event) {
  22021. if (event.type === "load" && !callbacks[callbackId].called) {
  22022. event = { type: "error" };
  22023. }
  22024. text = event.type;
  22025. status = event.type === "error" ? 404 : 200;
  22026. }
  22027. if (done) {
  22028. done(status, text);
  22029. }
  22030. };
  22031. addEventListenerFn(script, "load", callback);
  22032. addEventListenerFn(script, "error", callback);
  22033. rawDocument.body.appendChild(script);
  22034. return callback;
  22035. }
  22036. }
  22037. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  22038. $interpolateMinErr.throwNoconcat = function(text) {
  22039. throw $interpolateMinErr('noconcat',
  22040. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  22041. "interpolations that concatenate multiple expressions when a trusted value is " +
  22042. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  22043. };
  22044. $interpolateMinErr.interr = function(text, err) {
  22045. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  22046. };
  22047. /**
  22048. * @ngdoc provider
  22049. * @name $interpolateProvider
  22050. *
  22051. * @description
  22052. *
  22053. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  22054. *
  22055. * <div class="alert alert-danger">
  22056. * This feature is sometimes used to mix different markup languages, e.g. to wrap an Angular
  22057. * template within a Python Jinja template (or any other template language). Mixing templating
  22058. * languages is **very dangerous**. The embedding template language will not safely escape Angular
  22059. * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS)
  22060. * security bugs!
  22061. * </div>
  22062. *
  22063. * @example
  22064. <example name="custom-interpolation-markup" module="customInterpolationApp">
  22065. <file name="index.html">
  22066. <script>
  22067. var customInterpolationApp = angular.module('customInterpolationApp', []);
  22068. customInterpolationApp.config(function($interpolateProvider) {
  22069. $interpolateProvider.startSymbol('//');
  22070. $interpolateProvider.endSymbol('//');
  22071. });
  22072. customInterpolationApp.controller('DemoController', function() {
  22073. this.label = "This binding is brought you by // interpolation symbols.";
  22074. });
  22075. </script>
  22076. <div ng-controller="DemoController as demo">
  22077. //demo.label//
  22078. </div>
  22079. </file>
  22080. <file name="protractor.js" type="protractor">
  22081. it('should interpolate binding with custom symbols', function() {
  22082. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  22083. });
  22084. </file>
  22085. </example>
  22086. */
  22087. function $InterpolateProvider() {
  22088. var startSymbol = '{{';
  22089. var endSymbol = '}}';
  22090. /**
  22091. * @ngdoc method
  22092. * @name $interpolateProvider#startSymbol
  22093. * @description
  22094. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  22095. *
  22096. * @param {string=} value new value to set the starting symbol to.
  22097. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  22098. */
  22099. this.startSymbol = function(value) {
  22100. if (value) {
  22101. startSymbol = value;
  22102. return this;
  22103. } else {
  22104. return startSymbol;
  22105. }
  22106. };
  22107. /**
  22108. * @ngdoc method
  22109. * @name $interpolateProvider#endSymbol
  22110. * @description
  22111. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  22112. *
  22113. * @param {string=} value new value to set the ending symbol to.
  22114. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  22115. */
  22116. this.endSymbol = function(value) {
  22117. if (value) {
  22118. endSymbol = value;
  22119. return this;
  22120. } else {
  22121. return endSymbol;
  22122. }
  22123. };
  22124. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  22125. var startSymbolLength = startSymbol.length,
  22126. endSymbolLength = endSymbol.length,
  22127. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  22128. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  22129. function escape(ch) {
  22130. return '\\\\\\' + ch;
  22131. }
  22132. function unescapeText(text) {
  22133. return text.replace(escapedStartRegexp, startSymbol).
  22134. replace(escapedEndRegexp, endSymbol);
  22135. }
  22136. function stringify(value) {
  22137. if (value == null) { // null || undefined
  22138. return '';
  22139. }
  22140. switch (typeof value) {
  22141. case 'string':
  22142. break;
  22143. case 'number':
  22144. value = '' + value;
  22145. break;
  22146. default:
  22147. value = toJson(value);
  22148. }
  22149. return value;
  22150. }
  22151. //TODO: this is the same as the constantWatchDelegate in parse.js
  22152. function constantWatchDelegate(scope, listener, objectEquality, constantInterp) {
  22153. var unwatch;
  22154. return unwatch = scope.$watch(function constantInterpolateWatch(scope) {
  22155. unwatch();
  22156. return constantInterp(scope);
  22157. }, listener, objectEquality);
  22158. }
  22159. /**
  22160. * @ngdoc service
  22161. * @name $interpolate
  22162. * @kind function
  22163. *
  22164. * @requires $parse
  22165. * @requires $sce
  22166. *
  22167. * @description
  22168. *
  22169. * Compiles a string with markup into an interpolation function. This service is used by the
  22170. * HTML {@link ng.$compile $compile} service for data binding. See
  22171. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  22172. * interpolation markup.
  22173. *
  22174. *
  22175. * ```js
  22176. * var $interpolate = ...; // injected
  22177. * var exp = $interpolate('Hello {{name | uppercase}}!');
  22178. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  22179. * ```
  22180. *
  22181. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  22182. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  22183. * evaluate to a value other than `undefined`.
  22184. *
  22185. * ```js
  22186. * var $interpolate = ...; // injected
  22187. * var context = {greeting: 'Hello', name: undefined };
  22188. *
  22189. * // default "forgiving" mode
  22190. * var exp = $interpolate('{{greeting}} {{name}}!');
  22191. * expect(exp(context)).toEqual('Hello !');
  22192. *
  22193. * // "allOrNothing" mode
  22194. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  22195. * expect(exp(context)).toBeUndefined();
  22196. * context.name = 'Angular';
  22197. * expect(exp(context)).toEqual('Hello Angular!');
  22198. * ```
  22199. *
  22200. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  22201. *
  22202. * ####Escaped Interpolation
  22203. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  22204. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  22205. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  22206. * or binding.
  22207. *
  22208. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  22209. * degree, while also enabling code examples to work without relying on the
  22210. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  22211. *
  22212. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  22213. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  22214. * interpolation start/end markers with their escaped counterparts.**
  22215. *
  22216. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  22217. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  22218. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  22219. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  22220. * this is typically useful only when user-data is used in rendering a template from the server, or
  22221. * when otherwise untrusted data is used by a directive.
  22222. *
  22223. * <example>
  22224. * <file name="index.html">
  22225. * <div ng-init="username='A user'">
  22226. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  22227. * </p>
  22228. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  22229. * application, but fails to accomplish their task, because the server has correctly
  22230. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  22231. * characters.</p>
  22232. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  22233. * from the database by an administrator.</p>
  22234. * </div>
  22235. * </file>
  22236. * </example>
  22237. *
  22238. * @param {string} text The text with markup to interpolate.
  22239. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  22240. * embedded expression in order to return an interpolation function. Strings with no
  22241. * embedded expression will return null for the interpolation function.
  22242. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  22243. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  22244. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  22245. * provides Strict Contextual Escaping for details.
  22246. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  22247. * unless all embedded expressions evaluate to a value other than `undefined`.
  22248. * @returns {function(context)} an interpolation function which is used to compute the
  22249. * interpolated string. The function has these parameters:
  22250. *
  22251. * - `context`: evaluation context for all expressions embedded in the interpolated text
  22252. */
  22253. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  22254. // Provide a quick exit and simplified result function for text with no interpolation
  22255. if (!text.length || text.indexOf(startSymbol) === -1) {
  22256. var constantInterp;
  22257. if (!mustHaveExpression) {
  22258. var unescapedText = unescapeText(text);
  22259. constantInterp = valueFn(unescapedText);
  22260. constantInterp.exp = text;
  22261. constantInterp.expressions = [];
  22262. constantInterp.$$watchDelegate = constantWatchDelegate;
  22263. }
  22264. return constantInterp;
  22265. }
  22266. allOrNothing = !!allOrNothing;
  22267. var startIndex,
  22268. endIndex,
  22269. index = 0,
  22270. expressions = [],
  22271. parseFns = [],
  22272. textLength = text.length,
  22273. exp,
  22274. concat = [],
  22275. expressionPositions = [];
  22276. while (index < textLength) {
  22277. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  22278. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  22279. if (index !== startIndex) {
  22280. concat.push(unescapeText(text.substring(index, startIndex)));
  22281. }
  22282. exp = text.substring(startIndex + startSymbolLength, endIndex);
  22283. expressions.push(exp);
  22284. parseFns.push($parse(exp, parseStringifyInterceptor));
  22285. index = endIndex + endSymbolLength;
  22286. expressionPositions.push(concat.length);
  22287. concat.push('');
  22288. } else {
  22289. // we did not find an interpolation, so we have to add the remainder to the separators array
  22290. if (index !== textLength) {
  22291. concat.push(unescapeText(text.substring(index)));
  22292. }
  22293. break;
  22294. }
  22295. }
  22296. // Concatenating expressions makes it hard to reason about whether some combination of
  22297. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  22298. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  22299. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  22300. // make it obvious that you bound the value to some user controlled value. This helps reduce
  22301. // the load when auditing for XSS issues.
  22302. if (trustedContext && concat.length > 1) {
  22303. $interpolateMinErr.throwNoconcat(text);
  22304. }
  22305. if (!mustHaveExpression || expressions.length) {
  22306. var compute = function(values) {
  22307. for (var i = 0, ii = expressions.length; i < ii; i++) {
  22308. if (allOrNothing && isUndefined(values[i])) return;
  22309. concat[expressionPositions[i]] = values[i];
  22310. }
  22311. return concat.join('');
  22312. };
  22313. var getValue = function(value) {
  22314. return trustedContext ?
  22315. $sce.getTrusted(trustedContext, value) :
  22316. $sce.valueOf(value);
  22317. };
  22318. return extend(function interpolationFn(context) {
  22319. var i = 0;
  22320. var ii = expressions.length;
  22321. var values = new Array(ii);
  22322. try {
  22323. for (; i < ii; i++) {
  22324. values[i] = parseFns[i](context);
  22325. }
  22326. return compute(values);
  22327. } catch (err) {
  22328. $exceptionHandler($interpolateMinErr.interr(text, err));
  22329. }
  22330. }, {
  22331. // all of these properties are undocumented for now
  22332. exp: text, //just for compatibility with regular watchers created via $watch
  22333. expressions: expressions,
  22334. $$watchDelegate: function(scope, listener) {
  22335. var lastValue;
  22336. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  22337. var currValue = compute(values);
  22338. if (isFunction(listener)) {
  22339. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  22340. }
  22341. lastValue = currValue;
  22342. });
  22343. }
  22344. });
  22345. }
  22346. function parseStringifyInterceptor(value) {
  22347. try {
  22348. value = getValue(value);
  22349. return allOrNothing && !isDefined(value) ? value : stringify(value);
  22350. } catch (err) {
  22351. $exceptionHandler($interpolateMinErr.interr(text, err));
  22352. }
  22353. }
  22354. }
  22355. /**
  22356. * @ngdoc method
  22357. * @name $interpolate#startSymbol
  22358. * @description
  22359. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  22360. *
  22361. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  22362. * the symbol.
  22363. *
  22364. * @returns {string} start symbol.
  22365. */
  22366. $interpolate.startSymbol = function() {
  22367. return startSymbol;
  22368. };
  22369. /**
  22370. * @ngdoc method
  22371. * @name $interpolate#endSymbol
  22372. * @description
  22373. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  22374. *
  22375. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  22376. * the symbol.
  22377. *
  22378. * @returns {string} end symbol.
  22379. */
  22380. $interpolate.endSymbol = function() {
  22381. return endSymbol;
  22382. };
  22383. return $interpolate;
  22384. }];
  22385. }
  22386. function $IntervalProvider() {
  22387. this.$get = ['$rootScope', '$window', '$q', '$$q', '$browser',
  22388. function($rootScope, $window, $q, $$q, $browser) {
  22389. var intervals = {};
  22390. /**
  22391. * @ngdoc service
  22392. * @name $interval
  22393. *
  22394. * @description
  22395. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  22396. * milliseconds.
  22397. *
  22398. * The return value of registering an interval function is a promise. This promise will be
  22399. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  22400. * run indefinitely if `count` is not defined. The value of the notification will be the
  22401. * number of iterations that have run.
  22402. * To cancel an interval, call `$interval.cancel(promise)`.
  22403. *
  22404. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  22405. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  22406. * time.
  22407. *
  22408. * <div class="alert alert-warning">
  22409. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  22410. * with them. In particular they are not automatically destroyed when a controller's scope or a
  22411. * directive's element are destroyed.
  22412. * You should take this into consideration and make sure to always cancel the interval at the
  22413. * appropriate moment. See the example below for more details on how and when to do this.
  22414. * </div>
  22415. *
  22416. * @param {function()} fn A function that should be called repeatedly.
  22417. * @param {number} delay Number of milliseconds between each function call.
  22418. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  22419. * indefinitely.
  22420. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  22421. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  22422. * @param {...*=} Pass additional parameters to the executed function.
  22423. * @returns {promise} A promise which will be notified on each iteration.
  22424. *
  22425. * @example
  22426. * <example module="intervalExample">
  22427. * <file name="index.html">
  22428. * <script>
  22429. * angular.module('intervalExample', [])
  22430. * .controller('ExampleController', ['$scope', '$interval',
  22431. * function($scope, $interval) {
  22432. * $scope.format = 'M/d/yy h:mm:ss a';
  22433. * $scope.blood_1 = 100;
  22434. * $scope.blood_2 = 120;
  22435. *
  22436. * var stop;
  22437. * $scope.fight = function() {
  22438. * // Don't start a new fight if we are already fighting
  22439. * if ( angular.isDefined(stop) ) return;
  22440. *
  22441. * stop = $interval(function() {
  22442. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  22443. * $scope.blood_1 = $scope.blood_1 - 3;
  22444. * $scope.blood_2 = $scope.blood_2 - 4;
  22445. * } else {
  22446. * $scope.stopFight();
  22447. * }
  22448. * }, 100);
  22449. * };
  22450. *
  22451. * $scope.stopFight = function() {
  22452. * if (angular.isDefined(stop)) {
  22453. * $interval.cancel(stop);
  22454. * stop = undefined;
  22455. * }
  22456. * };
  22457. *
  22458. * $scope.resetFight = function() {
  22459. * $scope.blood_1 = 100;
  22460. * $scope.blood_2 = 120;
  22461. * };
  22462. *
  22463. * $scope.$on('$destroy', function() {
  22464. * // Make sure that the interval is destroyed too
  22465. * $scope.stopFight();
  22466. * });
  22467. * }])
  22468. * // Register the 'myCurrentTime' directive factory method.
  22469. * // We inject $interval and dateFilter service since the factory method is DI.
  22470. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  22471. * function($interval, dateFilter) {
  22472. * // return the directive link function. (compile function not needed)
  22473. * return function(scope, element, attrs) {
  22474. * var format, // date format
  22475. * stopTime; // so that we can cancel the time updates
  22476. *
  22477. * // used to update the UI
  22478. * function updateTime() {
  22479. * element.text(dateFilter(new Date(), format));
  22480. * }
  22481. *
  22482. * // watch the expression, and update the UI on change.
  22483. * scope.$watch(attrs.myCurrentTime, function(value) {
  22484. * format = value;
  22485. * updateTime();
  22486. * });
  22487. *
  22488. * stopTime = $interval(updateTime, 1000);
  22489. *
  22490. * // listen on DOM destroy (removal) event, and cancel the next UI update
  22491. * // to prevent updating time after the DOM element was removed.
  22492. * element.on('$destroy', function() {
  22493. * $interval.cancel(stopTime);
  22494. * });
  22495. * }
  22496. * }]);
  22497. * </script>
  22498. *
  22499. * <div>
  22500. * <div ng-controller="ExampleController">
  22501. * <label>Date format: <input ng-model="format"></label> <hr/>
  22502. * Current time is: <span my-current-time="format"></span>
  22503. * <hr/>
  22504. * Blood 1 : <font color='red'>{{blood_1}}</font>
  22505. * Blood 2 : <font color='red'>{{blood_2}}</font>
  22506. * <button type="button" data-ng-click="fight()">Fight</button>
  22507. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  22508. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  22509. * </div>
  22510. * </div>
  22511. *
  22512. * </file>
  22513. * </example>
  22514. */
  22515. function interval(fn, delay, count, invokeApply) {
  22516. var hasParams = arguments.length > 4,
  22517. args = hasParams ? sliceArgs(arguments, 4) : [],
  22518. setInterval = $window.setInterval,
  22519. clearInterval = $window.clearInterval,
  22520. iteration = 0,
  22521. skipApply = (isDefined(invokeApply) && !invokeApply),
  22522. deferred = (skipApply ? $$q : $q).defer(),
  22523. promise = deferred.promise;
  22524. count = isDefined(count) ? count : 0;
  22525. promise.$$intervalId = setInterval(function tick() {
  22526. if (skipApply) {
  22527. $browser.defer(callback);
  22528. } else {
  22529. $rootScope.$evalAsync(callback);
  22530. }
  22531. deferred.notify(iteration++);
  22532. if (count > 0 && iteration >= count) {
  22533. deferred.resolve(iteration);
  22534. clearInterval(promise.$$intervalId);
  22535. delete intervals[promise.$$intervalId];
  22536. }
  22537. if (!skipApply) $rootScope.$apply();
  22538. }, delay);
  22539. intervals[promise.$$intervalId] = deferred;
  22540. return promise;
  22541. function callback() {
  22542. if (!hasParams) {
  22543. fn(iteration);
  22544. } else {
  22545. fn.apply(null, args);
  22546. }
  22547. }
  22548. }
  22549. /**
  22550. * @ngdoc method
  22551. * @name $interval#cancel
  22552. *
  22553. * @description
  22554. * Cancels a task associated with the `promise`.
  22555. *
  22556. * @param {Promise=} promise returned by the `$interval` function.
  22557. * @returns {boolean} Returns `true` if the task was successfully canceled.
  22558. */
  22559. interval.cancel = function(promise) {
  22560. if (promise && promise.$$intervalId in intervals) {
  22561. intervals[promise.$$intervalId].reject('canceled');
  22562. $window.clearInterval(promise.$$intervalId);
  22563. delete intervals[promise.$$intervalId];
  22564. return true;
  22565. }
  22566. return false;
  22567. };
  22568. return interval;
  22569. }];
  22570. }
  22571. /**
  22572. * @ngdoc service
  22573. * @name $locale
  22574. *
  22575. * @description
  22576. * $locale service provides localization rules for various Angular components. As of right now the
  22577. * only public api is:
  22578. *
  22579. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  22580. */
  22581. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  22582. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  22583. var $locationMinErr = minErr('$location');
  22584. /**
  22585. * Encode path using encodeUriSegment, ignoring forward slashes
  22586. *
  22587. * @param {string} path Path to encode
  22588. * @returns {string}
  22589. */
  22590. function encodePath(path) {
  22591. var segments = path.split('/'),
  22592. i = segments.length;
  22593. while (i--) {
  22594. segments[i] = encodeUriSegment(segments[i]);
  22595. }
  22596. return segments.join('/');
  22597. }
  22598. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  22599. var parsedUrl = urlResolve(absoluteUrl);
  22600. locationObj.$$protocol = parsedUrl.protocol;
  22601. locationObj.$$host = parsedUrl.hostname;
  22602. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  22603. }
  22604. function parseAppUrl(relativeUrl, locationObj) {
  22605. var prefixed = (relativeUrl.charAt(0) !== '/');
  22606. if (prefixed) {
  22607. relativeUrl = '/' + relativeUrl;
  22608. }
  22609. var match = urlResolve(relativeUrl);
  22610. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  22611. match.pathname.substring(1) : match.pathname);
  22612. locationObj.$$search = parseKeyValue(match.search);
  22613. locationObj.$$hash = decodeURIComponent(match.hash);
  22614. // make sure path starts with '/';
  22615. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  22616. locationObj.$$path = '/' + locationObj.$$path;
  22617. }
  22618. }
  22619. /**
  22620. *
  22621. * @param {string} begin
  22622. * @param {string} whole
  22623. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  22624. * expected string.
  22625. */
  22626. function beginsWith(begin, whole) {
  22627. if (whole.indexOf(begin) === 0) {
  22628. return whole.substr(begin.length);
  22629. }
  22630. }
  22631. function stripHash(url) {
  22632. var index = url.indexOf('#');
  22633. return index == -1 ? url : url.substr(0, index);
  22634. }
  22635. function trimEmptyHash(url) {
  22636. return url.replace(/(#.+)|#$/, '$1');
  22637. }
  22638. function stripFile(url) {
  22639. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  22640. }
  22641. /* return the server only (scheme://host:port) */
  22642. function serverBase(url) {
  22643. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  22644. }
  22645. /**
  22646. * LocationHtml5Url represents an url
  22647. * This object is exposed as $location service when HTML5 mode is enabled and supported
  22648. *
  22649. * @constructor
  22650. * @param {string} appBase application base URL
  22651. * @param {string} appBaseNoFile application base URL stripped of any filename
  22652. * @param {string} basePrefix url path prefix
  22653. */
  22654. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  22655. this.$$html5 = true;
  22656. basePrefix = basePrefix || '';
  22657. parseAbsoluteUrl(appBase, this);
  22658. /**
  22659. * Parse given html5 (regular) url string into properties
  22660. * @param {string} url HTML5 url
  22661. * @private
  22662. */
  22663. this.$$parse = function(url) {
  22664. var pathUrl = beginsWith(appBaseNoFile, url);
  22665. if (!isString(pathUrl)) {
  22666. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  22667. appBaseNoFile);
  22668. }
  22669. parseAppUrl(pathUrl, this);
  22670. if (!this.$$path) {
  22671. this.$$path = '/';
  22672. }
  22673. this.$$compose();
  22674. };
  22675. /**
  22676. * Compose url and update `absUrl` property
  22677. * @private
  22678. */
  22679. this.$$compose = function() {
  22680. var search = toKeyValue(this.$$search),
  22681. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22682. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22683. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  22684. };
  22685. this.$$parseLinkUrl = function(url, relHref) {
  22686. if (relHref && relHref[0] === '#') {
  22687. // special case for links to hash fragments:
  22688. // keep the old url and only replace the hash fragment
  22689. this.hash(relHref.slice(1));
  22690. return true;
  22691. }
  22692. var appUrl, prevAppUrl;
  22693. var rewrittenUrl;
  22694. if (isDefined(appUrl = beginsWith(appBase, url))) {
  22695. prevAppUrl = appUrl;
  22696. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  22697. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  22698. } else {
  22699. rewrittenUrl = appBase + prevAppUrl;
  22700. }
  22701. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  22702. rewrittenUrl = appBaseNoFile + appUrl;
  22703. } else if (appBaseNoFile == url + '/') {
  22704. rewrittenUrl = appBaseNoFile;
  22705. }
  22706. if (rewrittenUrl) {
  22707. this.$$parse(rewrittenUrl);
  22708. }
  22709. return !!rewrittenUrl;
  22710. };
  22711. }
  22712. /**
  22713. * LocationHashbangUrl represents url
  22714. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  22715. * It also serves as the base class for html5 mode fallback on legacy browsers.
  22716. *
  22717. * @constructor
  22718. * @param {string} appBase application base URL
  22719. * @param {string} appBaseNoFile application base URL stripped of any filename
  22720. * @param {string} hashPrefix hashbang prefix
  22721. */
  22722. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  22723. parseAbsoluteUrl(appBase, this);
  22724. /**
  22725. * Parse given hashbang url into properties
  22726. * @param {string} url Hashbang url
  22727. * @private
  22728. */
  22729. this.$$parse = function(url) {
  22730. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  22731. var withoutHashUrl;
  22732. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  22733. // The rest of the url starts with a hash so we have
  22734. // got either a hashbang path or a plain hash fragment
  22735. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  22736. if (isUndefined(withoutHashUrl)) {
  22737. // There was no hashbang prefix so we just have a hash fragment
  22738. withoutHashUrl = withoutBaseUrl;
  22739. }
  22740. } else {
  22741. // There was no hashbang path nor hash fragment:
  22742. // If we are in HTML5 mode we use what is left as the path;
  22743. // Otherwise we ignore what is left
  22744. if (this.$$html5) {
  22745. withoutHashUrl = withoutBaseUrl;
  22746. } else {
  22747. withoutHashUrl = '';
  22748. if (isUndefined(withoutBaseUrl)) {
  22749. appBase = url;
  22750. this.replace();
  22751. }
  22752. }
  22753. }
  22754. parseAppUrl(withoutHashUrl, this);
  22755. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  22756. this.$$compose();
  22757. /*
  22758. * In Windows, on an anchor node on documents loaded from
  22759. * the filesystem, the browser will return a pathname
  22760. * prefixed with the drive name ('/C:/path') when a
  22761. * pathname without a drive is set:
  22762. * * a.setAttribute('href', '/foo')
  22763. * * a.pathname === '/C:/foo' //true
  22764. *
  22765. * Inside of Angular, we're always using pathnames that
  22766. * do not include drive names for routing.
  22767. */
  22768. function removeWindowsDriveName(path, url, base) {
  22769. /*
  22770. Matches paths for file protocol on windows,
  22771. such as /C:/foo/bar, and captures only /foo/bar.
  22772. */
  22773. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  22774. var firstPathSegmentMatch;
  22775. //Get the relative path from the input URL.
  22776. if (url.indexOf(base) === 0) {
  22777. url = url.replace(base, '');
  22778. }
  22779. // The input URL intentionally contains a first path segment that ends with a colon.
  22780. if (windowsFilePathExp.exec(url)) {
  22781. return path;
  22782. }
  22783. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  22784. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  22785. }
  22786. };
  22787. /**
  22788. * Compose hashbang url and update `absUrl` property
  22789. * @private
  22790. */
  22791. this.$$compose = function() {
  22792. var search = toKeyValue(this.$$search),
  22793. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22794. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22795. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  22796. };
  22797. this.$$parseLinkUrl = function(url, relHref) {
  22798. if (stripHash(appBase) == stripHash(url)) {
  22799. this.$$parse(url);
  22800. return true;
  22801. }
  22802. return false;
  22803. };
  22804. }
  22805. /**
  22806. * LocationHashbangUrl represents url
  22807. * This object is exposed as $location service when html5 history api is enabled but the browser
  22808. * does not support it.
  22809. *
  22810. * @constructor
  22811. * @param {string} appBase application base URL
  22812. * @param {string} appBaseNoFile application base URL stripped of any filename
  22813. * @param {string} hashPrefix hashbang prefix
  22814. */
  22815. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  22816. this.$$html5 = true;
  22817. LocationHashbangUrl.apply(this, arguments);
  22818. this.$$parseLinkUrl = function(url, relHref) {
  22819. if (relHref && relHref[0] === '#') {
  22820. // special case for links to hash fragments:
  22821. // keep the old url and only replace the hash fragment
  22822. this.hash(relHref.slice(1));
  22823. return true;
  22824. }
  22825. var rewrittenUrl;
  22826. var appUrl;
  22827. if (appBase == stripHash(url)) {
  22828. rewrittenUrl = url;
  22829. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  22830. rewrittenUrl = appBase + hashPrefix + appUrl;
  22831. } else if (appBaseNoFile === url + '/') {
  22832. rewrittenUrl = appBaseNoFile;
  22833. }
  22834. if (rewrittenUrl) {
  22835. this.$$parse(rewrittenUrl);
  22836. }
  22837. return !!rewrittenUrl;
  22838. };
  22839. this.$$compose = function() {
  22840. var search = toKeyValue(this.$$search),
  22841. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  22842. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  22843. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  22844. this.$$absUrl = appBase + hashPrefix + this.$$url;
  22845. };
  22846. }
  22847. var locationPrototype = {
  22848. /**
  22849. * Are we in html5 mode?
  22850. * @private
  22851. */
  22852. $$html5: false,
  22853. /**
  22854. * Has any change been replacing?
  22855. * @private
  22856. */
  22857. $$replace: false,
  22858. /**
  22859. * @ngdoc method
  22860. * @name $location#absUrl
  22861. *
  22862. * @description
  22863. * This method is getter only.
  22864. *
  22865. * Return full url representation with all segments encoded according to rules specified in
  22866. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  22867. *
  22868. *
  22869. * ```js
  22870. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22871. * var absUrl = $location.absUrl();
  22872. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  22873. * ```
  22874. *
  22875. * @return {string} full url
  22876. */
  22877. absUrl: locationGetter('$$absUrl'),
  22878. /**
  22879. * @ngdoc method
  22880. * @name $location#url
  22881. *
  22882. * @description
  22883. * This method is getter / setter.
  22884. *
  22885. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  22886. *
  22887. * Change path, search and hash, when called with parameter and return `$location`.
  22888. *
  22889. *
  22890. * ```js
  22891. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22892. * var url = $location.url();
  22893. * // => "/some/path?foo=bar&baz=xoxo"
  22894. * ```
  22895. *
  22896. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  22897. * @return {string} url
  22898. */
  22899. url: function(url) {
  22900. if (isUndefined(url)) {
  22901. return this.$$url;
  22902. }
  22903. var match = PATH_MATCH.exec(url);
  22904. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  22905. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  22906. this.hash(match[5] || '');
  22907. return this;
  22908. },
  22909. /**
  22910. * @ngdoc method
  22911. * @name $location#protocol
  22912. *
  22913. * @description
  22914. * This method is getter only.
  22915. *
  22916. * Return protocol of current url.
  22917. *
  22918. *
  22919. * ```js
  22920. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22921. * var protocol = $location.protocol();
  22922. * // => "http"
  22923. * ```
  22924. *
  22925. * @return {string} protocol of current url
  22926. */
  22927. protocol: locationGetter('$$protocol'),
  22928. /**
  22929. * @ngdoc method
  22930. * @name $location#host
  22931. *
  22932. * @description
  22933. * This method is getter only.
  22934. *
  22935. * Return host of current url.
  22936. *
  22937. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  22938. *
  22939. *
  22940. * ```js
  22941. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22942. * var host = $location.host();
  22943. * // => "example.com"
  22944. *
  22945. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  22946. * host = $location.host();
  22947. * // => "example.com"
  22948. * host = location.host;
  22949. * // => "example.com:8080"
  22950. * ```
  22951. *
  22952. * @return {string} host of current url.
  22953. */
  22954. host: locationGetter('$$host'),
  22955. /**
  22956. * @ngdoc method
  22957. * @name $location#port
  22958. *
  22959. * @description
  22960. * This method is getter only.
  22961. *
  22962. * Return port of current url.
  22963. *
  22964. *
  22965. * ```js
  22966. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22967. * var port = $location.port();
  22968. * // => 80
  22969. * ```
  22970. *
  22971. * @return {Number} port
  22972. */
  22973. port: locationGetter('$$port'),
  22974. /**
  22975. * @ngdoc method
  22976. * @name $location#path
  22977. *
  22978. * @description
  22979. * This method is getter / setter.
  22980. *
  22981. * Return path of current url when called without any parameter.
  22982. *
  22983. * Change path when called with parameter and return `$location`.
  22984. *
  22985. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  22986. * if it is missing.
  22987. *
  22988. *
  22989. * ```js
  22990. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  22991. * var path = $location.path();
  22992. * // => "/some/path"
  22993. * ```
  22994. *
  22995. * @param {(string|number)=} path New path
  22996. * @return {string} path
  22997. */
  22998. path: locationGetterSetter('$$path', function(path) {
  22999. path = path !== null ? path.toString() : '';
  23000. return path.charAt(0) == '/' ? path : '/' + path;
  23001. }),
  23002. /**
  23003. * @ngdoc method
  23004. * @name $location#search
  23005. *
  23006. * @description
  23007. * This method is getter / setter.
  23008. *
  23009. * Return search part (as object) of current url when called without any parameter.
  23010. *
  23011. * Change search part when called with parameter and return `$location`.
  23012. *
  23013. *
  23014. * ```js
  23015. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  23016. * var searchObject = $location.search();
  23017. * // => {foo: 'bar', baz: 'xoxo'}
  23018. *
  23019. * // set foo to 'yipee'
  23020. * $location.search('foo', 'yipee');
  23021. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  23022. * ```
  23023. *
  23024. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  23025. * hash object.
  23026. *
  23027. * When called with a single argument the method acts as a setter, setting the `search` component
  23028. * of `$location` to the specified value.
  23029. *
  23030. * If the argument is a hash object containing an array of values, these values will be encoded
  23031. * as duplicate search parameters in the url.
  23032. *
  23033. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  23034. * will override only a single search property.
  23035. *
  23036. * If `paramValue` is an array, it will override the property of the `search` component of
  23037. * `$location` specified via the first argument.
  23038. *
  23039. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  23040. *
  23041. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  23042. * value nor trailing equal sign.
  23043. *
  23044. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  23045. * one or more arguments returns `$location` object itself.
  23046. */
  23047. search: function(search, paramValue) {
  23048. switch (arguments.length) {
  23049. case 0:
  23050. return this.$$search;
  23051. case 1:
  23052. if (isString(search) || isNumber(search)) {
  23053. search = search.toString();
  23054. this.$$search = parseKeyValue(search);
  23055. } else if (isObject(search)) {
  23056. search = copy(search, {});
  23057. // remove object undefined or null properties
  23058. forEach(search, function(value, key) {
  23059. if (value == null) delete search[key];
  23060. });
  23061. this.$$search = search;
  23062. } else {
  23063. throw $locationMinErr('isrcharg',
  23064. 'The first argument of the `$location#search()` call must be a string or an object.');
  23065. }
  23066. break;
  23067. default:
  23068. if (isUndefined(paramValue) || paramValue === null) {
  23069. delete this.$$search[search];
  23070. } else {
  23071. this.$$search[search] = paramValue;
  23072. }
  23073. }
  23074. this.$$compose();
  23075. return this;
  23076. },
  23077. /**
  23078. * @ngdoc method
  23079. * @name $location#hash
  23080. *
  23081. * @description
  23082. * This method is getter / setter.
  23083. *
  23084. * Returns the hash fragment when called without any parameters.
  23085. *
  23086. * Changes the hash fragment when called with a parameter and returns `$location`.
  23087. *
  23088. *
  23089. * ```js
  23090. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  23091. * var hash = $location.hash();
  23092. * // => "hashValue"
  23093. * ```
  23094. *
  23095. * @param {(string|number)=} hash New hash fragment
  23096. * @return {string} hash
  23097. */
  23098. hash: locationGetterSetter('$$hash', function(hash) {
  23099. return hash !== null ? hash.toString() : '';
  23100. }),
  23101. /**
  23102. * @ngdoc method
  23103. * @name $location#replace
  23104. *
  23105. * @description
  23106. * If called, all changes to $location during the current `$digest` will replace the current history
  23107. * record, instead of adding a new one.
  23108. */
  23109. replace: function() {
  23110. this.$$replace = true;
  23111. return this;
  23112. }
  23113. };
  23114. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  23115. Location.prototype = Object.create(locationPrototype);
  23116. /**
  23117. * @ngdoc method
  23118. * @name $location#state
  23119. *
  23120. * @description
  23121. * This method is getter / setter.
  23122. *
  23123. * Return the history state object when called without any parameter.
  23124. *
  23125. * Change the history state object when called with one parameter and return `$location`.
  23126. * The state object is later passed to `pushState` or `replaceState`.
  23127. *
  23128. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  23129. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  23130. * older browsers (like IE9 or Android < 4.0), don't use this method.
  23131. *
  23132. * @param {object=} state State object for pushState or replaceState
  23133. * @return {object} state
  23134. */
  23135. Location.prototype.state = function(state) {
  23136. if (!arguments.length) {
  23137. return this.$$state;
  23138. }
  23139. if (Location !== LocationHtml5Url || !this.$$html5) {
  23140. throw $locationMinErr('nostate', 'History API state support is available only ' +
  23141. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  23142. }
  23143. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  23144. // but we're changing the $$state reference to $browser.state() during the $digest
  23145. // so the modification window is narrow.
  23146. this.$$state = isUndefined(state) ? null : state;
  23147. return this;
  23148. };
  23149. });
  23150. function locationGetter(property) {
  23151. return function() {
  23152. return this[property];
  23153. };
  23154. }
  23155. function locationGetterSetter(property, preprocess) {
  23156. return function(value) {
  23157. if (isUndefined(value)) {
  23158. return this[property];
  23159. }
  23160. this[property] = preprocess(value);
  23161. this.$$compose();
  23162. return this;
  23163. };
  23164. }
  23165. /**
  23166. * @ngdoc service
  23167. * @name $location
  23168. *
  23169. * @requires $rootElement
  23170. *
  23171. * @description
  23172. * The $location service parses the URL in the browser address bar (based on the
  23173. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  23174. * available to your application. Changes to the URL in the address bar are reflected into
  23175. * $location service and changes to $location are reflected into the browser address bar.
  23176. *
  23177. * **The $location service:**
  23178. *
  23179. * - Exposes the current URL in the browser address bar, so you can
  23180. * - Watch and observe the URL.
  23181. * - Change the URL.
  23182. * - Synchronizes the URL with the browser when the user
  23183. * - Changes the address bar.
  23184. * - Clicks the back or forward button (or clicks a History link).
  23185. * - Clicks on a link.
  23186. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  23187. *
  23188. * For more information see {@link guide/$location Developer Guide: Using $location}
  23189. */
  23190. /**
  23191. * @ngdoc provider
  23192. * @name $locationProvider
  23193. * @description
  23194. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  23195. */
  23196. function $LocationProvider() {
  23197. var hashPrefix = '',
  23198. html5Mode = {
  23199. enabled: false,
  23200. requireBase: true,
  23201. rewriteLinks: true
  23202. };
  23203. /**
  23204. * @ngdoc method
  23205. * @name $locationProvider#hashPrefix
  23206. * @description
  23207. * @param {string=} prefix Prefix for hash part (containing path and search)
  23208. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  23209. */
  23210. this.hashPrefix = function(prefix) {
  23211. if (isDefined(prefix)) {
  23212. hashPrefix = prefix;
  23213. return this;
  23214. } else {
  23215. return hashPrefix;
  23216. }
  23217. };
  23218. /**
  23219. * @ngdoc method
  23220. * @name $locationProvider#html5Mode
  23221. * @description
  23222. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  23223. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  23224. * properties:
  23225. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  23226. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  23227. * support `pushState`.
  23228. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  23229. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  23230. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  23231. * See the {@link guide/$location $location guide for more information}
  23232. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  23233. * enables/disables url rewriting for relative links.
  23234. *
  23235. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  23236. */
  23237. this.html5Mode = function(mode) {
  23238. if (isBoolean(mode)) {
  23239. html5Mode.enabled = mode;
  23240. return this;
  23241. } else if (isObject(mode)) {
  23242. if (isBoolean(mode.enabled)) {
  23243. html5Mode.enabled = mode.enabled;
  23244. }
  23245. if (isBoolean(mode.requireBase)) {
  23246. html5Mode.requireBase = mode.requireBase;
  23247. }
  23248. if (isBoolean(mode.rewriteLinks)) {
  23249. html5Mode.rewriteLinks = mode.rewriteLinks;
  23250. }
  23251. return this;
  23252. } else {
  23253. return html5Mode;
  23254. }
  23255. };
  23256. /**
  23257. * @ngdoc event
  23258. * @name $location#$locationChangeStart
  23259. * @eventType broadcast on root scope
  23260. * @description
  23261. * Broadcasted before a URL will change.
  23262. *
  23263. * This change can be prevented by calling
  23264. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  23265. * details about event object. Upon successful change
  23266. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  23267. *
  23268. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  23269. * the browser supports the HTML5 History API.
  23270. *
  23271. * @param {Object} angularEvent Synthetic event object.
  23272. * @param {string} newUrl New URL
  23273. * @param {string=} oldUrl URL that was before it was changed.
  23274. * @param {string=} newState New history state object
  23275. * @param {string=} oldState History state object that was before it was changed.
  23276. */
  23277. /**
  23278. * @ngdoc event
  23279. * @name $location#$locationChangeSuccess
  23280. * @eventType broadcast on root scope
  23281. * @description
  23282. * Broadcasted after a URL was changed.
  23283. *
  23284. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  23285. * the browser supports the HTML5 History API.
  23286. *
  23287. * @param {Object} angularEvent Synthetic event object.
  23288. * @param {string} newUrl New URL
  23289. * @param {string=} oldUrl URL that was before it was changed.
  23290. * @param {string=} newState New history state object
  23291. * @param {string=} oldState History state object that was before it was changed.
  23292. */
  23293. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  23294. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  23295. var $location,
  23296. LocationMode,
  23297. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  23298. initialUrl = $browser.url(),
  23299. appBase;
  23300. if (html5Mode.enabled) {
  23301. if (!baseHref && html5Mode.requireBase) {
  23302. throw $locationMinErr('nobase',
  23303. "$location in HTML5 mode requires a <base> tag to be present!");
  23304. }
  23305. appBase = serverBase(initialUrl) + (baseHref || '/');
  23306. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  23307. } else {
  23308. appBase = stripHash(initialUrl);
  23309. LocationMode = LocationHashbangUrl;
  23310. }
  23311. var appBaseNoFile = stripFile(appBase);
  23312. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  23313. $location.$$parseLinkUrl(initialUrl, initialUrl);
  23314. $location.$$state = $browser.state();
  23315. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  23316. function setBrowserUrlWithFallback(url, replace, state) {
  23317. var oldUrl = $location.url();
  23318. var oldState = $location.$$state;
  23319. try {
  23320. $browser.url(url, replace, state);
  23321. // Make sure $location.state() returns referentially identical (not just deeply equal)
  23322. // state object; this makes possible quick checking if the state changed in the digest
  23323. // loop. Checking deep equality would be too expensive.
  23324. $location.$$state = $browser.state();
  23325. } catch (e) {
  23326. // Restore old values if pushState fails
  23327. $location.url(oldUrl);
  23328. $location.$$state = oldState;
  23329. throw e;
  23330. }
  23331. }
  23332. $rootElement.on('click', function(event) {
  23333. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  23334. // currently we open nice url link and redirect then
  23335. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  23336. var elm = jqLite(event.target);
  23337. // traverse the DOM up to find first A tag
  23338. while (nodeName_(elm[0]) !== 'a') {
  23339. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  23340. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  23341. }
  23342. var absHref = elm.prop('href');
  23343. // get the actual href attribute - see
  23344. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  23345. var relHref = elm.attr('href') || elm.attr('xlink:href');
  23346. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  23347. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  23348. // an animation.
  23349. absHref = urlResolve(absHref.animVal).href;
  23350. }
  23351. // Ignore when url is started with javascript: or mailto:
  23352. if (IGNORE_URI_REGEXP.test(absHref)) return;
  23353. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  23354. if ($location.$$parseLinkUrl(absHref, relHref)) {
  23355. // We do a preventDefault for all urls that are part of the angular application,
  23356. // in html5mode and also without, so that we are able to abort navigation without
  23357. // getting double entries in the location history.
  23358. event.preventDefault();
  23359. // update location manually
  23360. if ($location.absUrl() != $browser.url()) {
  23361. $rootScope.$apply();
  23362. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  23363. $window.angular['ff-684208-preventDefault'] = true;
  23364. }
  23365. }
  23366. }
  23367. });
  23368. // rewrite hashbang url <> html5 url
  23369. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  23370. $browser.url($location.absUrl(), true);
  23371. }
  23372. var initializing = true;
  23373. // update $location when $browser url changes
  23374. $browser.onUrlChange(function(newUrl, newState) {
  23375. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  23376. // If we are navigating outside of the app then force a reload
  23377. $window.location.href = newUrl;
  23378. return;
  23379. }
  23380. $rootScope.$evalAsync(function() {
  23381. var oldUrl = $location.absUrl();
  23382. var oldState = $location.$$state;
  23383. var defaultPrevented;
  23384. newUrl = trimEmptyHash(newUrl);
  23385. $location.$$parse(newUrl);
  23386. $location.$$state = newState;
  23387. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  23388. newState, oldState).defaultPrevented;
  23389. // if the location was changed by a `$locationChangeStart` handler then stop
  23390. // processing this location change
  23391. if ($location.absUrl() !== newUrl) return;
  23392. if (defaultPrevented) {
  23393. $location.$$parse(oldUrl);
  23394. $location.$$state = oldState;
  23395. setBrowserUrlWithFallback(oldUrl, false, oldState);
  23396. } else {
  23397. initializing = false;
  23398. afterLocationChange(oldUrl, oldState);
  23399. }
  23400. });
  23401. if (!$rootScope.$$phase) $rootScope.$digest();
  23402. });
  23403. // update browser
  23404. $rootScope.$watch(function $locationWatch() {
  23405. var oldUrl = trimEmptyHash($browser.url());
  23406. var newUrl = trimEmptyHash($location.absUrl());
  23407. var oldState = $browser.state();
  23408. var currentReplace = $location.$$replace;
  23409. var urlOrStateChanged = oldUrl !== newUrl ||
  23410. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  23411. if (initializing || urlOrStateChanged) {
  23412. initializing = false;
  23413. $rootScope.$evalAsync(function() {
  23414. var newUrl = $location.absUrl();
  23415. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  23416. $location.$$state, oldState).defaultPrevented;
  23417. // if the location was changed by a `$locationChangeStart` handler then stop
  23418. // processing this location change
  23419. if ($location.absUrl() !== newUrl) return;
  23420. if (defaultPrevented) {
  23421. $location.$$parse(oldUrl);
  23422. $location.$$state = oldState;
  23423. } else {
  23424. if (urlOrStateChanged) {
  23425. setBrowserUrlWithFallback(newUrl, currentReplace,
  23426. oldState === $location.$$state ? null : $location.$$state);
  23427. }
  23428. afterLocationChange(oldUrl, oldState);
  23429. }
  23430. });
  23431. }
  23432. $location.$$replace = false;
  23433. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  23434. // there is a change
  23435. });
  23436. return $location;
  23437. function afterLocationChange(oldUrl, oldState) {
  23438. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  23439. $location.$$state, oldState);
  23440. }
  23441. }];
  23442. }
  23443. /**
  23444. * @ngdoc service
  23445. * @name $log
  23446. * @requires $window
  23447. *
  23448. * @description
  23449. * Simple service for logging. Default implementation safely writes the message
  23450. * into the browser's console (if present).
  23451. *
  23452. * The main purpose of this service is to simplify debugging and troubleshooting.
  23453. *
  23454. * The default is to log `debug` messages. You can use
  23455. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  23456. *
  23457. * @example
  23458. <example module="logExample">
  23459. <file name="script.js">
  23460. angular.module('logExample', [])
  23461. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  23462. $scope.$log = $log;
  23463. $scope.message = 'Hello World!';
  23464. }]);
  23465. </file>
  23466. <file name="index.html">
  23467. <div ng-controller="LogController">
  23468. <p>Reload this page with open console, enter text and hit the log button...</p>
  23469. <label>Message:
  23470. <input type="text" ng-model="message" /></label>
  23471. <button ng-click="$log.log(message)">log</button>
  23472. <button ng-click="$log.warn(message)">warn</button>
  23473. <button ng-click="$log.info(message)">info</button>
  23474. <button ng-click="$log.error(message)">error</button>
  23475. <button ng-click="$log.debug(message)">debug</button>
  23476. </div>
  23477. </file>
  23478. </example>
  23479. */
  23480. /**
  23481. * @ngdoc provider
  23482. * @name $logProvider
  23483. * @description
  23484. * Use the `$logProvider` to configure how the application logs messages
  23485. */
  23486. function $LogProvider() {
  23487. var debug = true,
  23488. self = this;
  23489. /**
  23490. * @ngdoc method
  23491. * @name $logProvider#debugEnabled
  23492. * @description
  23493. * @param {boolean=} flag enable or disable debug level messages
  23494. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  23495. */
  23496. this.debugEnabled = function(flag) {
  23497. if (isDefined(flag)) {
  23498. debug = flag;
  23499. return this;
  23500. } else {
  23501. return debug;
  23502. }
  23503. };
  23504. this.$get = ['$window', function($window) {
  23505. return {
  23506. /**
  23507. * @ngdoc method
  23508. * @name $log#log
  23509. *
  23510. * @description
  23511. * Write a log message
  23512. */
  23513. log: consoleLog('log'),
  23514. /**
  23515. * @ngdoc method
  23516. * @name $log#info
  23517. *
  23518. * @description
  23519. * Write an information message
  23520. */
  23521. info: consoleLog('info'),
  23522. /**
  23523. * @ngdoc method
  23524. * @name $log#warn
  23525. *
  23526. * @description
  23527. * Write a warning message
  23528. */
  23529. warn: consoleLog('warn'),
  23530. /**
  23531. * @ngdoc method
  23532. * @name $log#error
  23533. *
  23534. * @description
  23535. * Write an error message
  23536. */
  23537. error: consoleLog('error'),
  23538. /**
  23539. * @ngdoc method
  23540. * @name $log#debug
  23541. *
  23542. * @description
  23543. * Write a debug message
  23544. */
  23545. debug: (function() {
  23546. var fn = consoleLog('debug');
  23547. return function() {
  23548. if (debug) {
  23549. fn.apply(self, arguments);
  23550. }
  23551. };
  23552. }())
  23553. };
  23554. function formatError(arg) {
  23555. if (arg instanceof Error) {
  23556. if (arg.stack) {
  23557. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  23558. ? 'Error: ' + arg.message + '\n' + arg.stack
  23559. : arg.stack;
  23560. } else if (arg.sourceURL) {
  23561. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  23562. }
  23563. }
  23564. return arg;
  23565. }
  23566. function consoleLog(type) {
  23567. var console = $window.console || {},
  23568. logFn = console[type] || console.log || noop,
  23569. hasApply = false;
  23570. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  23571. // The reason behind this is that console.log has type "object" in IE8...
  23572. try {
  23573. hasApply = !!logFn.apply;
  23574. } catch (e) {}
  23575. if (hasApply) {
  23576. return function() {
  23577. var args = [];
  23578. forEach(arguments, function(arg) {
  23579. args.push(formatError(arg));
  23580. });
  23581. return logFn.apply(console, args);
  23582. };
  23583. }
  23584. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  23585. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  23586. return function(arg1, arg2) {
  23587. logFn(arg1, arg2 == null ? '' : arg2);
  23588. };
  23589. }
  23590. }];
  23591. }
  23592. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  23593. * Any commits to this file should be reviewed with security in mind. *
  23594. * Changes to this file can potentially create security vulnerabilities. *
  23595. * An approval from 2 Core members with history of modifying *
  23596. * this file is required. *
  23597. * *
  23598. * Does the change somehow allow for arbitrary javascript to be executed? *
  23599. * Or allows for someone to change the prototype of built-in objects? *
  23600. * Or gives undesired access to variables likes document or window? *
  23601. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  23602. var $parseMinErr = minErr('$parse');
  23603. // Sandboxing Angular Expressions
  23604. // ------------------------------
  23605. // Angular expressions are generally considered safe because these expressions only have direct
  23606. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  23607. // obtaining a reference to native JS functions such as the Function constructor.
  23608. //
  23609. // As an example, consider the following Angular expression:
  23610. //
  23611. // {}.toString.constructor('alert("evil JS code")')
  23612. //
  23613. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  23614. // against the expression language, but not to prevent exploits that were enabled by exposing
  23615. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  23616. // practice and therefore we are not even trying to protect against interaction with an object
  23617. // explicitly exposed in this way.
  23618. //
  23619. // In general, it is not possible to access a Window object from an angular expression unless a
  23620. // window or some DOM object that has a reference to window is published onto a Scope.
  23621. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  23622. // native objects.
  23623. //
  23624. // See https://docs.angularjs.org/guide/security
  23625. function ensureSafeMemberName(name, fullExpression) {
  23626. if (name === "__defineGetter__" || name === "__defineSetter__"
  23627. || name === "__lookupGetter__" || name === "__lookupSetter__"
  23628. || name === "__proto__") {
  23629. throw $parseMinErr('isecfld',
  23630. 'Attempting to access a disallowed field in Angular expressions! '
  23631. + 'Expression: {0}', fullExpression);
  23632. }
  23633. return name;
  23634. }
  23635. function getStringValue(name) {
  23636. // Property names must be strings. This means that non-string objects cannot be used
  23637. // as keys in an object. Any non-string object, including a number, is typecasted
  23638. // into a string via the toString method.
  23639. // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
  23640. //
  23641. // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
  23642. // to a string. It's not always possible. If `name` is an object and its `toString` method is
  23643. // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
  23644. //
  23645. // TypeError: Cannot convert object to primitive value
  23646. //
  23647. // For performance reasons, we don't catch this error here and allow it to propagate up the call
  23648. // stack. Note that you'll get the same error in JavaScript if you try to access a property using
  23649. // such a 'broken' object as a key.
  23650. return name + '';
  23651. }
  23652. function ensureSafeObject(obj, fullExpression) {
  23653. // nifty check if obj is Function that is fast and works across iframes and other contexts
  23654. if (obj) {
  23655. if (obj.constructor === obj) {
  23656. throw $parseMinErr('isecfn',
  23657. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  23658. fullExpression);
  23659. } else if (// isWindow(obj)
  23660. obj.window === obj) {
  23661. throw $parseMinErr('isecwindow',
  23662. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  23663. fullExpression);
  23664. } else if (// isElement(obj)
  23665. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  23666. throw $parseMinErr('isecdom',
  23667. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  23668. fullExpression);
  23669. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  23670. obj === Object) {
  23671. throw $parseMinErr('isecobj',
  23672. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  23673. fullExpression);
  23674. }
  23675. }
  23676. return obj;
  23677. }
  23678. var CALL = Function.prototype.call;
  23679. var APPLY = Function.prototype.apply;
  23680. var BIND = Function.prototype.bind;
  23681. function ensureSafeFunction(obj, fullExpression) {
  23682. if (obj) {
  23683. if (obj.constructor === obj) {
  23684. throw $parseMinErr('isecfn',
  23685. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  23686. fullExpression);
  23687. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  23688. throw $parseMinErr('isecff',
  23689. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  23690. fullExpression);
  23691. }
  23692. }
  23693. }
  23694. function ensureSafeAssignContext(obj, fullExpression) {
  23695. if (obj) {
  23696. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  23697. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  23698. throw $parseMinErr('isecaf',
  23699. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  23700. }
  23701. }
  23702. }
  23703. var OPERATORS = createMap();
  23704. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  23705. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  23706. /////////////////////////////////////////
  23707. /**
  23708. * @constructor
  23709. */
  23710. var Lexer = function(options) {
  23711. this.options = options;
  23712. };
  23713. Lexer.prototype = {
  23714. constructor: Lexer,
  23715. lex: function(text) {
  23716. this.text = text;
  23717. this.index = 0;
  23718. this.tokens = [];
  23719. while (this.index < this.text.length) {
  23720. var ch = this.text.charAt(this.index);
  23721. if (ch === '"' || ch === "'") {
  23722. this.readString(ch);
  23723. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  23724. this.readNumber();
  23725. } else if (this.isIdent(ch)) {
  23726. this.readIdent();
  23727. } else if (this.is(ch, '(){}[].,;:?')) {
  23728. this.tokens.push({index: this.index, text: ch});
  23729. this.index++;
  23730. } else if (this.isWhitespace(ch)) {
  23731. this.index++;
  23732. } else {
  23733. var ch2 = ch + this.peek();
  23734. var ch3 = ch2 + this.peek(2);
  23735. var op1 = OPERATORS[ch];
  23736. var op2 = OPERATORS[ch2];
  23737. var op3 = OPERATORS[ch3];
  23738. if (op1 || op2 || op3) {
  23739. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  23740. this.tokens.push({index: this.index, text: token, operator: true});
  23741. this.index += token.length;
  23742. } else {
  23743. this.throwError('Unexpected next character ', this.index, this.index + 1);
  23744. }
  23745. }
  23746. }
  23747. return this.tokens;
  23748. },
  23749. is: function(ch, chars) {
  23750. return chars.indexOf(ch) !== -1;
  23751. },
  23752. peek: function(i) {
  23753. var num = i || 1;
  23754. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  23755. },
  23756. isNumber: function(ch) {
  23757. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  23758. },
  23759. isWhitespace: function(ch) {
  23760. // IE treats non-breaking space as \u00A0
  23761. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  23762. ch === '\n' || ch === '\v' || ch === '\u00A0');
  23763. },
  23764. isIdent: function(ch) {
  23765. return ('a' <= ch && ch <= 'z' ||
  23766. 'A' <= ch && ch <= 'Z' ||
  23767. '_' === ch || ch === '$');
  23768. },
  23769. isExpOperator: function(ch) {
  23770. return (ch === '-' || ch === '+' || this.isNumber(ch));
  23771. },
  23772. throwError: function(error, start, end) {
  23773. end = end || this.index;
  23774. var colStr = (isDefined(start)
  23775. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  23776. : ' ' + end);
  23777. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  23778. error, colStr, this.text);
  23779. },
  23780. readNumber: function() {
  23781. var number = '';
  23782. var start = this.index;
  23783. while (this.index < this.text.length) {
  23784. var ch = lowercase(this.text.charAt(this.index));
  23785. if (ch == '.' || this.isNumber(ch)) {
  23786. number += ch;
  23787. } else {
  23788. var peekCh = this.peek();
  23789. if (ch == 'e' && this.isExpOperator(peekCh)) {
  23790. number += ch;
  23791. } else if (this.isExpOperator(ch) &&
  23792. peekCh && this.isNumber(peekCh) &&
  23793. number.charAt(number.length - 1) == 'e') {
  23794. number += ch;
  23795. } else if (this.isExpOperator(ch) &&
  23796. (!peekCh || !this.isNumber(peekCh)) &&
  23797. number.charAt(number.length - 1) == 'e') {
  23798. this.throwError('Invalid exponent');
  23799. } else {
  23800. break;
  23801. }
  23802. }
  23803. this.index++;
  23804. }
  23805. this.tokens.push({
  23806. index: start,
  23807. text: number,
  23808. constant: true,
  23809. value: Number(number)
  23810. });
  23811. },
  23812. readIdent: function() {
  23813. var start = this.index;
  23814. while (this.index < this.text.length) {
  23815. var ch = this.text.charAt(this.index);
  23816. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  23817. break;
  23818. }
  23819. this.index++;
  23820. }
  23821. this.tokens.push({
  23822. index: start,
  23823. text: this.text.slice(start, this.index),
  23824. identifier: true
  23825. });
  23826. },
  23827. readString: function(quote) {
  23828. var start = this.index;
  23829. this.index++;
  23830. var string = '';
  23831. var rawString = quote;
  23832. var escape = false;
  23833. while (this.index < this.text.length) {
  23834. var ch = this.text.charAt(this.index);
  23835. rawString += ch;
  23836. if (escape) {
  23837. if (ch === 'u') {
  23838. var hex = this.text.substring(this.index + 1, this.index + 5);
  23839. if (!hex.match(/[\da-f]{4}/i)) {
  23840. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  23841. }
  23842. this.index += 4;
  23843. string += String.fromCharCode(parseInt(hex, 16));
  23844. } else {
  23845. var rep = ESCAPE[ch];
  23846. string = string + (rep || ch);
  23847. }
  23848. escape = false;
  23849. } else if (ch === '\\') {
  23850. escape = true;
  23851. } else if (ch === quote) {
  23852. this.index++;
  23853. this.tokens.push({
  23854. index: start,
  23855. text: rawString,
  23856. constant: true,
  23857. value: string
  23858. });
  23859. return;
  23860. } else {
  23861. string += ch;
  23862. }
  23863. this.index++;
  23864. }
  23865. this.throwError('Unterminated quote', start);
  23866. }
  23867. };
  23868. var AST = function(lexer, options) {
  23869. this.lexer = lexer;
  23870. this.options = options;
  23871. };
  23872. AST.Program = 'Program';
  23873. AST.ExpressionStatement = 'ExpressionStatement';
  23874. AST.AssignmentExpression = 'AssignmentExpression';
  23875. AST.ConditionalExpression = 'ConditionalExpression';
  23876. AST.LogicalExpression = 'LogicalExpression';
  23877. AST.BinaryExpression = 'BinaryExpression';
  23878. AST.UnaryExpression = 'UnaryExpression';
  23879. AST.CallExpression = 'CallExpression';
  23880. AST.MemberExpression = 'MemberExpression';
  23881. AST.Identifier = 'Identifier';
  23882. AST.Literal = 'Literal';
  23883. AST.ArrayExpression = 'ArrayExpression';
  23884. AST.Property = 'Property';
  23885. AST.ObjectExpression = 'ObjectExpression';
  23886. AST.ThisExpression = 'ThisExpression';
  23887. AST.LocalsExpression = 'LocalsExpression';
  23888. // Internal use only
  23889. AST.NGValueParameter = 'NGValueParameter';
  23890. AST.prototype = {
  23891. ast: function(text) {
  23892. this.text = text;
  23893. this.tokens = this.lexer.lex(text);
  23894. var value = this.program();
  23895. if (this.tokens.length !== 0) {
  23896. this.throwError('is an unexpected token', this.tokens[0]);
  23897. }
  23898. return value;
  23899. },
  23900. program: function() {
  23901. var body = [];
  23902. while (true) {
  23903. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  23904. body.push(this.expressionStatement());
  23905. if (!this.expect(';')) {
  23906. return { type: AST.Program, body: body};
  23907. }
  23908. }
  23909. },
  23910. expressionStatement: function() {
  23911. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  23912. },
  23913. filterChain: function() {
  23914. var left = this.expression();
  23915. var token;
  23916. while ((token = this.expect('|'))) {
  23917. left = this.filter(left);
  23918. }
  23919. return left;
  23920. },
  23921. expression: function() {
  23922. return this.assignment();
  23923. },
  23924. assignment: function() {
  23925. var result = this.ternary();
  23926. if (this.expect('=')) {
  23927. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  23928. }
  23929. return result;
  23930. },
  23931. ternary: function() {
  23932. var test = this.logicalOR();
  23933. var alternate;
  23934. var consequent;
  23935. if (this.expect('?')) {
  23936. alternate = this.expression();
  23937. if (this.consume(':')) {
  23938. consequent = this.expression();
  23939. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  23940. }
  23941. }
  23942. return test;
  23943. },
  23944. logicalOR: function() {
  23945. var left = this.logicalAND();
  23946. while (this.expect('||')) {
  23947. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  23948. }
  23949. return left;
  23950. },
  23951. logicalAND: function() {
  23952. var left = this.equality();
  23953. while (this.expect('&&')) {
  23954. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  23955. }
  23956. return left;
  23957. },
  23958. equality: function() {
  23959. var left = this.relational();
  23960. var token;
  23961. while ((token = this.expect('==','!=','===','!=='))) {
  23962. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  23963. }
  23964. return left;
  23965. },
  23966. relational: function() {
  23967. var left = this.additive();
  23968. var token;
  23969. while ((token = this.expect('<', '>', '<=', '>='))) {
  23970. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  23971. }
  23972. return left;
  23973. },
  23974. additive: function() {
  23975. var left = this.multiplicative();
  23976. var token;
  23977. while ((token = this.expect('+','-'))) {
  23978. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  23979. }
  23980. return left;
  23981. },
  23982. multiplicative: function() {
  23983. var left = this.unary();
  23984. var token;
  23985. while ((token = this.expect('*','/','%'))) {
  23986. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  23987. }
  23988. return left;
  23989. },
  23990. unary: function() {
  23991. var token;
  23992. if ((token = this.expect('+', '-', '!'))) {
  23993. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  23994. } else {
  23995. return this.primary();
  23996. }
  23997. },
  23998. primary: function() {
  23999. var primary;
  24000. if (this.expect('(')) {
  24001. primary = this.filterChain();
  24002. this.consume(')');
  24003. } else if (this.expect('[')) {
  24004. primary = this.arrayDeclaration();
  24005. } else if (this.expect('{')) {
  24006. primary = this.object();
  24007. } else if (this.selfReferential.hasOwnProperty(this.peek().text)) {
  24008. primary = copy(this.selfReferential[this.consume().text]);
  24009. } else if (this.options.literals.hasOwnProperty(this.peek().text)) {
  24010. primary = { type: AST.Literal, value: this.options.literals[this.consume().text]};
  24011. } else if (this.peek().identifier) {
  24012. primary = this.identifier();
  24013. } else if (this.peek().constant) {
  24014. primary = this.constant();
  24015. } else {
  24016. this.throwError('not a primary expression', this.peek());
  24017. }
  24018. var next;
  24019. while ((next = this.expect('(', '[', '.'))) {
  24020. if (next.text === '(') {
  24021. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  24022. this.consume(')');
  24023. } else if (next.text === '[') {
  24024. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  24025. this.consume(']');
  24026. } else if (next.text === '.') {
  24027. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  24028. } else {
  24029. this.throwError('IMPOSSIBLE');
  24030. }
  24031. }
  24032. return primary;
  24033. },
  24034. filter: function(baseExpression) {
  24035. var args = [baseExpression];
  24036. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  24037. while (this.expect(':')) {
  24038. args.push(this.expression());
  24039. }
  24040. return result;
  24041. },
  24042. parseArguments: function() {
  24043. var args = [];
  24044. if (this.peekToken().text !== ')') {
  24045. do {
  24046. args.push(this.expression());
  24047. } while (this.expect(','));
  24048. }
  24049. return args;
  24050. },
  24051. identifier: function() {
  24052. var token = this.consume();
  24053. if (!token.identifier) {
  24054. this.throwError('is not a valid identifier', token);
  24055. }
  24056. return { type: AST.Identifier, name: token.text };
  24057. },
  24058. constant: function() {
  24059. // TODO check that it is a constant
  24060. return { type: AST.Literal, value: this.consume().value };
  24061. },
  24062. arrayDeclaration: function() {
  24063. var elements = [];
  24064. if (this.peekToken().text !== ']') {
  24065. do {
  24066. if (this.peek(']')) {
  24067. // Support trailing commas per ES5.1.
  24068. break;
  24069. }
  24070. elements.push(this.expression());
  24071. } while (this.expect(','));
  24072. }
  24073. this.consume(']');
  24074. return { type: AST.ArrayExpression, elements: elements };
  24075. },
  24076. object: function() {
  24077. var properties = [], property;
  24078. if (this.peekToken().text !== '}') {
  24079. do {
  24080. if (this.peek('}')) {
  24081. // Support trailing commas per ES5.1.
  24082. break;
  24083. }
  24084. property = {type: AST.Property, kind: 'init'};
  24085. if (this.peek().constant) {
  24086. property.key = this.constant();
  24087. } else if (this.peek().identifier) {
  24088. property.key = this.identifier();
  24089. } else {
  24090. this.throwError("invalid key", this.peek());
  24091. }
  24092. this.consume(':');
  24093. property.value = this.expression();
  24094. properties.push(property);
  24095. } while (this.expect(','));
  24096. }
  24097. this.consume('}');
  24098. return {type: AST.ObjectExpression, properties: properties };
  24099. },
  24100. throwError: function(msg, token) {
  24101. throw $parseMinErr('syntax',
  24102. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  24103. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  24104. },
  24105. consume: function(e1) {
  24106. if (this.tokens.length === 0) {
  24107. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  24108. }
  24109. var token = this.expect(e1);
  24110. if (!token) {
  24111. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  24112. }
  24113. return token;
  24114. },
  24115. peekToken: function() {
  24116. if (this.tokens.length === 0) {
  24117. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  24118. }
  24119. return this.tokens[0];
  24120. },
  24121. peek: function(e1, e2, e3, e4) {
  24122. return this.peekAhead(0, e1, e2, e3, e4);
  24123. },
  24124. peekAhead: function(i, e1, e2, e3, e4) {
  24125. if (this.tokens.length > i) {
  24126. var token = this.tokens[i];
  24127. var t = token.text;
  24128. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  24129. (!e1 && !e2 && !e3 && !e4)) {
  24130. return token;
  24131. }
  24132. }
  24133. return false;
  24134. },
  24135. expect: function(e1, e2, e3, e4) {
  24136. var token = this.peek(e1, e2, e3, e4);
  24137. if (token) {
  24138. this.tokens.shift();
  24139. return token;
  24140. }
  24141. return false;
  24142. },
  24143. selfReferential: {
  24144. 'this': {type: AST.ThisExpression },
  24145. '$locals': {type: AST.LocalsExpression }
  24146. }
  24147. };
  24148. function ifDefined(v, d) {
  24149. return typeof v !== 'undefined' ? v : d;
  24150. }
  24151. function plusFn(l, r) {
  24152. if (typeof l === 'undefined') return r;
  24153. if (typeof r === 'undefined') return l;
  24154. return l + r;
  24155. }
  24156. function isStateless($filter, filterName) {
  24157. var fn = $filter(filterName);
  24158. return !fn.$stateful;
  24159. }
  24160. function findConstantAndWatchExpressions(ast, $filter) {
  24161. var allConstants;
  24162. var argsToWatch;
  24163. switch (ast.type) {
  24164. case AST.Program:
  24165. allConstants = true;
  24166. forEach(ast.body, function(expr) {
  24167. findConstantAndWatchExpressions(expr.expression, $filter);
  24168. allConstants = allConstants && expr.expression.constant;
  24169. });
  24170. ast.constant = allConstants;
  24171. break;
  24172. case AST.Literal:
  24173. ast.constant = true;
  24174. ast.toWatch = [];
  24175. break;
  24176. case AST.UnaryExpression:
  24177. findConstantAndWatchExpressions(ast.argument, $filter);
  24178. ast.constant = ast.argument.constant;
  24179. ast.toWatch = ast.argument.toWatch;
  24180. break;
  24181. case AST.BinaryExpression:
  24182. findConstantAndWatchExpressions(ast.left, $filter);
  24183. findConstantAndWatchExpressions(ast.right, $filter);
  24184. ast.constant = ast.left.constant && ast.right.constant;
  24185. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  24186. break;
  24187. case AST.LogicalExpression:
  24188. findConstantAndWatchExpressions(ast.left, $filter);
  24189. findConstantAndWatchExpressions(ast.right, $filter);
  24190. ast.constant = ast.left.constant && ast.right.constant;
  24191. ast.toWatch = ast.constant ? [] : [ast];
  24192. break;
  24193. case AST.ConditionalExpression:
  24194. findConstantAndWatchExpressions(ast.test, $filter);
  24195. findConstantAndWatchExpressions(ast.alternate, $filter);
  24196. findConstantAndWatchExpressions(ast.consequent, $filter);
  24197. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  24198. ast.toWatch = ast.constant ? [] : [ast];
  24199. break;
  24200. case AST.Identifier:
  24201. ast.constant = false;
  24202. ast.toWatch = [ast];
  24203. break;
  24204. case AST.MemberExpression:
  24205. findConstantAndWatchExpressions(ast.object, $filter);
  24206. if (ast.computed) {
  24207. findConstantAndWatchExpressions(ast.property, $filter);
  24208. }
  24209. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  24210. ast.toWatch = [ast];
  24211. break;
  24212. case AST.CallExpression:
  24213. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  24214. argsToWatch = [];
  24215. forEach(ast.arguments, function(expr) {
  24216. findConstantAndWatchExpressions(expr, $filter);
  24217. allConstants = allConstants && expr.constant;
  24218. if (!expr.constant) {
  24219. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  24220. }
  24221. });
  24222. ast.constant = allConstants;
  24223. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  24224. break;
  24225. case AST.AssignmentExpression:
  24226. findConstantAndWatchExpressions(ast.left, $filter);
  24227. findConstantAndWatchExpressions(ast.right, $filter);
  24228. ast.constant = ast.left.constant && ast.right.constant;
  24229. ast.toWatch = [ast];
  24230. break;
  24231. case AST.ArrayExpression:
  24232. allConstants = true;
  24233. argsToWatch = [];
  24234. forEach(ast.elements, function(expr) {
  24235. findConstantAndWatchExpressions(expr, $filter);
  24236. allConstants = allConstants && expr.constant;
  24237. if (!expr.constant) {
  24238. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  24239. }
  24240. });
  24241. ast.constant = allConstants;
  24242. ast.toWatch = argsToWatch;
  24243. break;
  24244. case AST.ObjectExpression:
  24245. allConstants = true;
  24246. argsToWatch = [];
  24247. forEach(ast.properties, function(property) {
  24248. findConstantAndWatchExpressions(property.value, $filter);
  24249. allConstants = allConstants && property.value.constant;
  24250. if (!property.value.constant) {
  24251. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  24252. }
  24253. });
  24254. ast.constant = allConstants;
  24255. ast.toWatch = argsToWatch;
  24256. break;
  24257. case AST.ThisExpression:
  24258. ast.constant = false;
  24259. ast.toWatch = [];
  24260. break;
  24261. case AST.LocalsExpression:
  24262. ast.constant = false;
  24263. ast.toWatch = [];
  24264. break;
  24265. }
  24266. }
  24267. function getInputs(body) {
  24268. if (body.length != 1) return;
  24269. var lastExpression = body[0].expression;
  24270. var candidate = lastExpression.toWatch;
  24271. if (candidate.length !== 1) return candidate;
  24272. return candidate[0] !== lastExpression ? candidate : undefined;
  24273. }
  24274. function isAssignable(ast) {
  24275. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  24276. }
  24277. function assignableAST(ast) {
  24278. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  24279. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  24280. }
  24281. }
  24282. function isLiteral(ast) {
  24283. return ast.body.length === 0 ||
  24284. ast.body.length === 1 && (
  24285. ast.body[0].expression.type === AST.Literal ||
  24286. ast.body[0].expression.type === AST.ArrayExpression ||
  24287. ast.body[0].expression.type === AST.ObjectExpression);
  24288. }
  24289. function isConstant(ast) {
  24290. return ast.constant;
  24291. }
  24292. function ASTCompiler(astBuilder, $filter) {
  24293. this.astBuilder = astBuilder;
  24294. this.$filter = $filter;
  24295. }
  24296. ASTCompiler.prototype = {
  24297. compile: function(expression, expensiveChecks) {
  24298. var self = this;
  24299. var ast = this.astBuilder.ast(expression);
  24300. this.state = {
  24301. nextId: 0,
  24302. filters: {},
  24303. expensiveChecks: expensiveChecks,
  24304. fn: {vars: [], body: [], own: {}},
  24305. assign: {vars: [], body: [], own: {}},
  24306. inputs: []
  24307. };
  24308. findConstantAndWatchExpressions(ast, self.$filter);
  24309. var extra = '';
  24310. var assignable;
  24311. this.stage = 'assign';
  24312. if ((assignable = assignableAST(ast))) {
  24313. this.state.computing = 'assign';
  24314. var result = this.nextId();
  24315. this.recurse(assignable, result);
  24316. this.return_(result);
  24317. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  24318. }
  24319. var toWatch = getInputs(ast.body);
  24320. self.stage = 'inputs';
  24321. forEach(toWatch, function(watch, key) {
  24322. var fnKey = 'fn' + key;
  24323. self.state[fnKey] = {vars: [], body: [], own: {}};
  24324. self.state.computing = fnKey;
  24325. var intoId = self.nextId();
  24326. self.recurse(watch, intoId);
  24327. self.return_(intoId);
  24328. self.state.inputs.push(fnKey);
  24329. watch.watchId = key;
  24330. });
  24331. this.state.computing = 'fn';
  24332. this.stage = 'main';
  24333. this.recurse(ast);
  24334. var fnString =
  24335. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  24336. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  24337. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  24338. this.filterPrefix() +
  24339. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  24340. extra +
  24341. this.watchFns() +
  24342. 'return fn;';
  24343. /* jshint -W054 */
  24344. var fn = (new Function('$filter',
  24345. 'ensureSafeMemberName',
  24346. 'ensureSafeObject',
  24347. 'ensureSafeFunction',
  24348. 'getStringValue',
  24349. 'ensureSafeAssignContext',
  24350. 'ifDefined',
  24351. 'plus',
  24352. 'text',
  24353. fnString))(
  24354. this.$filter,
  24355. ensureSafeMemberName,
  24356. ensureSafeObject,
  24357. ensureSafeFunction,
  24358. getStringValue,
  24359. ensureSafeAssignContext,
  24360. ifDefined,
  24361. plusFn,
  24362. expression);
  24363. /* jshint +W054 */
  24364. this.state = this.stage = undefined;
  24365. fn.literal = isLiteral(ast);
  24366. fn.constant = isConstant(ast);
  24367. return fn;
  24368. },
  24369. USE: 'use',
  24370. STRICT: 'strict',
  24371. watchFns: function() {
  24372. var result = [];
  24373. var fns = this.state.inputs;
  24374. var self = this;
  24375. forEach(fns, function(name) {
  24376. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  24377. });
  24378. if (fns.length) {
  24379. result.push('fn.inputs=[' + fns.join(',') + '];');
  24380. }
  24381. return result.join('');
  24382. },
  24383. generateFunction: function(name, params) {
  24384. return 'function(' + params + '){' +
  24385. this.varsPrefix(name) +
  24386. this.body(name) +
  24387. '};';
  24388. },
  24389. filterPrefix: function() {
  24390. var parts = [];
  24391. var self = this;
  24392. forEach(this.state.filters, function(id, filter) {
  24393. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  24394. });
  24395. if (parts.length) return 'var ' + parts.join(',') + ';';
  24396. return '';
  24397. },
  24398. varsPrefix: function(section) {
  24399. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  24400. },
  24401. body: function(section) {
  24402. return this.state[section].body.join('');
  24403. },
  24404. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  24405. var left, right, self = this, args, expression;
  24406. recursionFn = recursionFn || noop;
  24407. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  24408. intoId = intoId || this.nextId();
  24409. this.if_('i',
  24410. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  24411. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  24412. );
  24413. return;
  24414. }
  24415. switch (ast.type) {
  24416. case AST.Program:
  24417. forEach(ast.body, function(expression, pos) {
  24418. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  24419. if (pos !== ast.body.length - 1) {
  24420. self.current().body.push(right, ';');
  24421. } else {
  24422. self.return_(right);
  24423. }
  24424. });
  24425. break;
  24426. case AST.Literal:
  24427. expression = this.escape(ast.value);
  24428. this.assign(intoId, expression);
  24429. recursionFn(expression);
  24430. break;
  24431. case AST.UnaryExpression:
  24432. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  24433. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  24434. this.assign(intoId, expression);
  24435. recursionFn(expression);
  24436. break;
  24437. case AST.BinaryExpression:
  24438. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  24439. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  24440. if (ast.operator === '+') {
  24441. expression = this.plus(left, right);
  24442. } else if (ast.operator === '-') {
  24443. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  24444. } else {
  24445. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  24446. }
  24447. this.assign(intoId, expression);
  24448. recursionFn(expression);
  24449. break;
  24450. case AST.LogicalExpression:
  24451. intoId = intoId || this.nextId();
  24452. self.recurse(ast.left, intoId);
  24453. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  24454. recursionFn(intoId);
  24455. break;
  24456. case AST.ConditionalExpression:
  24457. intoId = intoId || this.nextId();
  24458. self.recurse(ast.test, intoId);
  24459. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  24460. recursionFn(intoId);
  24461. break;
  24462. case AST.Identifier:
  24463. intoId = intoId || this.nextId();
  24464. if (nameId) {
  24465. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  24466. nameId.computed = false;
  24467. nameId.name = ast.name;
  24468. }
  24469. ensureSafeMemberName(ast.name);
  24470. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  24471. function() {
  24472. self.if_(self.stage === 'inputs' || 's', function() {
  24473. if (create && create !== 1) {
  24474. self.if_(
  24475. self.not(self.nonComputedMember('s', ast.name)),
  24476. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  24477. }
  24478. self.assign(intoId, self.nonComputedMember('s', ast.name));
  24479. });
  24480. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  24481. );
  24482. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  24483. self.addEnsureSafeObject(intoId);
  24484. }
  24485. recursionFn(intoId);
  24486. break;
  24487. case AST.MemberExpression:
  24488. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  24489. intoId = intoId || this.nextId();
  24490. self.recurse(ast.object, left, undefined, function() {
  24491. self.if_(self.notNull(left), function() {
  24492. if (create && create !== 1) {
  24493. self.addEnsureSafeAssignContext(left);
  24494. }
  24495. if (ast.computed) {
  24496. right = self.nextId();
  24497. self.recurse(ast.property, right);
  24498. self.getStringValue(right);
  24499. self.addEnsureSafeMemberName(right);
  24500. if (create && create !== 1) {
  24501. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  24502. }
  24503. expression = self.ensureSafeObject(self.computedMember(left, right));
  24504. self.assign(intoId, expression);
  24505. if (nameId) {
  24506. nameId.computed = true;
  24507. nameId.name = right;
  24508. }
  24509. } else {
  24510. ensureSafeMemberName(ast.property.name);
  24511. if (create && create !== 1) {
  24512. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  24513. }
  24514. expression = self.nonComputedMember(left, ast.property.name);
  24515. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  24516. expression = self.ensureSafeObject(expression);
  24517. }
  24518. self.assign(intoId, expression);
  24519. if (nameId) {
  24520. nameId.computed = false;
  24521. nameId.name = ast.property.name;
  24522. }
  24523. }
  24524. }, function() {
  24525. self.assign(intoId, 'undefined');
  24526. });
  24527. recursionFn(intoId);
  24528. }, !!create);
  24529. break;
  24530. case AST.CallExpression:
  24531. intoId = intoId || this.nextId();
  24532. if (ast.filter) {
  24533. right = self.filter(ast.callee.name);
  24534. args = [];
  24535. forEach(ast.arguments, function(expr) {
  24536. var argument = self.nextId();
  24537. self.recurse(expr, argument);
  24538. args.push(argument);
  24539. });
  24540. expression = right + '(' + args.join(',') + ')';
  24541. self.assign(intoId, expression);
  24542. recursionFn(intoId);
  24543. } else {
  24544. right = self.nextId();
  24545. left = {};
  24546. args = [];
  24547. self.recurse(ast.callee, right, left, function() {
  24548. self.if_(self.notNull(right), function() {
  24549. self.addEnsureSafeFunction(right);
  24550. forEach(ast.arguments, function(expr) {
  24551. self.recurse(expr, self.nextId(), undefined, function(argument) {
  24552. args.push(self.ensureSafeObject(argument));
  24553. });
  24554. });
  24555. if (left.name) {
  24556. if (!self.state.expensiveChecks) {
  24557. self.addEnsureSafeObject(left.context);
  24558. }
  24559. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  24560. } else {
  24561. expression = right + '(' + args.join(',') + ')';
  24562. }
  24563. expression = self.ensureSafeObject(expression);
  24564. self.assign(intoId, expression);
  24565. }, function() {
  24566. self.assign(intoId, 'undefined');
  24567. });
  24568. recursionFn(intoId);
  24569. });
  24570. }
  24571. break;
  24572. case AST.AssignmentExpression:
  24573. right = this.nextId();
  24574. left = {};
  24575. if (!isAssignable(ast.left)) {
  24576. throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
  24577. }
  24578. this.recurse(ast.left, undefined, left, function() {
  24579. self.if_(self.notNull(left.context), function() {
  24580. self.recurse(ast.right, right);
  24581. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  24582. self.addEnsureSafeAssignContext(left.context);
  24583. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  24584. self.assign(intoId, expression);
  24585. recursionFn(intoId || expression);
  24586. });
  24587. }, 1);
  24588. break;
  24589. case AST.ArrayExpression:
  24590. args = [];
  24591. forEach(ast.elements, function(expr) {
  24592. self.recurse(expr, self.nextId(), undefined, function(argument) {
  24593. args.push(argument);
  24594. });
  24595. });
  24596. expression = '[' + args.join(',') + ']';
  24597. this.assign(intoId, expression);
  24598. recursionFn(expression);
  24599. break;
  24600. case AST.ObjectExpression:
  24601. args = [];
  24602. forEach(ast.properties, function(property) {
  24603. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  24604. args.push(self.escape(
  24605. property.key.type === AST.Identifier ? property.key.name :
  24606. ('' + property.key.value)) +
  24607. ':' + expr);
  24608. });
  24609. });
  24610. expression = '{' + args.join(',') + '}';
  24611. this.assign(intoId, expression);
  24612. recursionFn(expression);
  24613. break;
  24614. case AST.ThisExpression:
  24615. this.assign(intoId, 's');
  24616. recursionFn('s');
  24617. break;
  24618. case AST.LocalsExpression:
  24619. this.assign(intoId, 'l');
  24620. recursionFn('l');
  24621. break;
  24622. case AST.NGValueParameter:
  24623. this.assign(intoId, 'v');
  24624. recursionFn('v');
  24625. break;
  24626. }
  24627. },
  24628. getHasOwnProperty: function(element, property) {
  24629. var key = element + '.' + property;
  24630. var own = this.current().own;
  24631. if (!own.hasOwnProperty(key)) {
  24632. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  24633. }
  24634. return own[key];
  24635. },
  24636. assign: function(id, value) {
  24637. if (!id) return;
  24638. this.current().body.push(id, '=', value, ';');
  24639. return id;
  24640. },
  24641. filter: function(filterName) {
  24642. if (!this.state.filters.hasOwnProperty(filterName)) {
  24643. this.state.filters[filterName] = this.nextId(true);
  24644. }
  24645. return this.state.filters[filterName];
  24646. },
  24647. ifDefined: function(id, defaultValue) {
  24648. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  24649. },
  24650. plus: function(left, right) {
  24651. return 'plus(' + left + ',' + right + ')';
  24652. },
  24653. return_: function(id) {
  24654. this.current().body.push('return ', id, ';');
  24655. },
  24656. if_: function(test, alternate, consequent) {
  24657. if (test === true) {
  24658. alternate();
  24659. } else {
  24660. var body = this.current().body;
  24661. body.push('if(', test, '){');
  24662. alternate();
  24663. body.push('}');
  24664. if (consequent) {
  24665. body.push('else{');
  24666. consequent();
  24667. body.push('}');
  24668. }
  24669. }
  24670. },
  24671. not: function(expression) {
  24672. return '!(' + expression + ')';
  24673. },
  24674. notNull: function(expression) {
  24675. return expression + '!=null';
  24676. },
  24677. nonComputedMember: function(left, right) {
  24678. return left + '.' + right;
  24679. },
  24680. computedMember: function(left, right) {
  24681. return left + '[' + right + ']';
  24682. },
  24683. member: function(left, right, computed) {
  24684. if (computed) return this.computedMember(left, right);
  24685. return this.nonComputedMember(left, right);
  24686. },
  24687. addEnsureSafeObject: function(item) {
  24688. this.current().body.push(this.ensureSafeObject(item), ';');
  24689. },
  24690. addEnsureSafeMemberName: function(item) {
  24691. this.current().body.push(this.ensureSafeMemberName(item), ';');
  24692. },
  24693. addEnsureSafeFunction: function(item) {
  24694. this.current().body.push(this.ensureSafeFunction(item), ';');
  24695. },
  24696. addEnsureSafeAssignContext: function(item) {
  24697. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  24698. },
  24699. ensureSafeObject: function(item) {
  24700. return 'ensureSafeObject(' + item + ',text)';
  24701. },
  24702. ensureSafeMemberName: function(item) {
  24703. return 'ensureSafeMemberName(' + item + ',text)';
  24704. },
  24705. ensureSafeFunction: function(item) {
  24706. return 'ensureSafeFunction(' + item + ',text)';
  24707. },
  24708. getStringValue: function(item) {
  24709. this.assign(item, 'getStringValue(' + item + ')');
  24710. },
  24711. ensureSafeAssignContext: function(item) {
  24712. return 'ensureSafeAssignContext(' + item + ',text)';
  24713. },
  24714. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  24715. var self = this;
  24716. return function() {
  24717. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  24718. };
  24719. },
  24720. lazyAssign: function(id, value) {
  24721. var self = this;
  24722. return function() {
  24723. self.assign(id, value);
  24724. };
  24725. },
  24726. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  24727. stringEscapeFn: function(c) {
  24728. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  24729. },
  24730. escape: function(value) {
  24731. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  24732. if (isNumber(value)) return value.toString();
  24733. if (value === true) return 'true';
  24734. if (value === false) return 'false';
  24735. if (value === null) return 'null';
  24736. if (typeof value === 'undefined') return 'undefined';
  24737. throw $parseMinErr('esc', 'IMPOSSIBLE');
  24738. },
  24739. nextId: function(skip, init) {
  24740. var id = 'v' + (this.state.nextId++);
  24741. if (!skip) {
  24742. this.current().vars.push(id + (init ? '=' + init : ''));
  24743. }
  24744. return id;
  24745. },
  24746. current: function() {
  24747. return this.state[this.state.computing];
  24748. }
  24749. };
  24750. function ASTInterpreter(astBuilder, $filter) {
  24751. this.astBuilder = astBuilder;
  24752. this.$filter = $filter;
  24753. }
  24754. ASTInterpreter.prototype = {
  24755. compile: function(expression, expensiveChecks) {
  24756. var self = this;
  24757. var ast = this.astBuilder.ast(expression);
  24758. this.expression = expression;
  24759. this.expensiveChecks = expensiveChecks;
  24760. findConstantAndWatchExpressions(ast, self.$filter);
  24761. var assignable;
  24762. var assign;
  24763. if ((assignable = assignableAST(ast))) {
  24764. assign = this.recurse(assignable);
  24765. }
  24766. var toWatch = getInputs(ast.body);
  24767. var inputs;
  24768. if (toWatch) {
  24769. inputs = [];
  24770. forEach(toWatch, function(watch, key) {
  24771. var input = self.recurse(watch);
  24772. watch.input = input;
  24773. inputs.push(input);
  24774. watch.watchId = key;
  24775. });
  24776. }
  24777. var expressions = [];
  24778. forEach(ast.body, function(expression) {
  24779. expressions.push(self.recurse(expression.expression));
  24780. });
  24781. var fn = ast.body.length === 0 ? noop :
  24782. ast.body.length === 1 ? expressions[0] :
  24783. function(scope, locals) {
  24784. var lastValue;
  24785. forEach(expressions, function(exp) {
  24786. lastValue = exp(scope, locals);
  24787. });
  24788. return lastValue;
  24789. };
  24790. if (assign) {
  24791. fn.assign = function(scope, value, locals) {
  24792. return assign(scope, locals, value);
  24793. };
  24794. }
  24795. if (inputs) {
  24796. fn.inputs = inputs;
  24797. }
  24798. fn.literal = isLiteral(ast);
  24799. fn.constant = isConstant(ast);
  24800. return fn;
  24801. },
  24802. recurse: function(ast, context, create) {
  24803. var left, right, self = this, args, expression;
  24804. if (ast.input) {
  24805. return this.inputs(ast.input, ast.watchId);
  24806. }
  24807. switch (ast.type) {
  24808. case AST.Literal:
  24809. return this.value(ast.value, context);
  24810. case AST.UnaryExpression:
  24811. right = this.recurse(ast.argument);
  24812. return this['unary' + ast.operator](right, context);
  24813. case AST.BinaryExpression:
  24814. left = this.recurse(ast.left);
  24815. right = this.recurse(ast.right);
  24816. return this['binary' + ast.operator](left, right, context);
  24817. case AST.LogicalExpression:
  24818. left = this.recurse(ast.left);
  24819. right = this.recurse(ast.right);
  24820. return this['binary' + ast.operator](left, right, context);
  24821. case AST.ConditionalExpression:
  24822. return this['ternary?:'](
  24823. this.recurse(ast.test),
  24824. this.recurse(ast.alternate),
  24825. this.recurse(ast.consequent),
  24826. context
  24827. );
  24828. case AST.Identifier:
  24829. ensureSafeMemberName(ast.name, self.expression);
  24830. return self.identifier(ast.name,
  24831. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  24832. context, create, self.expression);
  24833. case AST.MemberExpression:
  24834. left = this.recurse(ast.object, false, !!create);
  24835. if (!ast.computed) {
  24836. ensureSafeMemberName(ast.property.name, self.expression);
  24837. right = ast.property.name;
  24838. }
  24839. if (ast.computed) right = this.recurse(ast.property);
  24840. return ast.computed ?
  24841. this.computedMember(left, right, context, create, self.expression) :
  24842. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  24843. case AST.CallExpression:
  24844. args = [];
  24845. forEach(ast.arguments, function(expr) {
  24846. args.push(self.recurse(expr));
  24847. });
  24848. if (ast.filter) right = this.$filter(ast.callee.name);
  24849. if (!ast.filter) right = this.recurse(ast.callee, true);
  24850. return ast.filter ?
  24851. function(scope, locals, assign, inputs) {
  24852. var values = [];
  24853. for (var i = 0; i < args.length; ++i) {
  24854. values.push(args[i](scope, locals, assign, inputs));
  24855. }
  24856. var value = right.apply(undefined, values, inputs);
  24857. return context ? {context: undefined, name: undefined, value: value} : value;
  24858. } :
  24859. function(scope, locals, assign, inputs) {
  24860. var rhs = right(scope, locals, assign, inputs);
  24861. var value;
  24862. if (rhs.value != null) {
  24863. ensureSafeObject(rhs.context, self.expression);
  24864. ensureSafeFunction(rhs.value, self.expression);
  24865. var values = [];
  24866. for (var i = 0; i < args.length; ++i) {
  24867. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  24868. }
  24869. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  24870. }
  24871. return context ? {value: value} : value;
  24872. };
  24873. case AST.AssignmentExpression:
  24874. left = this.recurse(ast.left, true, 1);
  24875. right = this.recurse(ast.right);
  24876. return function(scope, locals, assign, inputs) {
  24877. var lhs = left(scope, locals, assign, inputs);
  24878. var rhs = right(scope, locals, assign, inputs);
  24879. ensureSafeObject(lhs.value, self.expression);
  24880. ensureSafeAssignContext(lhs.context);
  24881. lhs.context[lhs.name] = rhs;
  24882. return context ? {value: rhs} : rhs;
  24883. };
  24884. case AST.ArrayExpression:
  24885. args = [];
  24886. forEach(ast.elements, function(expr) {
  24887. args.push(self.recurse(expr));
  24888. });
  24889. return function(scope, locals, assign, inputs) {
  24890. var value = [];
  24891. for (var i = 0; i < args.length; ++i) {
  24892. value.push(args[i](scope, locals, assign, inputs));
  24893. }
  24894. return context ? {value: value} : value;
  24895. };
  24896. case AST.ObjectExpression:
  24897. args = [];
  24898. forEach(ast.properties, function(property) {
  24899. args.push({key: property.key.type === AST.Identifier ?
  24900. property.key.name :
  24901. ('' + property.key.value),
  24902. value: self.recurse(property.value)
  24903. });
  24904. });
  24905. return function(scope, locals, assign, inputs) {
  24906. var value = {};
  24907. for (var i = 0; i < args.length; ++i) {
  24908. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  24909. }
  24910. return context ? {value: value} : value;
  24911. };
  24912. case AST.ThisExpression:
  24913. return function(scope) {
  24914. return context ? {value: scope} : scope;
  24915. };
  24916. case AST.LocalsExpression:
  24917. return function(scope, locals) {
  24918. return context ? {value: locals} : locals;
  24919. };
  24920. case AST.NGValueParameter:
  24921. return function(scope, locals, assign) {
  24922. return context ? {value: assign} : assign;
  24923. };
  24924. }
  24925. },
  24926. 'unary+': function(argument, context) {
  24927. return function(scope, locals, assign, inputs) {
  24928. var arg = argument(scope, locals, assign, inputs);
  24929. if (isDefined(arg)) {
  24930. arg = +arg;
  24931. } else {
  24932. arg = 0;
  24933. }
  24934. return context ? {value: arg} : arg;
  24935. };
  24936. },
  24937. 'unary-': function(argument, context) {
  24938. return function(scope, locals, assign, inputs) {
  24939. var arg = argument(scope, locals, assign, inputs);
  24940. if (isDefined(arg)) {
  24941. arg = -arg;
  24942. } else {
  24943. arg = 0;
  24944. }
  24945. return context ? {value: arg} : arg;
  24946. };
  24947. },
  24948. 'unary!': function(argument, context) {
  24949. return function(scope, locals, assign, inputs) {
  24950. var arg = !argument(scope, locals, assign, inputs);
  24951. return context ? {value: arg} : arg;
  24952. };
  24953. },
  24954. 'binary+': function(left, right, context) {
  24955. return function(scope, locals, assign, inputs) {
  24956. var lhs = left(scope, locals, assign, inputs);
  24957. var rhs = right(scope, locals, assign, inputs);
  24958. var arg = plusFn(lhs, rhs);
  24959. return context ? {value: arg} : arg;
  24960. };
  24961. },
  24962. 'binary-': function(left, right, context) {
  24963. return function(scope, locals, assign, inputs) {
  24964. var lhs = left(scope, locals, assign, inputs);
  24965. var rhs = right(scope, locals, assign, inputs);
  24966. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  24967. return context ? {value: arg} : arg;
  24968. };
  24969. },
  24970. 'binary*': function(left, right, context) {
  24971. return function(scope, locals, assign, inputs) {
  24972. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  24973. return context ? {value: arg} : arg;
  24974. };
  24975. },
  24976. 'binary/': function(left, right, context) {
  24977. return function(scope, locals, assign, inputs) {
  24978. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  24979. return context ? {value: arg} : arg;
  24980. };
  24981. },
  24982. 'binary%': function(left, right, context) {
  24983. return function(scope, locals, assign, inputs) {
  24984. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  24985. return context ? {value: arg} : arg;
  24986. };
  24987. },
  24988. 'binary===': function(left, right, context) {
  24989. return function(scope, locals, assign, inputs) {
  24990. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  24991. return context ? {value: arg} : arg;
  24992. };
  24993. },
  24994. 'binary!==': function(left, right, context) {
  24995. return function(scope, locals, assign, inputs) {
  24996. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  24997. return context ? {value: arg} : arg;
  24998. };
  24999. },
  25000. 'binary==': function(left, right, context) {
  25001. return function(scope, locals, assign, inputs) {
  25002. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  25003. return context ? {value: arg} : arg;
  25004. };
  25005. },
  25006. 'binary!=': function(left, right, context) {
  25007. return function(scope, locals, assign, inputs) {
  25008. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  25009. return context ? {value: arg} : arg;
  25010. };
  25011. },
  25012. 'binary<': function(left, right, context) {
  25013. return function(scope, locals, assign, inputs) {
  25014. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  25015. return context ? {value: arg} : arg;
  25016. };
  25017. },
  25018. 'binary>': function(left, right, context) {
  25019. return function(scope, locals, assign, inputs) {
  25020. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  25021. return context ? {value: arg} : arg;
  25022. };
  25023. },
  25024. 'binary<=': function(left, right, context) {
  25025. return function(scope, locals, assign, inputs) {
  25026. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  25027. return context ? {value: arg} : arg;
  25028. };
  25029. },
  25030. 'binary>=': function(left, right, context) {
  25031. return function(scope, locals, assign, inputs) {
  25032. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  25033. return context ? {value: arg} : arg;
  25034. };
  25035. },
  25036. 'binary&&': function(left, right, context) {
  25037. return function(scope, locals, assign, inputs) {
  25038. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  25039. return context ? {value: arg} : arg;
  25040. };
  25041. },
  25042. 'binary||': function(left, right, context) {
  25043. return function(scope, locals, assign, inputs) {
  25044. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  25045. return context ? {value: arg} : arg;
  25046. };
  25047. },
  25048. 'ternary?:': function(test, alternate, consequent, context) {
  25049. return function(scope, locals, assign, inputs) {
  25050. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  25051. return context ? {value: arg} : arg;
  25052. };
  25053. },
  25054. value: function(value, context) {
  25055. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  25056. },
  25057. identifier: function(name, expensiveChecks, context, create, expression) {
  25058. return function(scope, locals, assign, inputs) {
  25059. var base = locals && (name in locals) ? locals : scope;
  25060. if (create && create !== 1 && base && !(base[name])) {
  25061. base[name] = {};
  25062. }
  25063. var value = base ? base[name] : undefined;
  25064. if (expensiveChecks) {
  25065. ensureSafeObject(value, expression);
  25066. }
  25067. if (context) {
  25068. return {context: base, name: name, value: value};
  25069. } else {
  25070. return value;
  25071. }
  25072. };
  25073. },
  25074. computedMember: function(left, right, context, create, expression) {
  25075. return function(scope, locals, assign, inputs) {
  25076. var lhs = left(scope, locals, assign, inputs);
  25077. var rhs;
  25078. var value;
  25079. if (lhs != null) {
  25080. rhs = right(scope, locals, assign, inputs);
  25081. rhs = getStringValue(rhs);
  25082. ensureSafeMemberName(rhs, expression);
  25083. if (create && create !== 1) {
  25084. ensureSafeAssignContext(lhs);
  25085. if (lhs && !(lhs[rhs])) {
  25086. lhs[rhs] = {};
  25087. }
  25088. }
  25089. value = lhs[rhs];
  25090. ensureSafeObject(value, expression);
  25091. }
  25092. if (context) {
  25093. return {context: lhs, name: rhs, value: value};
  25094. } else {
  25095. return value;
  25096. }
  25097. };
  25098. },
  25099. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  25100. return function(scope, locals, assign, inputs) {
  25101. var lhs = left(scope, locals, assign, inputs);
  25102. if (create && create !== 1) {
  25103. ensureSafeAssignContext(lhs);
  25104. if (lhs && !(lhs[right])) {
  25105. lhs[right] = {};
  25106. }
  25107. }
  25108. var value = lhs != null ? lhs[right] : undefined;
  25109. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  25110. ensureSafeObject(value, expression);
  25111. }
  25112. if (context) {
  25113. return {context: lhs, name: right, value: value};
  25114. } else {
  25115. return value;
  25116. }
  25117. };
  25118. },
  25119. inputs: function(input, watchId) {
  25120. return function(scope, value, locals, inputs) {
  25121. if (inputs) return inputs[watchId];
  25122. return input(scope, value, locals);
  25123. };
  25124. }
  25125. };
  25126. /**
  25127. * @constructor
  25128. */
  25129. var Parser = function(lexer, $filter, options) {
  25130. this.lexer = lexer;
  25131. this.$filter = $filter;
  25132. this.options = options;
  25133. this.ast = new AST(lexer, options);
  25134. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  25135. new ASTCompiler(this.ast, $filter);
  25136. };
  25137. Parser.prototype = {
  25138. constructor: Parser,
  25139. parse: function(text) {
  25140. return this.astCompiler.compile(text, this.options.expensiveChecks);
  25141. }
  25142. };
  25143. function isPossiblyDangerousMemberName(name) {
  25144. return name == 'constructor';
  25145. }
  25146. var objectValueOf = Object.prototype.valueOf;
  25147. function getValueOf(value) {
  25148. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  25149. }
  25150. ///////////////////////////////////
  25151. /**
  25152. * @ngdoc service
  25153. * @name $parse
  25154. * @kind function
  25155. *
  25156. * @description
  25157. *
  25158. * Converts Angular {@link guide/expression expression} into a function.
  25159. *
  25160. * ```js
  25161. * var getter = $parse('user.name');
  25162. * var setter = getter.assign;
  25163. * var context = {user:{name:'angular'}};
  25164. * var locals = {user:{name:'local'}};
  25165. *
  25166. * expect(getter(context)).toEqual('angular');
  25167. * setter(context, 'newValue');
  25168. * expect(context.user.name).toEqual('newValue');
  25169. * expect(getter(context, locals)).toEqual('local');
  25170. * ```
  25171. *
  25172. *
  25173. * @param {string} expression String expression to compile.
  25174. * @returns {function(context, locals)} a function which represents the compiled expression:
  25175. *
  25176. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  25177. * are evaluated against (typically a scope object).
  25178. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  25179. * `context`.
  25180. *
  25181. * The returned function also has the following properties:
  25182. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  25183. * literal.
  25184. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  25185. * constant literals.
  25186. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  25187. * set to a function to change its value on the given context.
  25188. *
  25189. */
  25190. /**
  25191. * @ngdoc provider
  25192. * @name $parseProvider
  25193. *
  25194. * @description
  25195. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  25196. * service.
  25197. */
  25198. function $ParseProvider() {
  25199. var cacheDefault = createMap();
  25200. var cacheExpensive = createMap();
  25201. var literals = {
  25202. 'true': true,
  25203. 'false': false,
  25204. 'null': null,
  25205. 'undefined': undefined
  25206. };
  25207. /**
  25208. * @ngdoc method
  25209. * @name $parseProvider#addLiteral
  25210. * @description
  25211. *
  25212. * Configure $parse service to add literal values that will be present as literal at expressions.
  25213. *
  25214. * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name.
  25215. * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`.
  25216. *
  25217. **/
  25218. this.addLiteral = function(literalName, literalValue) {
  25219. literals[literalName] = literalValue;
  25220. };
  25221. this.$get = ['$filter', function($filter) {
  25222. var noUnsafeEval = csp().noUnsafeEval;
  25223. var $parseOptions = {
  25224. csp: noUnsafeEval,
  25225. expensiveChecks: false,
  25226. literals: copy(literals)
  25227. },
  25228. $parseOptionsExpensive = {
  25229. csp: noUnsafeEval,
  25230. expensiveChecks: true,
  25231. literals: copy(literals)
  25232. };
  25233. var runningChecksEnabled = false;
  25234. $parse.$$runningExpensiveChecks = function() {
  25235. return runningChecksEnabled;
  25236. };
  25237. return $parse;
  25238. function $parse(exp, interceptorFn, expensiveChecks) {
  25239. var parsedExpression, oneTime, cacheKey;
  25240. expensiveChecks = expensiveChecks || runningChecksEnabled;
  25241. switch (typeof exp) {
  25242. case 'string':
  25243. exp = exp.trim();
  25244. cacheKey = exp;
  25245. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  25246. parsedExpression = cache[cacheKey];
  25247. if (!parsedExpression) {
  25248. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  25249. oneTime = true;
  25250. exp = exp.substring(2);
  25251. }
  25252. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  25253. var lexer = new Lexer(parseOptions);
  25254. var parser = new Parser(lexer, $filter, parseOptions);
  25255. parsedExpression = parser.parse(exp);
  25256. if (parsedExpression.constant) {
  25257. parsedExpression.$$watchDelegate = constantWatchDelegate;
  25258. } else if (oneTime) {
  25259. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  25260. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  25261. } else if (parsedExpression.inputs) {
  25262. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  25263. }
  25264. if (expensiveChecks) {
  25265. parsedExpression = expensiveChecksInterceptor(parsedExpression);
  25266. }
  25267. cache[cacheKey] = parsedExpression;
  25268. }
  25269. return addInterceptor(parsedExpression, interceptorFn);
  25270. case 'function':
  25271. return addInterceptor(exp, interceptorFn);
  25272. default:
  25273. return addInterceptor(noop, interceptorFn);
  25274. }
  25275. }
  25276. function expensiveChecksInterceptor(fn) {
  25277. if (!fn) return fn;
  25278. expensiveCheckFn.$$watchDelegate = fn.$$watchDelegate;
  25279. expensiveCheckFn.assign = expensiveChecksInterceptor(fn.assign);
  25280. expensiveCheckFn.constant = fn.constant;
  25281. expensiveCheckFn.literal = fn.literal;
  25282. for (var i = 0; fn.inputs && i < fn.inputs.length; ++i) {
  25283. fn.inputs[i] = expensiveChecksInterceptor(fn.inputs[i]);
  25284. }
  25285. expensiveCheckFn.inputs = fn.inputs;
  25286. return expensiveCheckFn;
  25287. function expensiveCheckFn(scope, locals, assign, inputs) {
  25288. var expensiveCheckOldValue = runningChecksEnabled;
  25289. runningChecksEnabled = true;
  25290. try {
  25291. return fn(scope, locals, assign, inputs);
  25292. } finally {
  25293. runningChecksEnabled = expensiveCheckOldValue;
  25294. }
  25295. }
  25296. }
  25297. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  25298. if (newValue == null || oldValueOfValue == null) { // null/undefined
  25299. return newValue === oldValueOfValue;
  25300. }
  25301. if (typeof newValue === 'object') {
  25302. // attempt to convert the value to a primitive type
  25303. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  25304. // be cheaply dirty-checked
  25305. newValue = getValueOf(newValue);
  25306. if (typeof newValue === 'object') {
  25307. // objects/arrays are not supported - deep-watching them would be too expensive
  25308. return false;
  25309. }
  25310. // fall-through to the primitive equality check
  25311. }
  25312. //Primitive or NaN
  25313. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  25314. }
  25315. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  25316. var inputExpressions = parsedExpression.inputs;
  25317. var lastResult;
  25318. if (inputExpressions.length === 1) {
  25319. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  25320. inputExpressions = inputExpressions[0];
  25321. return scope.$watch(function expressionInputWatch(scope) {
  25322. var newInputValue = inputExpressions(scope);
  25323. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  25324. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  25325. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  25326. }
  25327. return lastResult;
  25328. }, listener, objectEquality, prettyPrintExpression);
  25329. }
  25330. var oldInputValueOfValues = [];
  25331. var oldInputValues = [];
  25332. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  25333. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  25334. oldInputValues[i] = null;
  25335. }
  25336. return scope.$watch(function expressionInputsWatch(scope) {
  25337. var changed = false;
  25338. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  25339. var newInputValue = inputExpressions[i](scope);
  25340. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  25341. oldInputValues[i] = newInputValue;
  25342. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  25343. }
  25344. }
  25345. if (changed) {
  25346. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  25347. }
  25348. return lastResult;
  25349. }, listener, objectEquality, prettyPrintExpression);
  25350. }
  25351. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25352. var unwatch, lastValue;
  25353. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  25354. return parsedExpression(scope);
  25355. }, function oneTimeListener(value, old, scope) {
  25356. lastValue = value;
  25357. if (isFunction(listener)) {
  25358. listener.apply(this, arguments);
  25359. }
  25360. if (isDefined(value)) {
  25361. scope.$$postDigest(function() {
  25362. if (isDefined(lastValue)) {
  25363. unwatch();
  25364. }
  25365. });
  25366. }
  25367. }, objectEquality);
  25368. }
  25369. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25370. var unwatch, lastValue;
  25371. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  25372. return parsedExpression(scope);
  25373. }, function oneTimeListener(value, old, scope) {
  25374. lastValue = value;
  25375. if (isFunction(listener)) {
  25376. listener.call(this, value, old, scope);
  25377. }
  25378. if (isAllDefined(value)) {
  25379. scope.$$postDigest(function() {
  25380. if (isAllDefined(lastValue)) unwatch();
  25381. });
  25382. }
  25383. }, objectEquality);
  25384. function isAllDefined(value) {
  25385. var allDefined = true;
  25386. forEach(value, function(val) {
  25387. if (!isDefined(val)) allDefined = false;
  25388. });
  25389. return allDefined;
  25390. }
  25391. }
  25392. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  25393. var unwatch;
  25394. return unwatch = scope.$watch(function constantWatch(scope) {
  25395. unwatch();
  25396. return parsedExpression(scope);
  25397. }, listener, objectEquality);
  25398. }
  25399. function addInterceptor(parsedExpression, interceptorFn) {
  25400. if (!interceptorFn) return parsedExpression;
  25401. var watchDelegate = parsedExpression.$$watchDelegate;
  25402. var useInputs = false;
  25403. var regularWatch =
  25404. watchDelegate !== oneTimeLiteralWatchDelegate &&
  25405. watchDelegate !== oneTimeWatchDelegate;
  25406. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  25407. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  25408. return interceptorFn(value, scope, locals);
  25409. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  25410. var value = parsedExpression(scope, locals, assign, inputs);
  25411. var result = interceptorFn(value, scope, locals);
  25412. // we only return the interceptor's result if the
  25413. // initial value is defined (for bind-once)
  25414. return isDefined(value) ? result : value;
  25415. };
  25416. // Propagate $$watchDelegates other then inputsWatchDelegate
  25417. if (parsedExpression.$$watchDelegate &&
  25418. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  25419. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  25420. } else if (!interceptorFn.$stateful) {
  25421. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  25422. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  25423. fn.$$watchDelegate = inputsWatchDelegate;
  25424. useInputs = !parsedExpression.inputs;
  25425. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  25426. }
  25427. return fn;
  25428. }
  25429. }];
  25430. }
  25431. /**
  25432. * @ngdoc service
  25433. * @name $q
  25434. * @requires $rootScope
  25435. *
  25436. * @description
  25437. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  25438. * when they are done processing.
  25439. *
  25440. * This is an implementation of promises/deferred objects inspired by
  25441. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  25442. *
  25443. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  25444. * implementations, and the other which resembles ES6 (ES2015) promises to some degree.
  25445. *
  25446. * # $q constructor
  25447. *
  25448. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  25449. * function as the first argument. This is similar to the native Promise implementation from ES6,
  25450. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  25451. *
  25452. * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are
  25453. * available yet.
  25454. *
  25455. * It can be used like so:
  25456. *
  25457. * ```js
  25458. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  25459. * // are available in the current lexical scope (they could have been injected or passed in).
  25460. *
  25461. * function asyncGreet(name) {
  25462. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  25463. * return $q(function(resolve, reject) {
  25464. * setTimeout(function() {
  25465. * if (okToGreet(name)) {
  25466. * resolve('Hello, ' + name + '!');
  25467. * } else {
  25468. * reject('Greeting ' + name + ' is not allowed.');
  25469. * }
  25470. * }, 1000);
  25471. * });
  25472. * }
  25473. *
  25474. * var promise = asyncGreet('Robin Hood');
  25475. * promise.then(function(greeting) {
  25476. * alert('Success: ' + greeting);
  25477. * }, function(reason) {
  25478. * alert('Failed: ' + reason);
  25479. * });
  25480. * ```
  25481. *
  25482. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  25483. *
  25484. * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise.
  25485. *
  25486. * However, the more traditional CommonJS-style usage is still available, and documented below.
  25487. *
  25488. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  25489. * interface for interacting with an object that represents the result of an action that is
  25490. * performed asynchronously, and may or may not be finished at any given point in time.
  25491. *
  25492. * From the perspective of dealing with error handling, deferred and promise APIs are to
  25493. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  25494. *
  25495. * ```js
  25496. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  25497. * // are available in the current lexical scope (they could have been injected or passed in).
  25498. *
  25499. * function asyncGreet(name) {
  25500. * var deferred = $q.defer();
  25501. *
  25502. * setTimeout(function() {
  25503. * deferred.notify('About to greet ' + name + '.');
  25504. *
  25505. * if (okToGreet(name)) {
  25506. * deferred.resolve('Hello, ' + name + '!');
  25507. * } else {
  25508. * deferred.reject('Greeting ' + name + ' is not allowed.');
  25509. * }
  25510. * }, 1000);
  25511. *
  25512. * return deferred.promise;
  25513. * }
  25514. *
  25515. * var promise = asyncGreet('Robin Hood');
  25516. * promise.then(function(greeting) {
  25517. * alert('Success: ' + greeting);
  25518. * }, function(reason) {
  25519. * alert('Failed: ' + reason);
  25520. * }, function(update) {
  25521. * alert('Got notification: ' + update);
  25522. * });
  25523. * ```
  25524. *
  25525. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  25526. * comes in the way of guarantees that promise and deferred APIs make, see
  25527. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  25528. *
  25529. * Additionally the promise api allows for composition that is very hard to do with the
  25530. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  25531. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  25532. * section on serial or parallel joining of promises.
  25533. *
  25534. * # The Deferred API
  25535. *
  25536. * A new instance of deferred is constructed by calling `$q.defer()`.
  25537. *
  25538. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  25539. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  25540. * of the task.
  25541. *
  25542. * **Methods**
  25543. *
  25544. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  25545. * constructed via `$q.reject`, the promise will be rejected instead.
  25546. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  25547. * resolving it with a rejection constructed via `$q.reject`.
  25548. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  25549. * multiple times before the promise is either resolved or rejected.
  25550. *
  25551. * **Properties**
  25552. *
  25553. * - promise – `{Promise}` – promise object associated with this deferred.
  25554. *
  25555. *
  25556. * # The Promise API
  25557. *
  25558. * A new promise instance is created when a deferred instance is created and can be retrieved by
  25559. * calling `deferred.promise`.
  25560. *
  25561. * The purpose of the promise object is to allow for interested parties to get access to the result
  25562. * of the deferred task when it completes.
  25563. *
  25564. * **Methods**
  25565. *
  25566. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  25567. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  25568. * as soon as the result is available. The callbacks are called with a single argument: the result
  25569. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  25570. * provide a progress indication, before the promise is resolved or rejected.
  25571. *
  25572. * This method *returns a new promise* which is resolved or rejected via the return value of the
  25573. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  25574. * with the value which is resolved in that promise using
  25575. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  25576. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  25577. * resolved or rejected from the notifyCallback method.
  25578. *
  25579. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  25580. *
  25581. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  25582. * but to do so without modifying the final value. This is useful to release resources or do some
  25583. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  25584. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  25585. * more information.
  25586. *
  25587. * # Chaining promises
  25588. *
  25589. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  25590. * possible to create a chain of promises:
  25591. *
  25592. * ```js
  25593. * promiseB = promiseA.then(function(result) {
  25594. * return result + 1;
  25595. * });
  25596. *
  25597. * // promiseB will be resolved immediately after promiseA is resolved and its value
  25598. * // will be the result of promiseA incremented by 1
  25599. * ```
  25600. *
  25601. * It is possible to create chains of any length and since a promise can be resolved with another
  25602. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  25603. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  25604. * $http's response interceptors.
  25605. *
  25606. *
  25607. * # Differences between Kris Kowal's Q and $q
  25608. *
  25609. * There are two main differences:
  25610. *
  25611. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  25612. * mechanism in angular, which means faster propagation of resolution or rejection into your
  25613. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  25614. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  25615. * all the important functionality needed for common async tasks.
  25616. *
  25617. * # Testing
  25618. *
  25619. * ```js
  25620. * it('should simulate promise', inject(function($q, $rootScope) {
  25621. * var deferred = $q.defer();
  25622. * var promise = deferred.promise;
  25623. * var resolvedValue;
  25624. *
  25625. * promise.then(function(value) { resolvedValue = value; });
  25626. * expect(resolvedValue).toBeUndefined();
  25627. *
  25628. * // Simulate resolving of promise
  25629. * deferred.resolve(123);
  25630. * // Note that the 'then' function does not get called synchronously.
  25631. * // This is because we want the promise API to always be async, whether or not
  25632. * // it got called synchronously or asynchronously.
  25633. * expect(resolvedValue).toBeUndefined();
  25634. *
  25635. * // Propagate promise resolution to 'then' functions using $apply().
  25636. * $rootScope.$apply();
  25637. * expect(resolvedValue).toEqual(123);
  25638. * }));
  25639. * ```
  25640. *
  25641. * @param {function(function, function)} resolver Function which is responsible for resolving or
  25642. * rejecting the newly created promise. The first parameter is a function which resolves the
  25643. * promise, the second parameter is a function which rejects the promise.
  25644. *
  25645. * @returns {Promise} The newly created promise.
  25646. */
  25647. function $QProvider() {
  25648. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  25649. return qFactory(function(callback) {
  25650. $rootScope.$evalAsync(callback);
  25651. }, $exceptionHandler);
  25652. }];
  25653. }
  25654. function $$QProvider() {
  25655. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  25656. return qFactory(function(callback) {
  25657. $browser.defer(callback);
  25658. }, $exceptionHandler);
  25659. }];
  25660. }
  25661. /**
  25662. * Constructs a promise manager.
  25663. *
  25664. * @param {function(function)} nextTick Function for executing functions in the next turn.
  25665. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  25666. * debugging purposes.
  25667. * @returns {object} Promise manager.
  25668. */
  25669. function qFactory(nextTick, exceptionHandler) {
  25670. var $qMinErr = minErr('$q', TypeError);
  25671. /**
  25672. * @ngdoc method
  25673. * @name ng.$q#defer
  25674. * @kind function
  25675. *
  25676. * @description
  25677. * Creates a `Deferred` object which represents a task which will finish in the future.
  25678. *
  25679. * @returns {Deferred} Returns a new instance of deferred.
  25680. */
  25681. var defer = function() {
  25682. var d = new Deferred();
  25683. //Necessary to support unbound execution :/
  25684. d.resolve = simpleBind(d, d.resolve);
  25685. d.reject = simpleBind(d, d.reject);
  25686. d.notify = simpleBind(d, d.notify);
  25687. return d;
  25688. };
  25689. function Promise() {
  25690. this.$$state = { status: 0 };
  25691. }
  25692. extend(Promise.prototype, {
  25693. then: function(onFulfilled, onRejected, progressBack) {
  25694. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  25695. return this;
  25696. }
  25697. var result = new Deferred();
  25698. this.$$state.pending = this.$$state.pending || [];
  25699. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  25700. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  25701. return result.promise;
  25702. },
  25703. "catch": function(callback) {
  25704. return this.then(null, callback);
  25705. },
  25706. "finally": function(callback, progressBack) {
  25707. return this.then(function(value) {
  25708. return handleCallback(value, true, callback);
  25709. }, function(error) {
  25710. return handleCallback(error, false, callback);
  25711. }, progressBack);
  25712. }
  25713. });
  25714. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  25715. function simpleBind(context, fn) {
  25716. return function(value) {
  25717. fn.call(context, value);
  25718. };
  25719. }
  25720. function processQueue(state) {
  25721. var fn, deferred, pending;
  25722. pending = state.pending;
  25723. state.processScheduled = false;
  25724. state.pending = undefined;
  25725. for (var i = 0, ii = pending.length; i < ii; ++i) {
  25726. deferred = pending[i][0];
  25727. fn = pending[i][state.status];
  25728. try {
  25729. if (isFunction(fn)) {
  25730. deferred.resolve(fn(state.value));
  25731. } else if (state.status === 1) {
  25732. deferred.resolve(state.value);
  25733. } else {
  25734. deferred.reject(state.value);
  25735. }
  25736. } catch (e) {
  25737. deferred.reject(e);
  25738. exceptionHandler(e);
  25739. }
  25740. }
  25741. }
  25742. function scheduleProcessQueue(state) {
  25743. if (state.processScheduled || !state.pending) return;
  25744. state.processScheduled = true;
  25745. nextTick(function() { processQueue(state); });
  25746. }
  25747. function Deferred() {
  25748. this.promise = new Promise();
  25749. }
  25750. extend(Deferred.prototype, {
  25751. resolve: function(val) {
  25752. if (this.promise.$$state.status) return;
  25753. if (val === this.promise) {
  25754. this.$$reject($qMinErr(
  25755. 'qcycle',
  25756. "Expected promise to be resolved with value other than itself '{0}'",
  25757. val));
  25758. } else {
  25759. this.$$resolve(val);
  25760. }
  25761. },
  25762. $$resolve: function(val) {
  25763. var then;
  25764. var that = this;
  25765. var done = false;
  25766. try {
  25767. if ((isObject(val) || isFunction(val))) then = val && val.then;
  25768. if (isFunction(then)) {
  25769. this.promise.$$state.status = -1;
  25770. then.call(val, resolvePromise, rejectPromise, simpleBind(this, this.notify));
  25771. } else {
  25772. this.promise.$$state.value = val;
  25773. this.promise.$$state.status = 1;
  25774. scheduleProcessQueue(this.promise.$$state);
  25775. }
  25776. } catch (e) {
  25777. rejectPromise(e);
  25778. exceptionHandler(e);
  25779. }
  25780. function resolvePromise(val) {
  25781. if (done) return;
  25782. done = true;
  25783. that.$$resolve(val);
  25784. }
  25785. function rejectPromise(val) {
  25786. if (done) return;
  25787. done = true;
  25788. that.$$reject(val);
  25789. }
  25790. },
  25791. reject: function(reason) {
  25792. if (this.promise.$$state.status) return;
  25793. this.$$reject(reason);
  25794. },
  25795. $$reject: function(reason) {
  25796. this.promise.$$state.value = reason;
  25797. this.promise.$$state.status = 2;
  25798. scheduleProcessQueue(this.promise.$$state);
  25799. },
  25800. notify: function(progress) {
  25801. var callbacks = this.promise.$$state.pending;
  25802. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  25803. nextTick(function() {
  25804. var callback, result;
  25805. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  25806. result = callbacks[i][0];
  25807. callback = callbacks[i][3];
  25808. try {
  25809. result.notify(isFunction(callback) ? callback(progress) : progress);
  25810. } catch (e) {
  25811. exceptionHandler(e);
  25812. }
  25813. }
  25814. });
  25815. }
  25816. }
  25817. });
  25818. /**
  25819. * @ngdoc method
  25820. * @name $q#reject
  25821. * @kind function
  25822. *
  25823. * @description
  25824. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  25825. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  25826. * a promise chain, you don't need to worry about it.
  25827. *
  25828. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  25829. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  25830. * a promise error callback and you want to forward the error to the promise derived from the
  25831. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  25832. * `reject`.
  25833. *
  25834. * ```js
  25835. * promiseB = promiseA.then(function(result) {
  25836. * // success: do something and resolve promiseB
  25837. * // with the old or a new result
  25838. * return result;
  25839. * }, function(reason) {
  25840. * // error: handle the error if possible and
  25841. * // resolve promiseB with newPromiseOrValue,
  25842. * // otherwise forward the rejection to promiseB
  25843. * if (canHandle(reason)) {
  25844. * // handle the error and recover
  25845. * return newPromiseOrValue;
  25846. * }
  25847. * return $q.reject(reason);
  25848. * });
  25849. * ```
  25850. *
  25851. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  25852. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  25853. */
  25854. var reject = function(reason) {
  25855. var result = new Deferred();
  25856. result.reject(reason);
  25857. return result.promise;
  25858. };
  25859. var makePromise = function makePromise(value, resolved) {
  25860. var result = new Deferred();
  25861. if (resolved) {
  25862. result.resolve(value);
  25863. } else {
  25864. result.reject(value);
  25865. }
  25866. return result.promise;
  25867. };
  25868. var handleCallback = function handleCallback(value, isResolved, callback) {
  25869. var callbackOutput = null;
  25870. try {
  25871. if (isFunction(callback)) callbackOutput = callback();
  25872. } catch (e) {
  25873. return makePromise(e, false);
  25874. }
  25875. if (isPromiseLike(callbackOutput)) {
  25876. return callbackOutput.then(function() {
  25877. return makePromise(value, isResolved);
  25878. }, function(error) {
  25879. return makePromise(error, false);
  25880. });
  25881. } else {
  25882. return makePromise(value, isResolved);
  25883. }
  25884. };
  25885. /**
  25886. * @ngdoc method
  25887. * @name $q#when
  25888. * @kind function
  25889. *
  25890. * @description
  25891. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  25892. * This is useful when you are dealing with an object that might or might not be a promise, or if
  25893. * the promise comes from a source that can't be trusted.
  25894. *
  25895. * @param {*} value Value or a promise
  25896. * @param {Function=} successCallback
  25897. * @param {Function=} errorCallback
  25898. * @param {Function=} progressCallback
  25899. * @returns {Promise} Returns a promise of the passed value or promise
  25900. */
  25901. var when = function(value, callback, errback, progressBack) {
  25902. var result = new Deferred();
  25903. result.resolve(value);
  25904. return result.promise.then(callback, errback, progressBack);
  25905. };
  25906. /**
  25907. * @ngdoc method
  25908. * @name $q#resolve
  25909. * @kind function
  25910. *
  25911. * @description
  25912. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  25913. *
  25914. * @param {*} value Value or a promise
  25915. * @param {Function=} successCallback
  25916. * @param {Function=} errorCallback
  25917. * @param {Function=} progressCallback
  25918. * @returns {Promise} Returns a promise of the passed value or promise
  25919. */
  25920. var resolve = when;
  25921. /**
  25922. * @ngdoc method
  25923. * @name $q#all
  25924. * @kind function
  25925. *
  25926. * @description
  25927. * Combines multiple promises into a single promise that is resolved when all of the input
  25928. * promises are resolved.
  25929. *
  25930. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  25931. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  25932. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  25933. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  25934. * with the same rejection value.
  25935. */
  25936. function all(promises) {
  25937. var deferred = new Deferred(),
  25938. counter = 0,
  25939. results = isArray(promises) ? [] : {};
  25940. forEach(promises, function(promise, key) {
  25941. counter++;
  25942. when(promise).then(function(value) {
  25943. if (results.hasOwnProperty(key)) return;
  25944. results[key] = value;
  25945. if (!(--counter)) deferred.resolve(results);
  25946. }, function(reason) {
  25947. if (results.hasOwnProperty(key)) return;
  25948. deferred.reject(reason);
  25949. });
  25950. });
  25951. if (counter === 0) {
  25952. deferred.resolve(results);
  25953. }
  25954. return deferred.promise;
  25955. }
  25956. var $Q = function Q(resolver) {
  25957. if (!isFunction(resolver)) {
  25958. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  25959. }
  25960. var deferred = new Deferred();
  25961. function resolveFn(value) {
  25962. deferred.resolve(value);
  25963. }
  25964. function rejectFn(reason) {
  25965. deferred.reject(reason);
  25966. }
  25967. resolver(resolveFn, rejectFn);
  25968. return deferred.promise;
  25969. };
  25970. // Let's make the instanceof operator work for promises, so that
  25971. // `new $q(fn) instanceof $q` would evaluate to true.
  25972. $Q.prototype = Promise.prototype;
  25973. $Q.defer = defer;
  25974. $Q.reject = reject;
  25975. $Q.when = when;
  25976. $Q.resolve = resolve;
  25977. $Q.all = all;
  25978. return $Q;
  25979. }
  25980. function $$RAFProvider() { //rAF
  25981. this.$get = ['$window', '$timeout', function($window, $timeout) {
  25982. var requestAnimationFrame = $window.requestAnimationFrame ||
  25983. $window.webkitRequestAnimationFrame;
  25984. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  25985. $window.webkitCancelAnimationFrame ||
  25986. $window.webkitCancelRequestAnimationFrame;
  25987. var rafSupported = !!requestAnimationFrame;
  25988. var raf = rafSupported
  25989. ? function(fn) {
  25990. var id = requestAnimationFrame(fn);
  25991. return function() {
  25992. cancelAnimationFrame(id);
  25993. };
  25994. }
  25995. : function(fn) {
  25996. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  25997. return function() {
  25998. $timeout.cancel(timer);
  25999. };
  26000. };
  26001. raf.supported = rafSupported;
  26002. return raf;
  26003. }];
  26004. }
  26005. /**
  26006. * DESIGN NOTES
  26007. *
  26008. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  26009. *
  26010. * The typical use of scope is to watch the expressions, which most of the time return the same
  26011. * value as last time so we optimize the operation.
  26012. *
  26013. * Closures construction is expensive in terms of speed as well as memory:
  26014. * - No closures, instead use prototypical inheritance for API
  26015. * - Internal state needs to be stored on scope directly, which means that private state is
  26016. * exposed as $$____ properties
  26017. *
  26018. * Loop operations are optimized by using while(count--) { ... }
  26019. * - This means that in order to keep the same order of execution as addition we have to add
  26020. * items to the array at the beginning (unshift) instead of at the end (push)
  26021. *
  26022. * Child scopes are created and removed often
  26023. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  26024. *
  26025. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  26026. * in the same way as watch. Watch requires return of the initialization function which is expensive
  26027. * to construct.
  26028. */
  26029. /**
  26030. * @ngdoc provider
  26031. * @name $rootScopeProvider
  26032. * @description
  26033. *
  26034. * Provider for the $rootScope service.
  26035. */
  26036. /**
  26037. * @ngdoc method
  26038. * @name $rootScopeProvider#digestTtl
  26039. * @description
  26040. *
  26041. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  26042. * assuming that the model is unstable.
  26043. *
  26044. * The current default is 10 iterations.
  26045. *
  26046. * In complex applications it's possible that the dependencies between `$watch`s will result in
  26047. * several digest iterations. However if an application needs more than the default 10 digest
  26048. * iterations for its model to stabilize then you should investigate what is causing the model to
  26049. * continuously change during the digest.
  26050. *
  26051. * Increasing the TTL could have performance implications, so you should not change it without
  26052. * proper justification.
  26053. *
  26054. * @param {number} limit The number of digest iterations.
  26055. */
  26056. /**
  26057. * @ngdoc service
  26058. * @name $rootScope
  26059. * @description
  26060. *
  26061. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  26062. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  26063. * between the model and the view, via a mechanism for watching the model for changes.
  26064. * They also provide event emission/broadcast and subscription facility. See the
  26065. * {@link guide/scope developer guide on scopes}.
  26066. */
  26067. function $RootScopeProvider() {
  26068. var TTL = 10;
  26069. var $rootScopeMinErr = minErr('$rootScope');
  26070. var lastDirtyWatch = null;
  26071. var applyAsyncId = null;
  26072. this.digestTtl = function(value) {
  26073. if (arguments.length) {
  26074. TTL = value;
  26075. }
  26076. return TTL;
  26077. };
  26078. function createChildScopeClass(parent) {
  26079. function ChildScope() {
  26080. this.$$watchers = this.$$nextSibling =
  26081. this.$$childHead = this.$$childTail = null;
  26082. this.$$listeners = {};
  26083. this.$$listenerCount = {};
  26084. this.$$watchersCount = 0;
  26085. this.$id = nextUid();
  26086. this.$$ChildScope = null;
  26087. }
  26088. ChildScope.prototype = parent;
  26089. return ChildScope;
  26090. }
  26091. this.$get = ['$exceptionHandler', '$parse', '$browser',
  26092. function($exceptionHandler, $parse, $browser) {
  26093. function destroyChildScope($event) {
  26094. $event.currentScope.$$destroyed = true;
  26095. }
  26096. function cleanUpScope($scope) {
  26097. if (msie === 9) {
  26098. // There is a memory leak in IE9 if all child scopes are not disconnected
  26099. // completely when a scope is destroyed. So this code will recurse up through
  26100. // all this scopes children
  26101. //
  26102. // See issue https://github.com/angular/angular.js/issues/10706
  26103. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  26104. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  26105. }
  26106. // The code below works around IE9 and V8's memory leaks
  26107. //
  26108. // See:
  26109. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  26110. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  26111. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  26112. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  26113. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  26114. }
  26115. /**
  26116. * @ngdoc type
  26117. * @name $rootScope.Scope
  26118. *
  26119. * @description
  26120. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  26121. * {@link auto.$injector $injector}. Child scopes are created using the
  26122. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  26123. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  26124. * an in-depth introduction and usage examples.
  26125. *
  26126. *
  26127. * # Inheritance
  26128. * A scope can inherit from a parent scope, as in this example:
  26129. * ```js
  26130. var parent = $rootScope;
  26131. var child = parent.$new();
  26132. parent.salutation = "Hello";
  26133. expect(child.salutation).toEqual('Hello');
  26134. child.salutation = "Welcome";
  26135. expect(child.salutation).toEqual('Welcome');
  26136. expect(parent.salutation).toEqual('Hello');
  26137. * ```
  26138. *
  26139. * When interacting with `Scope` in tests, additional helper methods are available on the
  26140. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  26141. * details.
  26142. *
  26143. *
  26144. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  26145. * provided for the current scope. Defaults to {@link ng}.
  26146. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  26147. * append/override services provided by `providers`. This is handy
  26148. * when unit-testing and having the need to override a default
  26149. * service.
  26150. * @returns {Object} Newly created scope.
  26151. *
  26152. */
  26153. function Scope() {
  26154. this.$id = nextUid();
  26155. this.$$phase = this.$parent = this.$$watchers =
  26156. this.$$nextSibling = this.$$prevSibling =
  26157. this.$$childHead = this.$$childTail = null;
  26158. this.$root = this;
  26159. this.$$destroyed = false;
  26160. this.$$listeners = {};
  26161. this.$$listenerCount = {};
  26162. this.$$watchersCount = 0;
  26163. this.$$isolateBindings = null;
  26164. }
  26165. /**
  26166. * @ngdoc property
  26167. * @name $rootScope.Scope#$id
  26168. *
  26169. * @description
  26170. * Unique scope ID (monotonically increasing) useful for debugging.
  26171. */
  26172. /**
  26173. * @ngdoc property
  26174. * @name $rootScope.Scope#$parent
  26175. *
  26176. * @description
  26177. * Reference to the parent scope.
  26178. */
  26179. /**
  26180. * @ngdoc property
  26181. * @name $rootScope.Scope#$root
  26182. *
  26183. * @description
  26184. * Reference to the root scope.
  26185. */
  26186. Scope.prototype = {
  26187. constructor: Scope,
  26188. /**
  26189. * @ngdoc method
  26190. * @name $rootScope.Scope#$new
  26191. * @kind function
  26192. *
  26193. * @description
  26194. * Creates a new child {@link ng.$rootScope.Scope scope}.
  26195. *
  26196. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  26197. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  26198. *
  26199. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  26200. * desired for the scope and its child scopes to be permanently detached from the parent and
  26201. * thus stop participating in model change detection and listener notification by invoking.
  26202. *
  26203. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  26204. * parent scope. The scope is isolated, as it can not see parent scope properties.
  26205. * When creating widgets, it is useful for the widget to not accidentally read parent
  26206. * state.
  26207. *
  26208. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  26209. * of the newly created scope. Defaults to `this` scope if not provided.
  26210. * This is used when creating a transclude scope to correctly place it
  26211. * in the scope hierarchy while maintaining the correct prototypical
  26212. * inheritance.
  26213. *
  26214. * @returns {Object} The newly created child scope.
  26215. *
  26216. */
  26217. $new: function(isolate, parent) {
  26218. var child;
  26219. parent = parent || this;
  26220. if (isolate) {
  26221. child = new Scope();
  26222. child.$root = this.$root;
  26223. } else {
  26224. // Only create a child scope class if somebody asks for one,
  26225. // but cache it to allow the VM to optimize lookups.
  26226. if (!this.$$ChildScope) {
  26227. this.$$ChildScope = createChildScopeClass(this);
  26228. }
  26229. child = new this.$$ChildScope();
  26230. }
  26231. child.$parent = parent;
  26232. child.$$prevSibling = parent.$$childTail;
  26233. if (parent.$$childHead) {
  26234. parent.$$childTail.$$nextSibling = child;
  26235. parent.$$childTail = child;
  26236. } else {
  26237. parent.$$childHead = parent.$$childTail = child;
  26238. }
  26239. // When the new scope is not isolated or we inherit from `this`, and
  26240. // the parent scope is destroyed, the property `$$destroyed` is inherited
  26241. // prototypically. In all other cases, this property needs to be set
  26242. // when the parent scope is destroyed.
  26243. // The listener needs to be added after the parent is set
  26244. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  26245. return child;
  26246. },
  26247. /**
  26248. * @ngdoc method
  26249. * @name $rootScope.Scope#$watch
  26250. * @kind function
  26251. *
  26252. * @description
  26253. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  26254. *
  26255. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  26256. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  26257. * its value when executed multiple times with the same input because it may be executed multiple
  26258. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  26259. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  26260. * - The `listener` is called only when the value from the current `watchExpression` and the
  26261. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  26262. * see below). Inequality is determined according to reference inequality,
  26263. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  26264. * via the `!==` Javascript operator, unless `objectEquality == true`
  26265. * (see next point)
  26266. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  26267. * according to the {@link angular.equals} function. To save the value of the object for
  26268. * later comparison, the {@link angular.copy} function is used. This therefore means that
  26269. * watching complex objects will have adverse memory and performance implications.
  26270. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  26271. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  26272. * iteration limit is 10 to prevent an infinite loop deadlock.
  26273. *
  26274. *
  26275. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  26276. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  26277. * multiple calls to your `watchExpression` because it will execute multiple times in a
  26278. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  26279. *
  26280. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  26281. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  26282. * watcher. In rare cases, this is undesirable because the listener is called when the result
  26283. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  26284. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  26285. * listener was called due to initialization.
  26286. *
  26287. *
  26288. *
  26289. * # Example
  26290. * ```js
  26291. // let's assume that scope was dependency injected as the $rootScope
  26292. var scope = $rootScope;
  26293. scope.name = 'misko';
  26294. scope.counter = 0;
  26295. expect(scope.counter).toEqual(0);
  26296. scope.$watch('name', function(newValue, oldValue) {
  26297. scope.counter = scope.counter + 1;
  26298. });
  26299. expect(scope.counter).toEqual(0);
  26300. scope.$digest();
  26301. // the listener is always called during the first $digest loop after it was registered
  26302. expect(scope.counter).toEqual(1);
  26303. scope.$digest();
  26304. // but now it will not be called unless the value changes
  26305. expect(scope.counter).toEqual(1);
  26306. scope.name = 'adam';
  26307. scope.$digest();
  26308. expect(scope.counter).toEqual(2);
  26309. // Using a function as a watchExpression
  26310. var food;
  26311. scope.foodCounter = 0;
  26312. expect(scope.foodCounter).toEqual(0);
  26313. scope.$watch(
  26314. // This function returns the value being watched. It is called for each turn of the $digest loop
  26315. function() { return food; },
  26316. // This is the change listener, called when the value returned from the above function changes
  26317. function(newValue, oldValue) {
  26318. if ( newValue !== oldValue ) {
  26319. // Only increment the counter if the value changed
  26320. scope.foodCounter = scope.foodCounter + 1;
  26321. }
  26322. }
  26323. );
  26324. // No digest has been run so the counter will be zero
  26325. expect(scope.foodCounter).toEqual(0);
  26326. // Run the digest but since food has not changed count will still be zero
  26327. scope.$digest();
  26328. expect(scope.foodCounter).toEqual(0);
  26329. // Update food and run digest. Now the counter will increment
  26330. food = 'cheeseburger';
  26331. scope.$digest();
  26332. expect(scope.foodCounter).toEqual(1);
  26333. * ```
  26334. *
  26335. *
  26336. *
  26337. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  26338. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  26339. * a call to the `listener`.
  26340. *
  26341. * - `string`: Evaluated as {@link guide/expression expression}
  26342. * - `function(scope)`: called with current `scope` as a parameter.
  26343. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  26344. * of `watchExpression` changes.
  26345. *
  26346. * - `newVal` contains the current value of the `watchExpression`
  26347. * - `oldVal` contains the previous value of the `watchExpression`
  26348. * - `scope` refers to the current scope
  26349. * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of
  26350. * comparing for reference equality.
  26351. * @returns {function()} Returns a deregistration function for this listener.
  26352. */
  26353. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  26354. var get = $parse(watchExp);
  26355. if (get.$$watchDelegate) {
  26356. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  26357. }
  26358. var scope = this,
  26359. array = scope.$$watchers,
  26360. watcher = {
  26361. fn: listener,
  26362. last: initWatchVal,
  26363. get: get,
  26364. exp: prettyPrintExpression || watchExp,
  26365. eq: !!objectEquality
  26366. };
  26367. lastDirtyWatch = null;
  26368. if (!isFunction(listener)) {
  26369. watcher.fn = noop;
  26370. }
  26371. if (!array) {
  26372. array = scope.$$watchers = [];
  26373. }
  26374. // we use unshift since we use a while loop in $digest for speed.
  26375. // the while loop reads in reverse order.
  26376. array.unshift(watcher);
  26377. incrementWatchersCount(this, 1);
  26378. return function deregisterWatch() {
  26379. if (arrayRemove(array, watcher) >= 0) {
  26380. incrementWatchersCount(scope, -1);
  26381. }
  26382. lastDirtyWatch = null;
  26383. };
  26384. },
  26385. /**
  26386. * @ngdoc method
  26387. * @name $rootScope.Scope#$watchGroup
  26388. * @kind function
  26389. *
  26390. * @description
  26391. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  26392. * If any one expression in the collection changes the `listener` is executed.
  26393. *
  26394. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  26395. * call to $digest() to see if any items changes.
  26396. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  26397. *
  26398. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  26399. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  26400. *
  26401. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  26402. * expression in `watchExpressions` changes
  26403. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  26404. * those of `watchExpression`
  26405. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  26406. * those of `watchExpression`
  26407. * The `scope` refers to the current scope.
  26408. * @returns {function()} Returns a de-registration function for all listeners.
  26409. */
  26410. $watchGroup: function(watchExpressions, listener) {
  26411. var oldValues = new Array(watchExpressions.length);
  26412. var newValues = new Array(watchExpressions.length);
  26413. var deregisterFns = [];
  26414. var self = this;
  26415. var changeReactionScheduled = false;
  26416. var firstRun = true;
  26417. if (!watchExpressions.length) {
  26418. // No expressions means we call the listener ASAP
  26419. var shouldCall = true;
  26420. self.$evalAsync(function() {
  26421. if (shouldCall) listener(newValues, newValues, self);
  26422. });
  26423. return function deregisterWatchGroup() {
  26424. shouldCall = false;
  26425. };
  26426. }
  26427. if (watchExpressions.length === 1) {
  26428. // Special case size of one
  26429. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  26430. newValues[0] = value;
  26431. oldValues[0] = oldValue;
  26432. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  26433. });
  26434. }
  26435. forEach(watchExpressions, function(expr, i) {
  26436. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  26437. newValues[i] = value;
  26438. oldValues[i] = oldValue;
  26439. if (!changeReactionScheduled) {
  26440. changeReactionScheduled = true;
  26441. self.$evalAsync(watchGroupAction);
  26442. }
  26443. });
  26444. deregisterFns.push(unwatchFn);
  26445. });
  26446. function watchGroupAction() {
  26447. changeReactionScheduled = false;
  26448. if (firstRun) {
  26449. firstRun = false;
  26450. listener(newValues, newValues, self);
  26451. } else {
  26452. listener(newValues, oldValues, self);
  26453. }
  26454. }
  26455. return function deregisterWatchGroup() {
  26456. while (deregisterFns.length) {
  26457. deregisterFns.shift()();
  26458. }
  26459. };
  26460. },
  26461. /**
  26462. * @ngdoc method
  26463. * @name $rootScope.Scope#$watchCollection
  26464. * @kind function
  26465. *
  26466. * @description
  26467. * Shallow watches the properties of an object and fires whenever any of the properties change
  26468. * (for arrays, this implies watching the array items; for object maps, this implies watching
  26469. * the properties). If a change is detected, the `listener` callback is fired.
  26470. *
  26471. * - The `obj` collection is observed via standard $watch operation and is examined on every
  26472. * call to $digest() to see if any items have been added, removed, or moved.
  26473. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  26474. * adding, removing, and moving items belonging to an object or array.
  26475. *
  26476. *
  26477. * # Example
  26478. * ```js
  26479. $scope.names = ['igor', 'matias', 'misko', 'james'];
  26480. $scope.dataCount = 4;
  26481. $scope.$watchCollection('names', function(newNames, oldNames) {
  26482. $scope.dataCount = newNames.length;
  26483. });
  26484. expect($scope.dataCount).toEqual(4);
  26485. $scope.$digest();
  26486. //still at 4 ... no changes
  26487. expect($scope.dataCount).toEqual(4);
  26488. $scope.names.pop();
  26489. $scope.$digest();
  26490. //now there's been a change
  26491. expect($scope.dataCount).toEqual(3);
  26492. * ```
  26493. *
  26494. *
  26495. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  26496. * expression value should evaluate to an object or an array which is observed on each
  26497. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  26498. * collection will trigger a call to the `listener`.
  26499. *
  26500. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  26501. * when a change is detected.
  26502. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  26503. * - The `oldCollection` object is a copy of the former collection data.
  26504. * Due to performance considerations, the`oldCollection` value is computed only if the
  26505. * `listener` function declares two or more arguments.
  26506. * - The `scope` argument refers to the current scope.
  26507. *
  26508. * @returns {function()} Returns a de-registration function for this listener. When the
  26509. * de-registration function is executed, the internal watch operation is terminated.
  26510. */
  26511. $watchCollection: function(obj, listener) {
  26512. $watchCollectionInterceptor.$stateful = true;
  26513. var self = this;
  26514. // the current value, updated on each dirty-check run
  26515. var newValue;
  26516. // a shallow copy of the newValue from the last dirty-check run,
  26517. // updated to match newValue during dirty-check run
  26518. var oldValue;
  26519. // a shallow copy of the newValue from when the last change happened
  26520. var veryOldValue;
  26521. // only track veryOldValue if the listener is asking for it
  26522. var trackVeryOldValue = (listener.length > 1);
  26523. var changeDetected = 0;
  26524. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  26525. var internalArray = [];
  26526. var internalObject = {};
  26527. var initRun = true;
  26528. var oldLength = 0;
  26529. function $watchCollectionInterceptor(_value) {
  26530. newValue = _value;
  26531. var newLength, key, bothNaN, newItem, oldItem;
  26532. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  26533. if (isUndefined(newValue)) return;
  26534. if (!isObject(newValue)) { // if primitive
  26535. if (oldValue !== newValue) {
  26536. oldValue = newValue;
  26537. changeDetected++;
  26538. }
  26539. } else if (isArrayLike(newValue)) {
  26540. if (oldValue !== internalArray) {
  26541. // we are transitioning from something which was not an array into array.
  26542. oldValue = internalArray;
  26543. oldLength = oldValue.length = 0;
  26544. changeDetected++;
  26545. }
  26546. newLength = newValue.length;
  26547. if (oldLength !== newLength) {
  26548. // if lengths do not match we need to trigger change notification
  26549. changeDetected++;
  26550. oldValue.length = oldLength = newLength;
  26551. }
  26552. // copy the items to oldValue and look for changes.
  26553. for (var i = 0; i < newLength; i++) {
  26554. oldItem = oldValue[i];
  26555. newItem = newValue[i];
  26556. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  26557. if (!bothNaN && (oldItem !== newItem)) {
  26558. changeDetected++;
  26559. oldValue[i] = newItem;
  26560. }
  26561. }
  26562. } else {
  26563. if (oldValue !== internalObject) {
  26564. // we are transitioning from something which was not an object into object.
  26565. oldValue = internalObject = {};
  26566. oldLength = 0;
  26567. changeDetected++;
  26568. }
  26569. // copy the items to oldValue and look for changes.
  26570. newLength = 0;
  26571. for (key in newValue) {
  26572. if (hasOwnProperty.call(newValue, key)) {
  26573. newLength++;
  26574. newItem = newValue[key];
  26575. oldItem = oldValue[key];
  26576. if (key in oldValue) {
  26577. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  26578. if (!bothNaN && (oldItem !== newItem)) {
  26579. changeDetected++;
  26580. oldValue[key] = newItem;
  26581. }
  26582. } else {
  26583. oldLength++;
  26584. oldValue[key] = newItem;
  26585. changeDetected++;
  26586. }
  26587. }
  26588. }
  26589. if (oldLength > newLength) {
  26590. // we used to have more keys, need to find them and destroy them.
  26591. changeDetected++;
  26592. for (key in oldValue) {
  26593. if (!hasOwnProperty.call(newValue, key)) {
  26594. oldLength--;
  26595. delete oldValue[key];
  26596. }
  26597. }
  26598. }
  26599. }
  26600. return changeDetected;
  26601. }
  26602. function $watchCollectionAction() {
  26603. if (initRun) {
  26604. initRun = false;
  26605. listener(newValue, newValue, self);
  26606. } else {
  26607. listener(newValue, veryOldValue, self);
  26608. }
  26609. // make a copy for the next time a collection is changed
  26610. if (trackVeryOldValue) {
  26611. if (!isObject(newValue)) {
  26612. //primitive
  26613. veryOldValue = newValue;
  26614. } else if (isArrayLike(newValue)) {
  26615. veryOldValue = new Array(newValue.length);
  26616. for (var i = 0; i < newValue.length; i++) {
  26617. veryOldValue[i] = newValue[i];
  26618. }
  26619. } else { // if object
  26620. veryOldValue = {};
  26621. for (var key in newValue) {
  26622. if (hasOwnProperty.call(newValue, key)) {
  26623. veryOldValue[key] = newValue[key];
  26624. }
  26625. }
  26626. }
  26627. }
  26628. }
  26629. return this.$watch(changeDetector, $watchCollectionAction);
  26630. },
  26631. /**
  26632. * @ngdoc method
  26633. * @name $rootScope.Scope#$digest
  26634. * @kind function
  26635. *
  26636. * @description
  26637. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  26638. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  26639. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  26640. * until no more listeners are firing. This means that it is possible to get into an infinite
  26641. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  26642. * iterations exceeds 10.
  26643. *
  26644. * Usually, you don't call `$digest()` directly in
  26645. * {@link ng.directive:ngController controllers} or in
  26646. * {@link ng.$compileProvider#directive directives}.
  26647. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  26648. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  26649. *
  26650. * If you want to be notified whenever `$digest()` is called,
  26651. * you can register a `watchExpression` function with
  26652. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  26653. *
  26654. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  26655. *
  26656. * # Example
  26657. * ```js
  26658. var scope = ...;
  26659. scope.name = 'misko';
  26660. scope.counter = 0;
  26661. expect(scope.counter).toEqual(0);
  26662. scope.$watch('name', function(newValue, oldValue) {
  26663. scope.counter = scope.counter + 1;
  26664. });
  26665. expect(scope.counter).toEqual(0);
  26666. scope.$digest();
  26667. // the listener is always called during the first $digest loop after it was registered
  26668. expect(scope.counter).toEqual(1);
  26669. scope.$digest();
  26670. // but now it will not be called unless the value changes
  26671. expect(scope.counter).toEqual(1);
  26672. scope.name = 'adam';
  26673. scope.$digest();
  26674. expect(scope.counter).toEqual(2);
  26675. * ```
  26676. *
  26677. */
  26678. $digest: function() {
  26679. var watch, value, last, fn, get,
  26680. watchers,
  26681. length,
  26682. dirty, ttl = TTL,
  26683. next, current, target = this,
  26684. watchLog = [],
  26685. logIdx, asyncTask;
  26686. beginPhase('$digest');
  26687. // Check for changes to browser url that happened in sync before the call to $digest
  26688. $browser.$$checkUrlChange();
  26689. if (this === $rootScope && applyAsyncId !== null) {
  26690. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  26691. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  26692. $browser.defer.cancel(applyAsyncId);
  26693. flushApplyAsync();
  26694. }
  26695. lastDirtyWatch = null;
  26696. do { // "while dirty" loop
  26697. dirty = false;
  26698. current = target;
  26699. while (asyncQueue.length) {
  26700. try {
  26701. asyncTask = asyncQueue.shift();
  26702. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  26703. } catch (e) {
  26704. $exceptionHandler(e);
  26705. }
  26706. lastDirtyWatch = null;
  26707. }
  26708. traverseScopesLoop:
  26709. do { // "traverse the scopes" loop
  26710. if ((watchers = current.$$watchers)) {
  26711. // process our watches
  26712. length = watchers.length;
  26713. while (length--) {
  26714. try {
  26715. watch = watchers[length];
  26716. // Most common watches are on primitives, in which case we can short
  26717. // circuit it with === operator, only when === fails do we use .equals
  26718. if (watch) {
  26719. get = watch.get;
  26720. if ((value = get(current)) !== (last = watch.last) &&
  26721. !(watch.eq
  26722. ? equals(value, last)
  26723. : (typeof value === 'number' && typeof last === 'number'
  26724. && isNaN(value) && isNaN(last)))) {
  26725. dirty = true;
  26726. lastDirtyWatch = watch;
  26727. watch.last = watch.eq ? copy(value, null) : value;
  26728. fn = watch.fn;
  26729. fn(value, ((last === initWatchVal) ? value : last), current);
  26730. if (ttl < 5) {
  26731. logIdx = 4 - ttl;
  26732. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  26733. watchLog[logIdx].push({
  26734. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  26735. newVal: value,
  26736. oldVal: last
  26737. });
  26738. }
  26739. } else if (watch === lastDirtyWatch) {
  26740. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  26741. // have already been tested.
  26742. dirty = false;
  26743. break traverseScopesLoop;
  26744. }
  26745. }
  26746. } catch (e) {
  26747. $exceptionHandler(e);
  26748. }
  26749. }
  26750. }
  26751. // Insanity Warning: scope depth-first traversal
  26752. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  26753. // this piece should be kept in sync with the traversal in $broadcast
  26754. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  26755. (current !== target && current.$$nextSibling)))) {
  26756. while (current !== target && !(next = current.$$nextSibling)) {
  26757. current = current.$parent;
  26758. }
  26759. }
  26760. } while ((current = next));
  26761. // `break traverseScopesLoop;` takes us to here
  26762. if ((dirty || asyncQueue.length) && !(ttl--)) {
  26763. clearPhase();
  26764. throw $rootScopeMinErr('infdig',
  26765. '{0} $digest() iterations reached. Aborting!\n' +
  26766. 'Watchers fired in the last 5 iterations: {1}',
  26767. TTL, watchLog);
  26768. }
  26769. } while (dirty || asyncQueue.length);
  26770. clearPhase();
  26771. while (postDigestQueue.length) {
  26772. try {
  26773. postDigestQueue.shift()();
  26774. } catch (e) {
  26775. $exceptionHandler(e);
  26776. }
  26777. }
  26778. },
  26779. /**
  26780. * @ngdoc event
  26781. * @name $rootScope.Scope#$destroy
  26782. * @eventType broadcast on scope being destroyed
  26783. *
  26784. * @description
  26785. * Broadcasted when a scope and its children are being destroyed.
  26786. *
  26787. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  26788. * clean up DOM bindings before an element is removed from the DOM.
  26789. */
  26790. /**
  26791. * @ngdoc method
  26792. * @name $rootScope.Scope#$destroy
  26793. * @kind function
  26794. *
  26795. * @description
  26796. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  26797. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  26798. * propagate to the current scope and its children. Removal also implies that the current
  26799. * scope is eligible for garbage collection.
  26800. *
  26801. * The `$destroy()` is usually used by directives such as
  26802. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  26803. * unrolling of the loop.
  26804. *
  26805. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  26806. * Application code can register a `$destroy` event handler that will give it a chance to
  26807. * perform any necessary cleanup.
  26808. *
  26809. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  26810. * clean up DOM bindings before an element is removed from the DOM.
  26811. */
  26812. $destroy: function() {
  26813. // We can't destroy a scope that has been already destroyed.
  26814. if (this.$$destroyed) return;
  26815. var parent = this.$parent;
  26816. this.$broadcast('$destroy');
  26817. this.$$destroyed = true;
  26818. if (this === $rootScope) {
  26819. //Remove handlers attached to window when $rootScope is removed
  26820. $browser.$$applicationDestroyed();
  26821. }
  26822. incrementWatchersCount(this, -this.$$watchersCount);
  26823. for (var eventName in this.$$listenerCount) {
  26824. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  26825. }
  26826. // sever all the references to parent scopes (after this cleanup, the current scope should
  26827. // not be retained by any of our references and should be eligible for garbage collection)
  26828. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  26829. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  26830. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  26831. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  26832. // Disable listeners, watchers and apply/digest methods
  26833. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  26834. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  26835. this.$$listeners = {};
  26836. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  26837. this.$$nextSibling = null;
  26838. cleanUpScope(this);
  26839. },
  26840. /**
  26841. * @ngdoc method
  26842. * @name $rootScope.Scope#$eval
  26843. * @kind function
  26844. *
  26845. * @description
  26846. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  26847. * the expression are propagated (uncaught). This is useful when evaluating Angular
  26848. * expressions.
  26849. *
  26850. * # Example
  26851. * ```js
  26852. var scope = ng.$rootScope.Scope();
  26853. scope.a = 1;
  26854. scope.b = 2;
  26855. expect(scope.$eval('a+b')).toEqual(3);
  26856. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  26857. * ```
  26858. *
  26859. * @param {(string|function())=} expression An angular expression to be executed.
  26860. *
  26861. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26862. * - `function(scope)`: execute the function with the current `scope` parameter.
  26863. *
  26864. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  26865. * @returns {*} The result of evaluating the expression.
  26866. */
  26867. $eval: function(expr, locals) {
  26868. return $parse(expr)(this, locals);
  26869. },
  26870. /**
  26871. * @ngdoc method
  26872. * @name $rootScope.Scope#$evalAsync
  26873. * @kind function
  26874. *
  26875. * @description
  26876. * Executes the expression on the current scope at a later point in time.
  26877. *
  26878. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  26879. * that:
  26880. *
  26881. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  26882. * rendering).
  26883. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  26884. * `expression` execution.
  26885. *
  26886. * Any exceptions from the execution of the expression are forwarded to the
  26887. * {@link ng.$exceptionHandler $exceptionHandler} service.
  26888. *
  26889. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  26890. * will be scheduled. However, it is encouraged to always call code that changes the model
  26891. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  26892. *
  26893. * @param {(string|function())=} expression An angular expression to be executed.
  26894. *
  26895. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26896. * - `function(scope)`: execute the function with the current `scope` parameter.
  26897. *
  26898. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  26899. */
  26900. $evalAsync: function(expr, locals) {
  26901. // if we are outside of an $digest loop and this is the first time we are scheduling async
  26902. // task also schedule async auto-flush
  26903. if (!$rootScope.$$phase && !asyncQueue.length) {
  26904. $browser.defer(function() {
  26905. if (asyncQueue.length) {
  26906. $rootScope.$digest();
  26907. }
  26908. });
  26909. }
  26910. asyncQueue.push({scope: this, expression: $parse(expr), locals: locals});
  26911. },
  26912. $$postDigest: function(fn) {
  26913. postDigestQueue.push(fn);
  26914. },
  26915. /**
  26916. * @ngdoc method
  26917. * @name $rootScope.Scope#$apply
  26918. * @kind function
  26919. *
  26920. * @description
  26921. * `$apply()` is used to execute an expression in angular from outside of the angular
  26922. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  26923. * Because we are calling into the angular framework we need to perform proper scope life
  26924. * cycle of {@link ng.$exceptionHandler exception handling},
  26925. * {@link ng.$rootScope.Scope#$digest executing watches}.
  26926. *
  26927. * ## Life cycle
  26928. *
  26929. * # Pseudo-Code of `$apply()`
  26930. * ```js
  26931. function $apply(expr) {
  26932. try {
  26933. return $eval(expr);
  26934. } catch (e) {
  26935. $exceptionHandler(e);
  26936. } finally {
  26937. $root.$digest();
  26938. }
  26939. }
  26940. * ```
  26941. *
  26942. *
  26943. * Scope's `$apply()` method transitions through the following stages:
  26944. *
  26945. * 1. The {@link guide/expression expression} is executed using the
  26946. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  26947. * 2. Any exceptions from the execution of the expression are forwarded to the
  26948. * {@link ng.$exceptionHandler $exceptionHandler} service.
  26949. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  26950. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  26951. *
  26952. *
  26953. * @param {(string|function())=} exp An angular expression to be executed.
  26954. *
  26955. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26956. * - `function(scope)`: execute the function with current `scope` parameter.
  26957. *
  26958. * @returns {*} The result of evaluating the expression.
  26959. */
  26960. $apply: function(expr) {
  26961. try {
  26962. beginPhase('$apply');
  26963. try {
  26964. return this.$eval(expr);
  26965. } finally {
  26966. clearPhase();
  26967. }
  26968. } catch (e) {
  26969. $exceptionHandler(e);
  26970. } finally {
  26971. try {
  26972. $rootScope.$digest();
  26973. } catch (e) {
  26974. $exceptionHandler(e);
  26975. throw e;
  26976. }
  26977. }
  26978. },
  26979. /**
  26980. * @ngdoc method
  26981. * @name $rootScope.Scope#$applyAsync
  26982. * @kind function
  26983. *
  26984. * @description
  26985. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  26986. * varies across browsers, but is typically around ~10 milliseconds.
  26987. *
  26988. * This can be used to queue up multiple expressions which need to be evaluated in the same
  26989. * digest.
  26990. *
  26991. * @param {(string|function())=} exp An angular expression to be executed.
  26992. *
  26993. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  26994. * - `function(scope)`: execute the function with current `scope` parameter.
  26995. */
  26996. $applyAsync: function(expr) {
  26997. var scope = this;
  26998. expr && applyAsyncQueue.push($applyAsyncExpression);
  26999. expr = $parse(expr);
  27000. scheduleApplyAsync();
  27001. function $applyAsyncExpression() {
  27002. scope.$eval(expr);
  27003. }
  27004. },
  27005. /**
  27006. * @ngdoc method
  27007. * @name $rootScope.Scope#$on
  27008. * @kind function
  27009. *
  27010. * @description
  27011. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  27012. * discussion of event life cycle.
  27013. *
  27014. * The event listener function format is: `function(event, args...)`. The `event` object
  27015. * passed into the listener has the following attributes:
  27016. *
  27017. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  27018. * `$broadcast`-ed.
  27019. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  27020. * event propagates through the scope hierarchy, this property is set to null.
  27021. * - `name` - `{string}`: name of the event.
  27022. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  27023. * further event propagation (available only for events that were `$emit`-ed).
  27024. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  27025. * to true.
  27026. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  27027. *
  27028. * @param {string} name Event name to listen on.
  27029. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  27030. * @returns {function()} Returns a deregistration function for this listener.
  27031. */
  27032. $on: function(name, listener) {
  27033. var namedListeners = this.$$listeners[name];
  27034. if (!namedListeners) {
  27035. this.$$listeners[name] = namedListeners = [];
  27036. }
  27037. namedListeners.push(listener);
  27038. var current = this;
  27039. do {
  27040. if (!current.$$listenerCount[name]) {
  27041. current.$$listenerCount[name] = 0;
  27042. }
  27043. current.$$listenerCount[name]++;
  27044. } while ((current = current.$parent));
  27045. var self = this;
  27046. return function() {
  27047. var indexOfListener = namedListeners.indexOf(listener);
  27048. if (indexOfListener !== -1) {
  27049. namedListeners[indexOfListener] = null;
  27050. decrementListenerCount(self, 1, name);
  27051. }
  27052. };
  27053. },
  27054. /**
  27055. * @ngdoc method
  27056. * @name $rootScope.Scope#$emit
  27057. * @kind function
  27058. *
  27059. * @description
  27060. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  27061. * registered {@link ng.$rootScope.Scope#$on} listeners.
  27062. *
  27063. * The event life cycle starts at the scope on which `$emit` was called. All
  27064. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  27065. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  27066. * registered listeners along the way. The event will stop propagating if one of the listeners
  27067. * cancels it.
  27068. *
  27069. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  27070. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  27071. *
  27072. * @param {string} name Event name to emit.
  27073. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  27074. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  27075. */
  27076. $emit: function(name, args) {
  27077. var empty = [],
  27078. namedListeners,
  27079. scope = this,
  27080. stopPropagation = false,
  27081. event = {
  27082. name: name,
  27083. targetScope: scope,
  27084. stopPropagation: function() {stopPropagation = true;},
  27085. preventDefault: function() {
  27086. event.defaultPrevented = true;
  27087. },
  27088. defaultPrevented: false
  27089. },
  27090. listenerArgs = concat([event], arguments, 1),
  27091. i, length;
  27092. do {
  27093. namedListeners = scope.$$listeners[name] || empty;
  27094. event.currentScope = scope;
  27095. for (i = 0, length = namedListeners.length; i < length; i++) {
  27096. // if listeners were deregistered, defragment the array
  27097. if (!namedListeners[i]) {
  27098. namedListeners.splice(i, 1);
  27099. i--;
  27100. length--;
  27101. continue;
  27102. }
  27103. try {
  27104. //allow all listeners attached to the current scope to run
  27105. namedListeners[i].apply(null, listenerArgs);
  27106. } catch (e) {
  27107. $exceptionHandler(e);
  27108. }
  27109. }
  27110. //if any listener on the current scope stops propagation, prevent bubbling
  27111. if (stopPropagation) {
  27112. event.currentScope = null;
  27113. return event;
  27114. }
  27115. //traverse upwards
  27116. scope = scope.$parent;
  27117. } while (scope);
  27118. event.currentScope = null;
  27119. return event;
  27120. },
  27121. /**
  27122. * @ngdoc method
  27123. * @name $rootScope.Scope#$broadcast
  27124. * @kind function
  27125. *
  27126. * @description
  27127. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  27128. * registered {@link ng.$rootScope.Scope#$on} listeners.
  27129. *
  27130. * The event life cycle starts at the scope on which `$broadcast` was called. All
  27131. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  27132. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  27133. * scope and calls all registered listeners along the way. The event cannot be canceled.
  27134. *
  27135. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  27136. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  27137. *
  27138. * @param {string} name Event name to broadcast.
  27139. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  27140. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  27141. */
  27142. $broadcast: function(name, args) {
  27143. var target = this,
  27144. current = target,
  27145. next = target,
  27146. event = {
  27147. name: name,
  27148. targetScope: target,
  27149. preventDefault: function() {
  27150. event.defaultPrevented = true;
  27151. },
  27152. defaultPrevented: false
  27153. };
  27154. if (!target.$$listenerCount[name]) return event;
  27155. var listenerArgs = concat([event], arguments, 1),
  27156. listeners, i, length;
  27157. //down while you can, then up and next sibling or up and next sibling until back at root
  27158. while ((current = next)) {
  27159. event.currentScope = current;
  27160. listeners = current.$$listeners[name] || [];
  27161. for (i = 0, length = listeners.length; i < length; i++) {
  27162. // if listeners were deregistered, defragment the array
  27163. if (!listeners[i]) {
  27164. listeners.splice(i, 1);
  27165. i--;
  27166. length--;
  27167. continue;
  27168. }
  27169. try {
  27170. listeners[i].apply(null, listenerArgs);
  27171. } catch (e) {
  27172. $exceptionHandler(e);
  27173. }
  27174. }
  27175. // Insanity Warning: scope depth-first traversal
  27176. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  27177. // this piece should be kept in sync with the traversal in $digest
  27178. // (though it differs due to having the extra check for $$listenerCount)
  27179. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  27180. (current !== target && current.$$nextSibling)))) {
  27181. while (current !== target && !(next = current.$$nextSibling)) {
  27182. current = current.$parent;
  27183. }
  27184. }
  27185. }
  27186. event.currentScope = null;
  27187. return event;
  27188. }
  27189. };
  27190. var $rootScope = new Scope();
  27191. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  27192. var asyncQueue = $rootScope.$$asyncQueue = [];
  27193. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  27194. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  27195. return $rootScope;
  27196. function beginPhase(phase) {
  27197. if ($rootScope.$$phase) {
  27198. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  27199. }
  27200. $rootScope.$$phase = phase;
  27201. }
  27202. function clearPhase() {
  27203. $rootScope.$$phase = null;
  27204. }
  27205. function incrementWatchersCount(current, count) {
  27206. do {
  27207. current.$$watchersCount += count;
  27208. } while ((current = current.$parent));
  27209. }
  27210. function decrementListenerCount(current, count, name) {
  27211. do {
  27212. current.$$listenerCount[name] -= count;
  27213. if (current.$$listenerCount[name] === 0) {
  27214. delete current.$$listenerCount[name];
  27215. }
  27216. } while ((current = current.$parent));
  27217. }
  27218. /**
  27219. * function used as an initial value for watchers.
  27220. * because it's unique we can easily tell it apart from other values
  27221. */
  27222. function initWatchVal() {}
  27223. function flushApplyAsync() {
  27224. while (applyAsyncQueue.length) {
  27225. try {
  27226. applyAsyncQueue.shift()();
  27227. } catch (e) {
  27228. $exceptionHandler(e);
  27229. }
  27230. }
  27231. applyAsyncId = null;
  27232. }
  27233. function scheduleApplyAsync() {
  27234. if (applyAsyncId === null) {
  27235. applyAsyncId = $browser.defer(function() {
  27236. $rootScope.$apply(flushApplyAsync);
  27237. });
  27238. }
  27239. }
  27240. }];
  27241. }
  27242. /**
  27243. * @ngdoc service
  27244. * @name $rootElement
  27245. *
  27246. * @description
  27247. * The root element of Angular application. This is either the element where {@link
  27248. * ng.directive:ngApp ngApp} was declared or the element passed into
  27249. * {@link angular.bootstrap}. The element represents the root element of application. It is also the
  27250. * location where the application's {@link auto.$injector $injector} service gets
  27251. * published, and can be retrieved using `$rootElement.injector()`.
  27252. */
  27253. // the implementation is in angular.bootstrap
  27254. /**
  27255. * @description
  27256. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  27257. */
  27258. function $$SanitizeUriProvider() {
  27259. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  27260. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  27261. /**
  27262. * @description
  27263. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  27264. * urls during a[href] sanitization.
  27265. *
  27266. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  27267. *
  27268. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  27269. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  27270. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  27271. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  27272. *
  27273. * @param {RegExp=} regexp New regexp to whitelist urls with.
  27274. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  27275. * chaining otherwise.
  27276. */
  27277. this.aHrefSanitizationWhitelist = function(regexp) {
  27278. if (isDefined(regexp)) {
  27279. aHrefSanitizationWhitelist = regexp;
  27280. return this;
  27281. }
  27282. return aHrefSanitizationWhitelist;
  27283. };
  27284. /**
  27285. * @description
  27286. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  27287. * urls during img[src] sanitization.
  27288. *
  27289. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  27290. *
  27291. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  27292. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  27293. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  27294. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  27295. *
  27296. * @param {RegExp=} regexp New regexp to whitelist urls with.
  27297. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  27298. * chaining otherwise.
  27299. */
  27300. this.imgSrcSanitizationWhitelist = function(regexp) {
  27301. if (isDefined(regexp)) {
  27302. imgSrcSanitizationWhitelist = regexp;
  27303. return this;
  27304. }
  27305. return imgSrcSanitizationWhitelist;
  27306. };
  27307. this.$get = function() {
  27308. return function sanitizeUri(uri, isImage) {
  27309. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  27310. var normalizedVal;
  27311. normalizedVal = urlResolve(uri).href;
  27312. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  27313. return 'unsafe:' + normalizedVal;
  27314. }
  27315. return uri;
  27316. };
  27317. };
  27318. }
  27319. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  27320. * Any commits to this file should be reviewed with security in mind. *
  27321. * Changes to this file can potentially create security vulnerabilities. *
  27322. * An approval from 2 Core members with history of modifying *
  27323. * this file is required. *
  27324. * *
  27325. * Does the change somehow allow for arbitrary javascript to be executed? *
  27326. * Or allows for someone to change the prototype of built-in objects? *
  27327. * Or gives undesired access to variables likes document or window? *
  27328. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  27329. var $sceMinErr = minErr('$sce');
  27330. var SCE_CONTEXTS = {
  27331. HTML: 'html',
  27332. CSS: 'css',
  27333. URL: 'url',
  27334. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  27335. // url. (e.g. ng-include, script src, templateUrl)
  27336. RESOURCE_URL: 'resourceUrl',
  27337. JS: 'js'
  27338. };
  27339. // Helper functions follow.
  27340. function adjustMatcher(matcher) {
  27341. if (matcher === 'self') {
  27342. return matcher;
  27343. } else if (isString(matcher)) {
  27344. // Strings match exactly except for 2 wildcards - '*' and '**'.
  27345. // '*' matches any character except those from the set ':/.?&'.
  27346. // '**' matches any character (like .* in a RegExp).
  27347. // More than 2 *'s raises an error as it's ill defined.
  27348. if (matcher.indexOf('***') > -1) {
  27349. throw $sceMinErr('iwcard',
  27350. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  27351. }
  27352. matcher = escapeForRegexp(matcher).
  27353. replace('\\*\\*', '.*').
  27354. replace('\\*', '[^:/.?&;]*');
  27355. return new RegExp('^' + matcher + '$');
  27356. } else if (isRegExp(matcher)) {
  27357. // The only other type of matcher allowed is a Regexp.
  27358. // Match entire URL / disallow partial matches.
  27359. // Flags are reset (i.e. no global, ignoreCase or multiline)
  27360. return new RegExp('^' + matcher.source + '$');
  27361. } else {
  27362. throw $sceMinErr('imatcher',
  27363. 'Matchers may only be "self", string patterns or RegExp objects');
  27364. }
  27365. }
  27366. function adjustMatchers(matchers) {
  27367. var adjustedMatchers = [];
  27368. if (isDefined(matchers)) {
  27369. forEach(matchers, function(matcher) {
  27370. adjustedMatchers.push(adjustMatcher(matcher));
  27371. });
  27372. }
  27373. return adjustedMatchers;
  27374. }
  27375. /**
  27376. * @ngdoc service
  27377. * @name $sceDelegate
  27378. * @kind function
  27379. *
  27380. * @description
  27381. *
  27382. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  27383. * Contextual Escaping (SCE)} services to AngularJS.
  27384. *
  27385. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  27386. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  27387. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  27388. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  27389. * work because `$sce` delegates to `$sceDelegate` for these operations.
  27390. *
  27391. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  27392. *
  27393. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  27394. * can override it completely to change the behavior of `$sce`, the common case would
  27395. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  27396. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  27397. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  27398. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  27399. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  27400. */
  27401. /**
  27402. * @ngdoc provider
  27403. * @name $sceDelegateProvider
  27404. * @description
  27405. *
  27406. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  27407. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  27408. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  27409. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  27410. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  27411. *
  27412. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  27413. * Strict Contextual Escaping (SCE)}.
  27414. *
  27415. * **Example**: Consider the following case. <a name="example"></a>
  27416. *
  27417. * - your app is hosted at url `http://myapp.example.com/`
  27418. * - but some of your templates are hosted on other domains you control such as
  27419. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  27420. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  27421. *
  27422. * Here is what a secure configuration for this scenario might look like:
  27423. *
  27424. * ```
  27425. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  27426. * $sceDelegateProvider.resourceUrlWhitelist([
  27427. * // Allow same origin resource loads.
  27428. * 'self',
  27429. * // Allow loading from our assets domain. Notice the difference between * and **.
  27430. * 'http://srv*.assets.example.com/**'
  27431. * ]);
  27432. *
  27433. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  27434. * $sceDelegateProvider.resourceUrlBlacklist([
  27435. * 'http://myapp.example.com/clickThru**'
  27436. * ]);
  27437. * });
  27438. * ```
  27439. */
  27440. function $SceDelegateProvider() {
  27441. this.SCE_CONTEXTS = SCE_CONTEXTS;
  27442. // Resource URLs can also be trusted by policy.
  27443. var resourceUrlWhitelist = ['self'],
  27444. resourceUrlBlacklist = [];
  27445. /**
  27446. * @ngdoc method
  27447. * @name $sceDelegateProvider#resourceUrlWhitelist
  27448. * @kind function
  27449. *
  27450. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  27451. * provided. This must be an array or null. A snapshot of this array is used so further
  27452. * changes to the array are ignored.
  27453. *
  27454. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  27455. * allowed in this array.
  27456. *
  27457. * <div class="alert alert-warning">
  27458. * **Note:** an empty whitelist array will block all URLs!
  27459. * </div>
  27460. *
  27461. * @return {Array} the currently set whitelist array.
  27462. *
  27463. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  27464. * same origin resource requests.
  27465. *
  27466. * @description
  27467. * Sets/Gets the whitelist of trusted resource URLs.
  27468. */
  27469. this.resourceUrlWhitelist = function(value) {
  27470. if (arguments.length) {
  27471. resourceUrlWhitelist = adjustMatchers(value);
  27472. }
  27473. return resourceUrlWhitelist;
  27474. };
  27475. /**
  27476. * @ngdoc method
  27477. * @name $sceDelegateProvider#resourceUrlBlacklist
  27478. * @kind function
  27479. *
  27480. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  27481. * provided. This must be an array or null. A snapshot of this array is used so further
  27482. * changes to the array are ignored.
  27483. *
  27484. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  27485. * allowed in this array.
  27486. *
  27487. * The typical usage for the blacklist is to **block
  27488. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  27489. * these would otherwise be trusted but actually return content from the redirected domain.
  27490. *
  27491. * Finally, **the blacklist overrides the whitelist** and has the final say.
  27492. *
  27493. * @return {Array} the currently set blacklist array.
  27494. *
  27495. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  27496. * is no blacklist.)
  27497. *
  27498. * @description
  27499. * Sets/Gets the blacklist of trusted resource URLs.
  27500. */
  27501. this.resourceUrlBlacklist = function(value) {
  27502. if (arguments.length) {
  27503. resourceUrlBlacklist = adjustMatchers(value);
  27504. }
  27505. return resourceUrlBlacklist;
  27506. };
  27507. this.$get = ['$injector', function($injector) {
  27508. var htmlSanitizer = function htmlSanitizer(html) {
  27509. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  27510. };
  27511. if ($injector.has('$sanitize')) {
  27512. htmlSanitizer = $injector.get('$sanitize');
  27513. }
  27514. function matchUrl(matcher, parsedUrl) {
  27515. if (matcher === 'self') {
  27516. return urlIsSameOrigin(parsedUrl);
  27517. } else {
  27518. // definitely a regex. See adjustMatchers()
  27519. return !!matcher.exec(parsedUrl.href);
  27520. }
  27521. }
  27522. function isResourceUrlAllowedByPolicy(url) {
  27523. var parsedUrl = urlResolve(url.toString());
  27524. var i, n, allowed = false;
  27525. // Ensure that at least one item from the whitelist allows this url.
  27526. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  27527. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  27528. allowed = true;
  27529. break;
  27530. }
  27531. }
  27532. if (allowed) {
  27533. // Ensure that no item from the blacklist blocked this url.
  27534. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  27535. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  27536. allowed = false;
  27537. break;
  27538. }
  27539. }
  27540. }
  27541. return allowed;
  27542. }
  27543. function generateHolderType(Base) {
  27544. var holderType = function TrustedValueHolderType(trustedValue) {
  27545. this.$$unwrapTrustedValue = function() {
  27546. return trustedValue;
  27547. };
  27548. };
  27549. if (Base) {
  27550. holderType.prototype = new Base();
  27551. }
  27552. holderType.prototype.valueOf = function sceValueOf() {
  27553. return this.$$unwrapTrustedValue();
  27554. };
  27555. holderType.prototype.toString = function sceToString() {
  27556. return this.$$unwrapTrustedValue().toString();
  27557. };
  27558. return holderType;
  27559. }
  27560. var trustedValueHolderBase = generateHolderType(),
  27561. byType = {};
  27562. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  27563. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  27564. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  27565. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  27566. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  27567. /**
  27568. * @ngdoc method
  27569. * @name $sceDelegate#trustAs
  27570. *
  27571. * @description
  27572. * Returns an object that is trusted by angular for use in specified strict
  27573. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  27574. * attribute interpolation, any dom event binding attribute interpolation
  27575. * such as for onclick, etc.) that uses the provided value.
  27576. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  27577. *
  27578. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  27579. * resourceUrl, html, js and css.
  27580. * @param {*} value The value that that should be considered trusted/safe.
  27581. * @returns {*} A value that can be used to stand in for the provided `value` in places
  27582. * where Angular expects a $sce.trustAs() return value.
  27583. */
  27584. function trustAs(type, trustedValue) {
  27585. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  27586. if (!Constructor) {
  27587. throw $sceMinErr('icontext',
  27588. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  27589. type, trustedValue);
  27590. }
  27591. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  27592. return trustedValue;
  27593. }
  27594. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  27595. // mutable objects, we ensure here that the value passed in is actually a string.
  27596. if (typeof trustedValue !== 'string') {
  27597. throw $sceMinErr('itype',
  27598. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  27599. type);
  27600. }
  27601. return new Constructor(trustedValue);
  27602. }
  27603. /**
  27604. * @ngdoc method
  27605. * @name $sceDelegate#valueOf
  27606. *
  27607. * @description
  27608. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  27609. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  27610. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  27611. *
  27612. * If the passed parameter is not a value that had been returned by {@link
  27613. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  27614. *
  27615. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  27616. * call or anything else.
  27617. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  27618. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  27619. * `value` unchanged.
  27620. */
  27621. function valueOf(maybeTrusted) {
  27622. if (maybeTrusted instanceof trustedValueHolderBase) {
  27623. return maybeTrusted.$$unwrapTrustedValue();
  27624. } else {
  27625. return maybeTrusted;
  27626. }
  27627. }
  27628. /**
  27629. * @ngdoc method
  27630. * @name $sceDelegate#getTrusted
  27631. *
  27632. * @description
  27633. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  27634. * returns the originally supplied value if the queried context type is a supertype of the
  27635. * created type. If this condition isn't satisfied, throws an exception.
  27636. *
  27637. * <div class="alert alert-danger">
  27638. * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting
  27639. * (XSS) vulnerability in your application.
  27640. * </div>
  27641. *
  27642. * @param {string} type The kind of context in which this value is to be used.
  27643. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  27644. * `$sceDelegate.trustAs`} call.
  27645. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  27646. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  27647. */
  27648. function getTrusted(type, maybeTrusted) {
  27649. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  27650. return maybeTrusted;
  27651. }
  27652. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  27653. if (constructor && maybeTrusted instanceof constructor) {
  27654. return maybeTrusted.$$unwrapTrustedValue();
  27655. }
  27656. // If we get here, then we may only take one of two actions.
  27657. // 1. sanitize the value for the requested type, or
  27658. // 2. throw an exception.
  27659. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  27660. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  27661. return maybeTrusted;
  27662. } else {
  27663. throw $sceMinErr('insecurl',
  27664. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  27665. maybeTrusted.toString());
  27666. }
  27667. } else if (type === SCE_CONTEXTS.HTML) {
  27668. return htmlSanitizer(maybeTrusted);
  27669. }
  27670. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  27671. }
  27672. return { trustAs: trustAs,
  27673. getTrusted: getTrusted,
  27674. valueOf: valueOf };
  27675. }];
  27676. }
  27677. /**
  27678. * @ngdoc provider
  27679. * @name $sceProvider
  27680. * @description
  27681. *
  27682. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  27683. * - enable/disable Strict Contextual Escaping (SCE) in a module
  27684. * - override the default implementation with a custom delegate
  27685. *
  27686. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  27687. */
  27688. /* jshint maxlen: false*/
  27689. /**
  27690. * @ngdoc service
  27691. * @name $sce
  27692. * @kind function
  27693. *
  27694. * @description
  27695. *
  27696. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  27697. *
  27698. * # Strict Contextual Escaping
  27699. *
  27700. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  27701. * contexts to result in a value that is marked as safe to use for that context. One example of
  27702. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  27703. * to these contexts as privileged or SCE contexts.
  27704. *
  27705. * As of version 1.2, Angular ships with SCE enabled by default.
  27706. *
  27707. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  27708. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  27709. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  27710. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  27711. * to the top of your HTML document.
  27712. *
  27713. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  27714. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  27715. *
  27716. * Here's an example of a binding in a privileged context:
  27717. *
  27718. * ```
  27719. * <input ng-model="userHtml" aria-label="User input">
  27720. * <div ng-bind-html="userHtml"></div>
  27721. * ```
  27722. *
  27723. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  27724. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  27725. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  27726. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  27727. * security vulnerabilities.)
  27728. *
  27729. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  27730. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  27731. *
  27732. * How would you ensure that every place that used these types of bindings was bound to a value that
  27733. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  27734. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  27735. * properties/fields and forgot to update the binding to the sanitized value?
  27736. *
  27737. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  27738. * determine that something explicitly says it's safe to use a value for binding in that
  27739. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  27740. * for those values that you can easily tell are safe - because they were received from your server,
  27741. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  27742. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  27743. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  27744. *
  27745. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  27746. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  27747. * obtain values that will be accepted by SCE / privileged contexts.
  27748. *
  27749. *
  27750. * ## How does it work?
  27751. *
  27752. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  27753. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  27754. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  27755. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  27756. *
  27757. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  27758. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  27759. * simplified):
  27760. *
  27761. * ```
  27762. * var ngBindHtmlDirective = ['$sce', function($sce) {
  27763. * return function(scope, element, attr) {
  27764. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  27765. * element.html(value || '');
  27766. * });
  27767. * };
  27768. * }];
  27769. * ```
  27770. *
  27771. * ## Impact on loading templates
  27772. *
  27773. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  27774. * `templateUrl`'s specified by {@link guide/directive directives}.
  27775. *
  27776. * By default, Angular only loads templates from the same domain and protocol as the application
  27777. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  27778. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  27779. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  27780. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  27781. *
  27782. * *Please note*:
  27783. * The browser's
  27784. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  27785. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  27786. * policy apply in addition to this and may further restrict whether the template is successfully
  27787. * loaded. This means that without the right CORS policy, loading templates from a different domain
  27788. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  27789. * browsers.
  27790. *
  27791. * ## This feels like too much overhead
  27792. *
  27793. * It's important to remember that SCE only applies to interpolation expressions.
  27794. *
  27795. * If your expressions are constant literals, they're automatically trusted and you don't need to
  27796. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  27797. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  27798. *
  27799. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  27800. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  27801. *
  27802. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  27803. * templates in `ng-include` from your application's domain without having to even know about SCE.
  27804. * It blocks loading templates from other domains or loading templates over http from an https
  27805. * served document. You can change these by setting your own custom {@link
  27806. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  27807. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  27808. *
  27809. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  27810. * application that's secure and can be audited to verify that with much more ease than bolting
  27811. * security onto an application later.
  27812. *
  27813. * <a name="contexts"></a>
  27814. * ## What trusted context types are supported?
  27815. *
  27816. * | Context | Notes |
  27817. * |---------------------|----------------|
  27818. * | `$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. |
  27819. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  27820. * | `$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. |
  27821. * | `$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. |
  27822. * | `$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. |
  27823. *
  27824. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  27825. *
  27826. * Each element in these arrays must be one of the following:
  27827. *
  27828. * - **'self'**
  27829. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  27830. * domain** as the application document using the **same protocol**.
  27831. * - **String** (except the special value `'self'`)
  27832. * - The string is matched against the full *normalized / absolute URL* of the resource
  27833. * being tested (substring matches are not good enough.)
  27834. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  27835. * match themselves.
  27836. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  27837. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  27838. * in a whitelist.
  27839. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  27840. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  27841. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  27842. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  27843. * http://foo.example.com/templates/**).
  27844. * - **RegExp** (*see caveat below*)
  27845. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  27846. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  27847. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  27848. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  27849. * small number of cases. A `.` character in the regex used when matching the scheme or a
  27850. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  27851. * is highly recommended to use the string patterns and only fall back to regular expressions
  27852. * as a last resort.
  27853. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  27854. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  27855. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  27856. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  27857. * - If you are generating your JavaScript from some other templating engine (not
  27858. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  27859. * remember to escape your regular expression (and be aware that you might need more than
  27860. * one level of escaping depending on your templating engine and the way you interpolated
  27861. * the value.) Do make use of your platform's escaping mechanism as it might be good
  27862. * enough before coding your own. E.g. Ruby has
  27863. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  27864. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  27865. * Javascript lacks a similar built in function for escaping. Take a look at Google
  27866. * Closure library's [goog.string.regExpEscape(s)](
  27867. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  27868. *
  27869. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  27870. *
  27871. * ## Show me an example using SCE.
  27872. *
  27873. * <example module="mySceApp" deps="angular-sanitize.js">
  27874. * <file name="index.html">
  27875. * <div ng-controller="AppController as myCtrl">
  27876. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  27877. * <b>User comments</b><br>
  27878. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  27879. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  27880. * exploit.
  27881. * <div class="well">
  27882. * <div ng-repeat="userComment in myCtrl.userComments">
  27883. * <b>{{userComment.name}}</b>:
  27884. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  27885. * <br>
  27886. * </div>
  27887. * </div>
  27888. * </div>
  27889. * </file>
  27890. *
  27891. * <file name="script.js">
  27892. * angular.module('mySceApp', ['ngSanitize'])
  27893. * .controller('AppController', ['$http', '$templateCache', '$sce',
  27894. * function($http, $templateCache, $sce) {
  27895. * var self = this;
  27896. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  27897. * self.userComments = userComments;
  27898. * });
  27899. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  27900. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  27901. * 'sanitization.&quot;">Hover over this text.</span>');
  27902. * }]);
  27903. * </file>
  27904. *
  27905. * <file name="test_data.json">
  27906. * [
  27907. * { "name": "Alice",
  27908. * "htmlComment":
  27909. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  27910. * },
  27911. * { "name": "Bob",
  27912. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  27913. * }
  27914. * ]
  27915. * </file>
  27916. *
  27917. * <file name="protractor.js" type="protractor">
  27918. * describe('SCE doc demo', function() {
  27919. * it('should sanitize untrusted values', function() {
  27920. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  27921. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  27922. * });
  27923. *
  27924. * it('should NOT sanitize explicitly trusted values', function() {
  27925. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  27926. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  27927. * 'sanitization.&quot;">Hover over this text.</span>');
  27928. * });
  27929. * });
  27930. * </file>
  27931. * </example>
  27932. *
  27933. *
  27934. *
  27935. * ## Can I disable SCE completely?
  27936. *
  27937. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  27938. * for little coding overhead. It will be much harder to take an SCE disabled application and
  27939. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  27940. * for cases where you have a lot of existing code that was written before SCE was introduced and
  27941. * you're migrating them a module at a time.
  27942. *
  27943. * That said, here's how you can completely disable SCE:
  27944. *
  27945. * ```
  27946. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  27947. * // Completely disable SCE. For demonstration purposes only!
  27948. * // Do not use in new projects.
  27949. * $sceProvider.enabled(false);
  27950. * });
  27951. * ```
  27952. *
  27953. */
  27954. /* jshint maxlen: 100 */
  27955. function $SceProvider() {
  27956. var enabled = true;
  27957. /**
  27958. * @ngdoc method
  27959. * @name $sceProvider#enabled
  27960. * @kind function
  27961. *
  27962. * @param {boolean=} value If provided, then enables/disables SCE.
  27963. * @return {boolean} true if SCE is enabled, false otherwise.
  27964. *
  27965. * @description
  27966. * Enables/disables SCE and returns the current value.
  27967. */
  27968. this.enabled = function(value) {
  27969. if (arguments.length) {
  27970. enabled = !!value;
  27971. }
  27972. return enabled;
  27973. };
  27974. /* Design notes on the default implementation for SCE.
  27975. *
  27976. * The API contract for the SCE delegate
  27977. * -------------------------------------
  27978. * The SCE delegate object must provide the following 3 methods:
  27979. *
  27980. * - trustAs(contextEnum, value)
  27981. * This method is used to tell the SCE service that the provided value is OK to use in the
  27982. * contexts specified by contextEnum. It must return an object that will be accepted by
  27983. * getTrusted() for a compatible contextEnum and return this value.
  27984. *
  27985. * - valueOf(value)
  27986. * For values that were not produced by trustAs(), return them as is. For values that were
  27987. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  27988. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  27989. * such a value.
  27990. *
  27991. * - getTrusted(contextEnum, value)
  27992. * This function should return the a value that is safe to use in the context specified by
  27993. * contextEnum or throw and exception otherwise.
  27994. *
  27995. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  27996. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  27997. * instance, an implementation could maintain a registry of all trusted objects by context. In
  27998. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  27999. * return the same object passed in if it was found in the registry under a compatible context or
  28000. * throw an exception otherwise. An implementation might only wrap values some of the time based
  28001. * on some criteria. getTrusted() might return a value and not throw an exception for special
  28002. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  28003. *
  28004. *
  28005. * A note on the inheritance model for SCE contexts
  28006. * ------------------------------------------------
  28007. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  28008. * is purely an implementation details.
  28009. *
  28010. * The contract is simply this:
  28011. *
  28012. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  28013. * will also succeed.
  28014. *
  28015. * Inheritance happens to capture this in a natural way. In some future, we
  28016. * may not use inheritance anymore. That is OK because no code outside of
  28017. * sce.js and sceSpecs.js would need to be aware of this detail.
  28018. */
  28019. this.$get = ['$parse', '$sceDelegate', function(
  28020. $parse, $sceDelegate) {
  28021. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  28022. // the "expression(javascript expression)" syntax which is insecure.
  28023. if (enabled && msie < 8) {
  28024. throw $sceMinErr('iequirks',
  28025. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  28026. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  28027. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  28028. }
  28029. var sce = shallowCopy(SCE_CONTEXTS);
  28030. /**
  28031. * @ngdoc method
  28032. * @name $sce#isEnabled
  28033. * @kind function
  28034. *
  28035. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  28036. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  28037. *
  28038. * @description
  28039. * Returns a boolean indicating if SCE is enabled.
  28040. */
  28041. sce.isEnabled = function() {
  28042. return enabled;
  28043. };
  28044. sce.trustAs = $sceDelegate.trustAs;
  28045. sce.getTrusted = $sceDelegate.getTrusted;
  28046. sce.valueOf = $sceDelegate.valueOf;
  28047. if (!enabled) {
  28048. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  28049. sce.valueOf = identity;
  28050. }
  28051. /**
  28052. * @ngdoc method
  28053. * @name $sce#parseAs
  28054. *
  28055. * @description
  28056. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  28057. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  28058. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  28059. * *result*)}
  28060. *
  28061. * @param {string} type The kind of SCE context in which this result will be used.
  28062. * @param {string} expression String expression to compile.
  28063. * @returns {function(context, locals)} a function which represents the compiled expression:
  28064. *
  28065. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28066. * are evaluated against (typically a scope object).
  28067. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28068. * `context`.
  28069. */
  28070. sce.parseAs = function sceParseAs(type, expr) {
  28071. var parsed = $parse(expr);
  28072. if (parsed.literal && parsed.constant) {
  28073. return parsed;
  28074. } else {
  28075. return $parse(expr, function(value) {
  28076. return sce.getTrusted(type, value);
  28077. });
  28078. }
  28079. };
  28080. /**
  28081. * @ngdoc method
  28082. * @name $sce#trustAs
  28083. *
  28084. * @description
  28085. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  28086. * returns an object that is trusted by angular for use in specified strict contextual
  28087. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  28088. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  28089. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  28090. * escaping.
  28091. *
  28092. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  28093. * resourceUrl, html, js and css.
  28094. * @param {*} value The value that that should be considered trusted/safe.
  28095. * @returns {*} A value that can be used to stand in for the provided `value` in places
  28096. * where Angular expects a $sce.trustAs() return value.
  28097. */
  28098. /**
  28099. * @ngdoc method
  28100. * @name $sce#trustAsHtml
  28101. *
  28102. * @description
  28103. * Shorthand method. `$sce.trustAsHtml(value)` →
  28104. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  28105. *
  28106. * @param {*} value The value to trustAs.
  28107. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  28108. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  28109. * only accept expressions that are either literal constants or are the
  28110. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28111. */
  28112. /**
  28113. * @ngdoc method
  28114. * @name $sce#trustAsUrl
  28115. *
  28116. * @description
  28117. * Shorthand method. `$sce.trustAsUrl(value)` →
  28118. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  28119. *
  28120. * @param {*} value The value to trustAs.
  28121. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  28122. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  28123. * only accept expressions that are either literal constants or are the
  28124. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28125. */
  28126. /**
  28127. * @ngdoc method
  28128. * @name $sce#trustAsResourceUrl
  28129. *
  28130. * @description
  28131. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  28132. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  28133. *
  28134. * @param {*} value The value to trustAs.
  28135. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  28136. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  28137. * only accept expressions that are either literal constants or are the return
  28138. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28139. */
  28140. /**
  28141. * @ngdoc method
  28142. * @name $sce#trustAsJs
  28143. *
  28144. * @description
  28145. * Shorthand method. `$sce.trustAsJs(value)` →
  28146. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  28147. *
  28148. * @param {*} value The value to trustAs.
  28149. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  28150. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  28151. * only accept expressions that are either literal constants or are the
  28152. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  28153. */
  28154. /**
  28155. * @ngdoc method
  28156. * @name $sce#getTrusted
  28157. *
  28158. * @description
  28159. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  28160. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  28161. * originally supplied value if the queried context type is a supertype of the created type.
  28162. * If this condition isn't satisfied, throws an exception.
  28163. *
  28164. * @param {string} type The kind of context in which this value is to be used.
  28165. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  28166. * call.
  28167. * @returns {*} The value the was originally provided to
  28168. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  28169. * Otherwise, throws an exception.
  28170. */
  28171. /**
  28172. * @ngdoc method
  28173. * @name $sce#getTrustedHtml
  28174. *
  28175. * @description
  28176. * Shorthand method. `$sce.getTrustedHtml(value)` →
  28177. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  28178. *
  28179. * @param {*} value The value to pass to `$sce.getTrusted`.
  28180. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  28181. */
  28182. /**
  28183. * @ngdoc method
  28184. * @name $sce#getTrustedCss
  28185. *
  28186. * @description
  28187. * Shorthand method. `$sce.getTrustedCss(value)` →
  28188. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  28189. *
  28190. * @param {*} value The value to pass to `$sce.getTrusted`.
  28191. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  28192. */
  28193. /**
  28194. * @ngdoc method
  28195. * @name $sce#getTrustedUrl
  28196. *
  28197. * @description
  28198. * Shorthand method. `$sce.getTrustedUrl(value)` →
  28199. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  28200. *
  28201. * @param {*} value The value to pass to `$sce.getTrusted`.
  28202. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  28203. */
  28204. /**
  28205. * @ngdoc method
  28206. * @name $sce#getTrustedResourceUrl
  28207. *
  28208. * @description
  28209. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  28210. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  28211. *
  28212. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  28213. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  28214. */
  28215. /**
  28216. * @ngdoc method
  28217. * @name $sce#getTrustedJs
  28218. *
  28219. * @description
  28220. * Shorthand method. `$sce.getTrustedJs(value)` →
  28221. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  28222. *
  28223. * @param {*} value The value to pass to `$sce.getTrusted`.
  28224. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  28225. */
  28226. /**
  28227. * @ngdoc method
  28228. * @name $sce#parseAsHtml
  28229. *
  28230. * @description
  28231. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  28232. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  28233. *
  28234. * @param {string} expression String expression to compile.
  28235. * @returns {function(context, locals)} a function which represents the compiled expression:
  28236. *
  28237. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28238. * are evaluated against (typically a scope object).
  28239. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28240. * `context`.
  28241. */
  28242. /**
  28243. * @ngdoc method
  28244. * @name $sce#parseAsCss
  28245. *
  28246. * @description
  28247. * Shorthand method. `$sce.parseAsCss(value)` →
  28248. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  28249. *
  28250. * @param {string} expression String expression to compile.
  28251. * @returns {function(context, locals)} a function which represents the compiled expression:
  28252. *
  28253. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28254. * are evaluated against (typically a scope object).
  28255. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28256. * `context`.
  28257. */
  28258. /**
  28259. * @ngdoc method
  28260. * @name $sce#parseAsUrl
  28261. *
  28262. * @description
  28263. * Shorthand method. `$sce.parseAsUrl(value)` →
  28264. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  28265. *
  28266. * @param {string} expression String expression to compile.
  28267. * @returns {function(context, locals)} a function which represents the compiled expression:
  28268. *
  28269. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28270. * are evaluated against (typically a scope object).
  28271. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28272. * `context`.
  28273. */
  28274. /**
  28275. * @ngdoc method
  28276. * @name $sce#parseAsResourceUrl
  28277. *
  28278. * @description
  28279. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  28280. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  28281. *
  28282. * @param {string} expression String expression to compile.
  28283. * @returns {function(context, locals)} a function which represents the compiled expression:
  28284. *
  28285. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28286. * are evaluated against (typically a scope object).
  28287. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28288. * `context`.
  28289. */
  28290. /**
  28291. * @ngdoc method
  28292. * @name $sce#parseAsJs
  28293. *
  28294. * @description
  28295. * Shorthand method. `$sce.parseAsJs(value)` →
  28296. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  28297. *
  28298. * @param {string} expression String expression to compile.
  28299. * @returns {function(context, locals)} a function which represents the compiled expression:
  28300. *
  28301. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  28302. * are evaluated against (typically a scope object).
  28303. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  28304. * `context`.
  28305. */
  28306. // Shorthand delegations.
  28307. var parse = sce.parseAs,
  28308. getTrusted = sce.getTrusted,
  28309. trustAs = sce.trustAs;
  28310. forEach(SCE_CONTEXTS, function(enumValue, name) {
  28311. var lName = lowercase(name);
  28312. sce[camelCase("parse_as_" + lName)] = function(expr) {
  28313. return parse(enumValue, expr);
  28314. };
  28315. sce[camelCase("get_trusted_" + lName)] = function(value) {
  28316. return getTrusted(enumValue, value);
  28317. };
  28318. sce[camelCase("trust_as_" + lName)] = function(value) {
  28319. return trustAs(enumValue, value);
  28320. };
  28321. });
  28322. return sce;
  28323. }];
  28324. }
  28325. /**
  28326. * !!! This is an undocumented "private" service !!!
  28327. *
  28328. * @name $sniffer
  28329. * @requires $window
  28330. * @requires $document
  28331. *
  28332. * @property {boolean} history Does the browser support html5 history api ?
  28333. * @property {boolean} transitions Does the browser support CSS transition events ?
  28334. * @property {boolean} animations Does the browser support CSS animation events ?
  28335. *
  28336. * @description
  28337. * This is very simple implementation of testing browser's features.
  28338. */
  28339. function $SnifferProvider() {
  28340. this.$get = ['$window', '$document', function($window, $document) {
  28341. var eventSupport = {},
  28342. // Chrome Packaged Apps are not allowed to access `history.pushState`. They can be detected by
  28343. // the presence of `chrome.app.runtime` (see https://developer.chrome.com/apps/api_index)
  28344. isChromePackagedApp = $window.chrome && $window.chrome.app && $window.chrome.app.runtime,
  28345. hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState,
  28346. android =
  28347. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  28348. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  28349. document = $document[0] || {},
  28350. vendorPrefix,
  28351. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  28352. bodyStyle = document.body && document.body.style,
  28353. transitions = false,
  28354. animations = false,
  28355. match;
  28356. if (bodyStyle) {
  28357. for (var prop in bodyStyle) {
  28358. if (match = vendorRegex.exec(prop)) {
  28359. vendorPrefix = match[0];
  28360. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  28361. break;
  28362. }
  28363. }
  28364. if (!vendorPrefix) {
  28365. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  28366. }
  28367. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  28368. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  28369. if (android && (!transitions || !animations)) {
  28370. transitions = isString(bodyStyle.webkitTransition);
  28371. animations = isString(bodyStyle.webkitAnimation);
  28372. }
  28373. }
  28374. return {
  28375. // Android has history.pushState, but it does not update location correctly
  28376. // so let's not use the history API at all.
  28377. // http://code.google.com/p/android/issues/detail?id=17471
  28378. // https://github.com/angular/angular.js/issues/904
  28379. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  28380. // so let's not use the history API also
  28381. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  28382. // jshint -W018
  28383. history: !!(hasHistoryPushState && !(android < 4) && !boxee),
  28384. // jshint +W018
  28385. hasEvent: function(event) {
  28386. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  28387. // it. In particular the event is not fired when backspace or delete key are pressed or
  28388. // when cut operation is performed.
  28389. // IE10+ implements 'input' event but it erroneously fires under various situations,
  28390. // e.g. when placeholder changes, or a form is focused.
  28391. if (event === 'input' && msie <= 11) return false;
  28392. if (isUndefined(eventSupport[event])) {
  28393. var divElm = document.createElement('div');
  28394. eventSupport[event] = 'on' + event in divElm;
  28395. }
  28396. return eventSupport[event];
  28397. },
  28398. csp: csp(),
  28399. vendorPrefix: vendorPrefix,
  28400. transitions: transitions,
  28401. animations: animations,
  28402. android: android
  28403. };
  28404. }];
  28405. }
  28406. var $templateRequestMinErr = minErr('$compile');
  28407. /**
  28408. * @ngdoc provider
  28409. * @name $templateRequestProvider
  28410. * @description
  28411. * Used to configure the options passed to the {@link $http} service when making a template request.
  28412. *
  28413. * For example, it can be used for specifying the "Accept" header that is sent to the server, when
  28414. * requesting a template.
  28415. */
  28416. function $TemplateRequestProvider() {
  28417. var httpOptions;
  28418. /**
  28419. * @ngdoc method
  28420. * @name $templateRequestProvider#httpOptions
  28421. * @description
  28422. * The options to be passed to the {@link $http} service when making the request.
  28423. * You can use this to override options such as the "Accept" header for template requests.
  28424. *
  28425. * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the
  28426. * options if not overridden here.
  28427. *
  28428. * @param {string=} value new value for the {@link $http} options.
  28429. * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter.
  28430. */
  28431. this.httpOptions = function(val) {
  28432. if (val) {
  28433. httpOptions = val;
  28434. return this;
  28435. }
  28436. return httpOptions;
  28437. };
  28438. /**
  28439. * @ngdoc service
  28440. * @name $templateRequest
  28441. *
  28442. * @description
  28443. * The `$templateRequest` service runs security checks then downloads the provided template using
  28444. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  28445. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  28446. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  28447. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  28448. * when `tpl` is of type string and `$templateCache` has the matching entry.
  28449. *
  28450. * If you want to pass custom options to the `$http` service, such as setting the Accept header you
  28451. * can configure this via {@link $templateRequestProvider#httpOptions}.
  28452. *
  28453. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  28454. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  28455. *
  28456. * @return {Promise} a promise for the HTTP response data of the given URL.
  28457. *
  28458. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  28459. */
  28460. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  28461. function handleRequestFn(tpl, ignoreRequestError) {
  28462. handleRequestFn.totalPendingRequests++;
  28463. // We consider the template cache holds only trusted templates, so
  28464. // there's no need to go through whitelisting again for keys that already
  28465. // are included in there. This also makes Angular accept any script
  28466. // directive, no matter its name. However, we still need to unwrap trusted
  28467. // types.
  28468. if (!isString(tpl) || !$templateCache.get(tpl)) {
  28469. tpl = $sce.getTrustedResourceUrl(tpl);
  28470. }
  28471. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  28472. if (isArray(transformResponse)) {
  28473. transformResponse = transformResponse.filter(function(transformer) {
  28474. return transformer !== defaultHttpResponseTransform;
  28475. });
  28476. } else if (transformResponse === defaultHttpResponseTransform) {
  28477. transformResponse = null;
  28478. }
  28479. return $http.get(tpl, extend({
  28480. cache: $templateCache,
  28481. transformResponse: transformResponse
  28482. }, httpOptions))
  28483. ['finally'](function() {
  28484. handleRequestFn.totalPendingRequests--;
  28485. })
  28486. .then(function(response) {
  28487. $templateCache.put(tpl, response.data);
  28488. return response.data;
  28489. }, handleError);
  28490. function handleError(resp) {
  28491. if (!ignoreRequestError) {
  28492. throw $templateRequestMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  28493. tpl, resp.status, resp.statusText);
  28494. }
  28495. return $q.reject(resp);
  28496. }
  28497. }
  28498. handleRequestFn.totalPendingRequests = 0;
  28499. return handleRequestFn;
  28500. }];
  28501. }
  28502. function $$TestabilityProvider() {
  28503. this.$get = ['$rootScope', '$browser', '$location',
  28504. function($rootScope, $browser, $location) {
  28505. /**
  28506. * @name $testability
  28507. *
  28508. * @description
  28509. * The private $$testability service provides a collection of methods for use when debugging
  28510. * or by automated test and debugging tools.
  28511. */
  28512. var testability = {};
  28513. /**
  28514. * @name $$testability#findBindings
  28515. *
  28516. * @description
  28517. * Returns an array of elements that are bound (via ng-bind or {{}})
  28518. * to expressions matching the input.
  28519. *
  28520. * @param {Element} element The element root to search from.
  28521. * @param {string} expression The binding expression to match.
  28522. * @param {boolean} opt_exactMatch If true, only returns exact matches
  28523. * for the expression. Filters and whitespace are ignored.
  28524. */
  28525. testability.findBindings = function(element, expression, opt_exactMatch) {
  28526. var bindings = element.getElementsByClassName('ng-binding');
  28527. var matches = [];
  28528. forEach(bindings, function(binding) {
  28529. var dataBinding = angular.element(binding).data('$binding');
  28530. if (dataBinding) {
  28531. forEach(dataBinding, function(bindingName) {
  28532. if (opt_exactMatch) {
  28533. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  28534. if (matcher.test(bindingName)) {
  28535. matches.push(binding);
  28536. }
  28537. } else {
  28538. if (bindingName.indexOf(expression) != -1) {
  28539. matches.push(binding);
  28540. }
  28541. }
  28542. });
  28543. }
  28544. });
  28545. return matches;
  28546. };
  28547. /**
  28548. * @name $$testability#findModels
  28549. *
  28550. * @description
  28551. * Returns an array of elements that are two-way found via ng-model to
  28552. * expressions matching the input.
  28553. *
  28554. * @param {Element} element The element root to search from.
  28555. * @param {string} expression The model expression to match.
  28556. * @param {boolean} opt_exactMatch If true, only returns exact matches
  28557. * for the expression.
  28558. */
  28559. testability.findModels = function(element, expression, opt_exactMatch) {
  28560. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  28561. for (var p = 0; p < prefixes.length; ++p) {
  28562. var attributeEquals = opt_exactMatch ? '=' : '*=';
  28563. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  28564. var elements = element.querySelectorAll(selector);
  28565. if (elements.length) {
  28566. return elements;
  28567. }
  28568. }
  28569. };
  28570. /**
  28571. * @name $$testability#getLocation
  28572. *
  28573. * @description
  28574. * Shortcut for getting the location in a browser agnostic way. Returns
  28575. * the path, search, and hash. (e.g. /path?a=b#hash)
  28576. */
  28577. testability.getLocation = function() {
  28578. return $location.url();
  28579. };
  28580. /**
  28581. * @name $$testability#setLocation
  28582. *
  28583. * @description
  28584. * Shortcut for navigating to a location without doing a full page reload.
  28585. *
  28586. * @param {string} url The location url (path, search and hash,
  28587. * e.g. /path?a=b#hash) to go to.
  28588. */
  28589. testability.setLocation = function(url) {
  28590. if (url !== $location.url()) {
  28591. $location.url(url);
  28592. $rootScope.$digest();
  28593. }
  28594. };
  28595. /**
  28596. * @name $$testability#whenStable
  28597. *
  28598. * @description
  28599. * Calls the callback when $timeout and $http requests are completed.
  28600. *
  28601. * @param {function} callback
  28602. */
  28603. testability.whenStable = function(callback) {
  28604. $browser.notifyWhenNoOutstandingRequests(callback);
  28605. };
  28606. return testability;
  28607. }];
  28608. }
  28609. function $TimeoutProvider() {
  28610. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  28611. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  28612. var deferreds = {};
  28613. /**
  28614. * @ngdoc service
  28615. * @name $timeout
  28616. *
  28617. * @description
  28618. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  28619. * block and delegates any exceptions to
  28620. * {@link ng.$exceptionHandler $exceptionHandler} service.
  28621. *
  28622. * The return value of calling `$timeout` is a promise, which will be resolved when
  28623. * the delay has passed and the timeout function, if provided, is executed.
  28624. *
  28625. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  28626. *
  28627. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  28628. * synchronously flush the queue of deferred functions.
  28629. *
  28630. * If you only want a promise that will be resolved after some specified delay
  28631. * then you can call `$timeout` without the `fn` function.
  28632. *
  28633. * @param {function()=} fn A function, whose execution should be delayed.
  28634. * @param {number=} [delay=0] Delay in milliseconds.
  28635. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  28636. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  28637. * @param {...*=} Pass additional parameters to the executed function.
  28638. * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise
  28639. * will be resolved with the return value of the `fn` function.
  28640. *
  28641. */
  28642. function timeout(fn, delay, invokeApply) {
  28643. if (!isFunction(fn)) {
  28644. invokeApply = delay;
  28645. delay = fn;
  28646. fn = noop;
  28647. }
  28648. var args = sliceArgs(arguments, 3),
  28649. skipApply = (isDefined(invokeApply) && !invokeApply),
  28650. deferred = (skipApply ? $$q : $q).defer(),
  28651. promise = deferred.promise,
  28652. timeoutId;
  28653. timeoutId = $browser.defer(function() {
  28654. try {
  28655. deferred.resolve(fn.apply(null, args));
  28656. } catch (e) {
  28657. deferred.reject(e);
  28658. $exceptionHandler(e);
  28659. }
  28660. finally {
  28661. delete deferreds[promise.$$timeoutId];
  28662. }
  28663. if (!skipApply) $rootScope.$apply();
  28664. }, delay);
  28665. promise.$$timeoutId = timeoutId;
  28666. deferreds[timeoutId] = deferred;
  28667. return promise;
  28668. }
  28669. /**
  28670. * @ngdoc method
  28671. * @name $timeout#cancel
  28672. *
  28673. * @description
  28674. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  28675. * resolved with a rejection.
  28676. *
  28677. * @param {Promise=} promise Promise returned by the `$timeout` function.
  28678. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  28679. * canceled.
  28680. */
  28681. timeout.cancel = function(promise) {
  28682. if (promise && promise.$$timeoutId in deferreds) {
  28683. deferreds[promise.$$timeoutId].reject('canceled');
  28684. delete deferreds[promise.$$timeoutId];
  28685. return $browser.defer.cancel(promise.$$timeoutId);
  28686. }
  28687. return false;
  28688. };
  28689. return timeout;
  28690. }];
  28691. }
  28692. // NOTE: The usage of window and document instead of $window and $document here is
  28693. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  28694. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  28695. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  28696. // doesn't know about mocked locations and resolves URLs to the real document - which is
  28697. // exactly the behavior needed here. There is little value is mocking these out for this
  28698. // service.
  28699. var urlParsingNode = document.createElement("a");
  28700. var originUrl = urlResolve(window.location.href);
  28701. /**
  28702. *
  28703. * Implementation Notes for non-IE browsers
  28704. * ----------------------------------------
  28705. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  28706. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  28707. * URL will be resolved into an absolute URL in the context of the application document.
  28708. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  28709. * properties are all populated to reflect the normalized URL. This approach has wide
  28710. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  28711. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  28712. *
  28713. * Implementation Notes for IE
  28714. * ---------------------------
  28715. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  28716. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  28717. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  28718. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  28719. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  28720. * properties such as protocol, hostname, port, etc.
  28721. *
  28722. * References:
  28723. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  28724. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  28725. * http://url.spec.whatwg.org/#urlutils
  28726. * https://github.com/angular/angular.js/pull/2902
  28727. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  28728. *
  28729. * @kind function
  28730. * @param {string} url The URL to be parsed.
  28731. * @description Normalizes and parses a URL.
  28732. * @returns {object} Returns the normalized URL as a dictionary.
  28733. *
  28734. * | member name | Description |
  28735. * |---------------|----------------|
  28736. * | href | A normalized version of the provided URL if it was not an absolute URL |
  28737. * | protocol | The protocol including the trailing colon |
  28738. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  28739. * | search | The search params, minus the question mark |
  28740. * | hash | The hash string, minus the hash symbol
  28741. * | hostname | The hostname
  28742. * | port | The port, without ":"
  28743. * | pathname | The pathname, beginning with "/"
  28744. *
  28745. */
  28746. function urlResolve(url) {
  28747. var href = url;
  28748. if (msie) {
  28749. // Normalize before parse. Refer Implementation Notes on why this is
  28750. // done in two steps on IE.
  28751. urlParsingNode.setAttribute("href", href);
  28752. href = urlParsingNode.href;
  28753. }
  28754. urlParsingNode.setAttribute('href', href);
  28755. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  28756. return {
  28757. href: urlParsingNode.href,
  28758. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  28759. host: urlParsingNode.host,
  28760. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  28761. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  28762. hostname: urlParsingNode.hostname,
  28763. port: urlParsingNode.port,
  28764. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  28765. ? urlParsingNode.pathname
  28766. : '/' + urlParsingNode.pathname
  28767. };
  28768. }
  28769. /**
  28770. * Parse a request URL and determine whether this is a same-origin request as the application document.
  28771. *
  28772. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  28773. * or a parsed URL object.
  28774. * @returns {boolean} Whether the request is for the same origin as the application document.
  28775. */
  28776. function urlIsSameOrigin(requestUrl) {
  28777. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  28778. return (parsed.protocol === originUrl.protocol &&
  28779. parsed.host === originUrl.host);
  28780. }
  28781. /**
  28782. * @ngdoc service
  28783. * @name $window
  28784. *
  28785. * @description
  28786. * A reference to the browser's `window` object. While `window`
  28787. * is globally available in JavaScript, it causes testability problems, because
  28788. * it is a global variable. In angular we always refer to it through the
  28789. * `$window` service, so it may be overridden, removed or mocked for testing.
  28790. *
  28791. * Expressions, like the one defined for the `ngClick` directive in the example
  28792. * below, are evaluated with respect to the current scope. Therefore, there is
  28793. * no risk of inadvertently coding in a dependency on a global value in such an
  28794. * expression.
  28795. *
  28796. * @example
  28797. <example module="windowExample">
  28798. <file name="index.html">
  28799. <script>
  28800. angular.module('windowExample', [])
  28801. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  28802. $scope.greeting = 'Hello, World!';
  28803. $scope.doGreeting = function(greeting) {
  28804. $window.alert(greeting);
  28805. };
  28806. }]);
  28807. </script>
  28808. <div ng-controller="ExampleController">
  28809. <input type="text" ng-model="greeting" aria-label="greeting" />
  28810. <button ng-click="doGreeting(greeting)">ALERT</button>
  28811. </div>
  28812. </file>
  28813. <file name="protractor.js" type="protractor">
  28814. it('should display the greeting in the input box', function() {
  28815. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  28816. // If we click the button it will block the test runner
  28817. // element(':button').click();
  28818. });
  28819. </file>
  28820. </example>
  28821. */
  28822. function $WindowProvider() {
  28823. this.$get = valueFn(window);
  28824. }
  28825. /**
  28826. * @name $$cookieReader
  28827. * @requires $document
  28828. *
  28829. * @description
  28830. * This is a private service for reading cookies used by $http and ngCookies
  28831. *
  28832. * @return {Object} a key/value map of the current cookies
  28833. */
  28834. function $$CookieReader($document) {
  28835. var rawDocument = $document[0] || {};
  28836. var lastCookies = {};
  28837. var lastCookieString = '';
  28838. function safeDecodeURIComponent(str) {
  28839. try {
  28840. return decodeURIComponent(str);
  28841. } catch (e) {
  28842. return str;
  28843. }
  28844. }
  28845. return function() {
  28846. var cookieArray, cookie, i, index, name;
  28847. var currentCookieString = rawDocument.cookie || '';
  28848. if (currentCookieString !== lastCookieString) {
  28849. lastCookieString = currentCookieString;
  28850. cookieArray = lastCookieString.split('; ');
  28851. lastCookies = {};
  28852. for (i = 0; i < cookieArray.length; i++) {
  28853. cookie = cookieArray[i];
  28854. index = cookie.indexOf('=');
  28855. if (index > 0) { //ignore nameless cookies
  28856. name = safeDecodeURIComponent(cookie.substring(0, index));
  28857. // the first value that is seen for a cookie is the most
  28858. // specific one. values for the same cookie name that
  28859. // follow are for less specific paths.
  28860. if (isUndefined(lastCookies[name])) {
  28861. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  28862. }
  28863. }
  28864. }
  28865. }
  28866. return lastCookies;
  28867. };
  28868. }
  28869. $$CookieReader.$inject = ['$document'];
  28870. function $$CookieReaderProvider() {
  28871. this.$get = $$CookieReader;
  28872. }
  28873. /* global currencyFilter: true,
  28874. dateFilter: true,
  28875. filterFilter: true,
  28876. jsonFilter: true,
  28877. limitToFilter: true,
  28878. lowercaseFilter: true,
  28879. numberFilter: true,
  28880. orderByFilter: true,
  28881. uppercaseFilter: true,
  28882. */
  28883. /**
  28884. * @ngdoc provider
  28885. * @name $filterProvider
  28886. * @description
  28887. *
  28888. * Filters are just functions which transform input to an output. However filters need to be
  28889. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  28890. * annotated with dependencies and is responsible for creating a filter function.
  28891. *
  28892. * <div class="alert alert-warning">
  28893. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  28894. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  28895. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  28896. * (`myapp_subsection_filterx`).
  28897. * </div>
  28898. *
  28899. * ```js
  28900. * // Filter registration
  28901. * function MyModule($provide, $filterProvider) {
  28902. * // create a service to demonstrate injection (not always needed)
  28903. * $provide.value('greet', function(name){
  28904. * return 'Hello ' + name + '!';
  28905. * });
  28906. *
  28907. * // register a filter factory which uses the
  28908. * // greet service to demonstrate DI.
  28909. * $filterProvider.register('greet', function(greet){
  28910. * // return the filter function which uses the greet service
  28911. * // to generate salutation
  28912. * return function(text) {
  28913. * // filters need to be forgiving so check input validity
  28914. * return text && greet(text) || text;
  28915. * };
  28916. * });
  28917. * }
  28918. * ```
  28919. *
  28920. * The filter function is registered with the `$injector` under the filter name suffix with
  28921. * `Filter`.
  28922. *
  28923. * ```js
  28924. * it('should be the same instance', inject(
  28925. * function($filterProvider) {
  28926. * $filterProvider.register('reverse', function(){
  28927. * return ...;
  28928. * });
  28929. * },
  28930. * function($filter, reverseFilter) {
  28931. * expect($filter('reverse')).toBe(reverseFilter);
  28932. * });
  28933. * ```
  28934. *
  28935. *
  28936. * For more information about how angular filters work, and how to create your own filters, see
  28937. * {@link guide/filter Filters} in the Angular Developer Guide.
  28938. */
  28939. /**
  28940. * @ngdoc service
  28941. * @name $filter
  28942. * @kind function
  28943. * @description
  28944. * Filters are used for formatting data displayed to the user.
  28945. *
  28946. * The general syntax in templates is as follows:
  28947. *
  28948. * {{ expression [| filter_name[:parameter_value] ... ] }}
  28949. *
  28950. * @param {String} name Name of the filter function to retrieve
  28951. * @return {Function} the filter function
  28952. * @example
  28953. <example name="$filter" module="filterExample">
  28954. <file name="index.html">
  28955. <div ng-controller="MainCtrl">
  28956. <h3>{{ originalText }}</h3>
  28957. <h3>{{ filteredText }}</h3>
  28958. </div>
  28959. </file>
  28960. <file name="script.js">
  28961. angular.module('filterExample', [])
  28962. .controller('MainCtrl', function($scope, $filter) {
  28963. $scope.originalText = 'hello';
  28964. $scope.filteredText = $filter('uppercase')($scope.originalText);
  28965. });
  28966. </file>
  28967. </example>
  28968. */
  28969. $FilterProvider.$inject = ['$provide'];
  28970. function $FilterProvider($provide) {
  28971. var suffix = 'Filter';
  28972. /**
  28973. * @ngdoc method
  28974. * @name $filterProvider#register
  28975. * @param {string|Object} name Name of the filter function, or an object map of filters where
  28976. * the keys are the filter names and the values are the filter factories.
  28977. *
  28978. * <div class="alert alert-warning">
  28979. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  28980. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  28981. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  28982. * (`myapp_subsection_filterx`).
  28983. * </div>
  28984. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  28985. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  28986. * of the registered filter instances.
  28987. */
  28988. function register(name, factory) {
  28989. if (isObject(name)) {
  28990. var filters = {};
  28991. forEach(name, function(filter, key) {
  28992. filters[key] = register(key, filter);
  28993. });
  28994. return filters;
  28995. } else {
  28996. return $provide.factory(name + suffix, factory);
  28997. }
  28998. }
  28999. this.register = register;
  29000. this.$get = ['$injector', function($injector) {
  29001. return function(name) {
  29002. return $injector.get(name + suffix);
  29003. };
  29004. }];
  29005. ////////////////////////////////////////
  29006. /* global
  29007. currencyFilter: false,
  29008. dateFilter: false,
  29009. filterFilter: false,
  29010. jsonFilter: false,
  29011. limitToFilter: false,
  29012. lowercaseFilter: false,
  29013. numberFilter: false,
  29014. orderByFilter: false,
  29015. uppercaseFilter: false,
  29016. */
  29017. register('currency', currencyFilter);
  29018. register('date', dateFilter);
  29019. register('filter', filterFilter);
  29020. register('json', jsonFilter);
  29021. register('limitTo', limitToFilter);
  29022. register('lowercase', lowercaseFilter);
  29023. register('number', numberFilter);
  29024. register('orderBy', orderByFilter);
  29025. register('uppercase', uppercaseFilter);
  29026. }
  29027. /**
  29028. * @ngdoc filter
  29029. * @name filter
  29030. * @kind function
  29031. *
  29032. * @description
  29033. * Selects a subset of items from `array` and returns it as a new array.
  29034. *
  29035. * @param {Array} array The source array.
  29036. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  29037. * `array`.
  29038. *
  29039. * Can be one of:
  29040. *
  29041. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  29042. * objects with string properties in `array` that match this string will be returned. This also
  29043. * applies to nested object properties.
  29044. * The predicate can be negated by prefixing the string with `!`.
  29045. *
  29046. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  29047. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  29048. * which have property `name` containing "M" and property `phone` containing "1". A special
  29049. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  29050. * property of the object or its nested object properties. That's equivalent to the simple
  29051. * substring match with a `string` as described above. The predicate can be negated by prefixing
  29052. * the string with `!`.
  29053. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  29054. * not containing "M".
  29055. *
  29056. * Note that a named property will match properties on the same level only, while the special
  29057. * `$` property will match properties on the same level or deeper. E.g. an array item like
  29058. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  29059. * **will** be matched by `{$: 'John'}`.
  29060. *
  29061. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  29062. * The function is called for each element of the array, with the element, its index, and
  29063. * the entire array itself as arguments.
  29064. *
  29065. * The final result is an array of those elements that the predicate returned true for.
  29066. *
  29067. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  29068. * determining if the expected value (from the filter expression) and actual value (from
  29069. * the object in the array) should be considered a match.
  29070. *
  29071. * Can be one of:
  29072. *
  29073. * - `function(actual, expected)`:
  29074. * The function will be given the object value and the predicate value to compare and
  29075. * should return true if both values should be considered equal.
  29076. *
  29077. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  29078. * This is essentially strict comparison of expected and actual.
  29079. *
  29080. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  29081. * insensitive way.
  29082. *
  29083. * Primitive values are converted to strings. Objects are not compared against primitives,
  29084. * unless they have a custom `toString` method (e.g. `Date` objects).
  29085. *
  29086. * @example
  29087. <example>
  29088. <file name="index.html">
  29089. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  29090. {name:'Mary', phone:'800-BIG-MARY'},
  29091. {name:'Mike', phone:'555-4321'},
  29092. {name:'Adam', phone:'555-5678'},
  29093. {name:'Julie', phone:'555-8765'},
  29094. {name:'Juliette', phone:'555-5678'}]"></div>
  29095. <label>Search: <input ng-model="searchText"></label>
  29096. <table id="searchTextResults">
  29097. <tr><th>Name</th><th>Phone</th></tr>
  29098. <tr ng-repeat="friend in friends | filter:searchText">
  29099. <td>{{friend.name}}</td>
  29100. <td>{{friend.phone}}</td>
  29101. </tr>
  29102. </table>
  29103. <hr>
  29104. <label>Any: <input ng-model="search.$"></label> <br>
  29105. <label>Name only <input ng-model="search.name"></label><br>
  29106. <label>Phone only <input ng-model="search.phone"></label><br>
  29107. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  29108. <table id="searchObjResults">
  29109. <tr><th>Name</th><th>Phone</th></tr>
  29110. <tr ng-repeat="friendObj in friends | filter:search:strict">
  29111. <td>{{friendObj.name}}</td>
  29112. <td>{{friendObj.phone}}</td>
  29113. </tr>
  29114. </table>
  29115. </file>
  29116. <file name="protractor.js" type="protractor">
  29117. var expectFriendNames = function(expectedNames, key) {
  29118. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  29119. arr.forEach(function(wd, i) {
  29120. expect(wd.getText()).toMatch(expectedNames[i]);
  29121. });
  29122. });
  29123. };
  29124. it('should search across all fields when filtering with a string', function() {
  29125. var searchText = element(by.model('searchText'));
  29126. searchText.clear();
  29127. searchText.sendKeys('m');
  29128. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  29129. searchText.clear();
  29130. searchText.sendKeys('76');
  29131. expectFriendNames(['John', 'Julie'], 'friend');
  29132. });
  29133. it('should search in specific fields when filtering with a predicate object', function() {
  29134. var searchAny = element(by.model('search.$'));
  29135. searchAny.clear();
  29136. searchAny.sendKeys('i');
  29137. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  29138. });
  29139. it('should use a equal comparison when comparator is true', function() {
  29140. var searchName = element(by.model('search.name'));
  29141. var strict = element(by.model('strict'));
  29142. searchName.clear();
  29143. searchName.sendKeys('Julie');
  29144. strict.click();
  29145. expectFriendNames(['Julie'], 'friendObj');
  29146. });
  29147. </file>
  29148. </example>
  29149. */
  29150. function filterFilter() {
  29151. return function(array, expression, comparator) {
  29152. if (!isArrayLike(array)) {
  29153. if (array == null) {
  29154. return array;
  29155. } else {
  29156. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  29157. }
  29158. }
  29159. var expressionType = getTypeForFilter(expression);
  29160. var predicateFn;
  29161. var matchAgainstAnyProp;
  29162. switch (expressionType) {
  29163. case 'function':
  29164. predicateFn = expression;
  29165. break;
  29166. case 'boolean':
  29167. case 'null':
  29168. case 'number':
  29169. case 'string':
  29170. matchAgainstAnyProp = true;
  29171. //jshint -W086
  29172. case 'object':
  29173. //jshint +W086
  29174. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  29175. break;
  29176. default:
  29177. return array;
  29178. }
  29179. return Array.prototype.filter.call(array, predicateFn);
  29180. };
  29181. }
  29182. // Helper functions for `filterFilter`
  29183. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  29184. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  29185. var predicateFn;
  29186. if (comparator === true) {
  29187. comparator = equals;
  29188. } else if (!isFunction(comparator)) {
  29189. comparator = function(actual, expected) {
  29190. if (isUndefined(actual)) {
  29191. // No substring matching against `undefined`
  29192. return false;
  29193. }
  29194. if ((actual === null) || (expected === null)) {
  29195. // No substring matching against `null`; only match against `null`
  29196. return actual === expected;
  29197. }
  29198. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  29199. // Should not compare primitives against objects, unless they have custom `toString` method
  29200. return false;
  29201. }
  29202. actual = lowercase('' + actual);
  29203. expected = lowercase('' + expected);
  29204. return actual.indexOf(expected) !== -1;
  29205. };
  29206. }
  29207. predicateFn = function(item) {
  29208. if (shouldMatchPrimitives && !isObject(item)) {
  29209. return deepCompare(item, expression.$, comparator, false);
  29210. }
  29211. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  29212. };
  29213. return predicateFn;
  29214. }
  29215. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  29216. var actualType = getTypeForFilter(actual);
  29217. var expectedType = getTypeForFilter(expected);
  29218. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  29219. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  29220. } else if (isArray(actual)) {
  29221. // In case `actual` is an array, consider it a match
  29222. // if ANY of it's items matches `expected`
  29223. return actual.some(function(item) {
  29224. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  29225. });
  29226. }
  29227. switch (actualType) {
  29228. case 'object':
  29229. var key;
  29230. if (matchAgainstAnyProp) {
  29231. for (key in actual) {
  29232. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  29233. return true;
  29234. }
  29235. }
  29236. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  29237. } else if (expectedType === 'object') {
  29238. for (key in expected) {
  29239. var expectedVal = expected[key];
  29240. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  29241. continue;
  29242. }
  29243. var matchAnyProperty = key === '$';
  29244. var actualVal = matchAnyProperty ? actual : actual[key];
  29245. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  29246. return false;
  29247. }
  29248. }
  29249. return true;
  29250. } else {
  29251. return comparator(actual, expected);
  29252. }
  29253. break;
  29254. case 'function':
  29255. return false;
  29256. default:
  29257. return comparator(actual, expected);
  29258. }
  29259. }
  29260. // Used for easily differentiating between `null` and actual `object`
  29261. function getTypeForFilter(val) {
  29262. return (val === null) ? 'null' : typeof val;
  29263. }
  29264. var MAX_DIGITS = 22;
  29265. var DECIMAL_SEP = '.';
  29266. var ZERO_CHAR = '0';
  29267. /**
  29268. * @ngdoc filter
  29269. * @name currency
  29270. * @kind function
  29271. *
  29272. * @description
  29273. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  29274. * symbol for current locale is used.
  29275. *
  29276. * @param {number} amount Input to filter.
  29277. * @param {string=} symbol Currency symbol or identifier to be displayed.
  29278. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  29279. * @returns {string} Formatted number.
  29280. *
  29281. *
  29282. * @example
  29283. <example module="currencyExample">
  29284. <file name="index.html">
  29285. <script>
  29286. angular.module('currencyExample', [])
  29287. .controller('ExampleController', ['$scope', function($scope) {
  29288. $scope.amount = 1234.56;
  29289. }]);
  29290. </script>
  29291. <div ng-controller="ExampleController">
  29292. <input type="number" ng-model="amount" aria-label="amount"> <br>
  29293. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  29294. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  29295. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  29296. </div>
  29297. </file>
  29298. <file name="protractor.js" type="protractor">
  29299. it('should init with 1234.56', function() {
  29300. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  29301. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  29302. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  29303. });
  29304. it('should update', function() {
  29305. if (browser.params.browser == 'safari') {
  29306. // Safari does not understand the minus key. See
  29307. // https://github.com/angular/protractor/issues/481
  29308. return;
  29309. }
  29310. element(by.model('amount')).clear();
  29311. element(by.model('amount')).sendKeys('-1234');
  29312. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  29313. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  29314. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  29315. });
  29316. </file>
  29317. </example>
  29318. */
  29319. currencyFilter.$inject = ['$locale'];
  29320. function currencyFilter($locale) {
  29321. var formats = $locale.NUMBER_FORMATS;
  29322. return function(amount, currencySymbol, fractionSize) {
  29323. if (isUndefined(currencySymbol)) {
  29324. currencySymbol = formats.CURRENCY_SYM;
  29325. }
  29326. if (isUndefined(fractionSize)) {
  29327. fractionSize = formats.PATTERNS[1].maxFrac;
  29328. }
  29329. // if null or undefined pass it through
  29330. return (amount == null)
  29331. ? amount
  29332. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  29333. replace(/\u00A4/g, currencySymbol);
  29334. };
  29335. }
  29336. /**
  29337. * @ngdoc filter
  29338. * @name number
  29339. * @kind function
  29340. *
  29341. * @description
  29342. * Formats a number as text.
  29343. *
  29344. * If the input is null or undefined, it will just be returned.
  29345. * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively.
  29346. * If the input is not a number an empty string is returned.
  29347. *
  29348. *
  29349. * @param {number|string} number Number to format.
  29350. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  29351. * If this is not provided then the fraction size is computed from the current locale's number
  29352. * formatting pattern. In the case of the default locale, it will be 3.
  29353. * @returns {string} Number rounded to fractionSize and places a “,” after each third digit.
  29354. *
  29355. * @example
  29356. <example module="numberFilterExample">
  29357. <file name="index.html">
  29358. <script>
  29359. angular.module('numberFilterExample', [])
  29360. .controller('ExampleController', ['$scope', function($scope) {
  29361. $scope.val = 1234.56789;
  29362. }]);
  29363. </script>
  29364. <div ng-controller="ExampleController">
  29365. <label>Enter number: <input ng-model='val'></label><br>
  29366. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  29367. No fractions: <span>{{val | number:0}}</span><br>
  29368. Negative number: <span>{{-val | number:4}}</span>
  29369. </div>
  29370. </file>
  29371. <file name="protractor.js" type="protractor">
  29372. it('should format numbers', function() {
  29373. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  29374. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  29375. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  29376. });
  29377. it('should update', function() {
  29378. element(by.model('val')).clear();
  29379. element(by.model('val')).sendKeys('3374.333');
  29380. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  29381. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  29382. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  29383. });
  29384. </file>
  29385. </example>
  29386. */
  29387. numberFilter.$inject = ['$locale'];
  29388. function numberFilter($locale) {
  29389. var formats = $locale.NUMBER_FORMATS;
  29390. return function(number, fractionSize) {
  29391. // if null or undefined pass it through
  29392. return (number == null)
  29393. ? number
  29394. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  29395. fractionSize);
  29396. };
  29397. }
  29398. /**
  29399. * Parse a number (as a string) into three components that can be used
  29400. * for formatting the number.
  29401. *
  29402. * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/)
  29403. *
  29404. * @param {string} numStr The number to parse
  29405. * @return {object} An object describing this number, containing the following keys:
  29406. * - d : an array of digits containing leading zeros as necessary
  29407. * - i : the number of the digits in `d` that are to the left of the decimal point
  29408. * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d`
  29409. *
  29410. */
  29411. function parse(numStr) {
  29412. var exponent = 0, digits, numberOfIntegerDigits;
  29413. var i, j, zeros;
  29414. // Decimal point?
  29415. if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) {
  29416. numStr = numStr.replace(DECIMAL_SEP, '');
  29417. }
  29418. // Exponential form?
  29419. if ((i = numStr.search(/e/i)) > 0) {
  29420. // Work out the exponent.
  29421. if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i;
  29422. numberOfIntegerDigits += +numStr.slice(i + 1);
  29423. numStr = numStr.substring(0, i);
  29424. } else if (numberOfIntegerDigits < 0) {
  29425. // There was no decimal point or exponent so it is an integer.
  29426. numberOfIntegerDigits = numStr.length;
  29427. }
  29428. // Count the number of leading zeros.
  29429. for (i = 0; numStr.charAt(i) == ZERO_CHAR; i++) {/* jshint noempty: false */}
  29430. if (i == (zeros = numStr.length)) {
  29431. // The digits are all zero.
  29432. digits = [0];
  29433. numberOfIntegerDigits = 1;
  29434. } else {
  29435. // Count the number of trailing zeros
  29436. zeros--;
  29437. while (numStr.charAt(zeros) == ZERO_CHAR) zeros--;
  29438. // Trailing zeros are insignificant so ignore them
  29439. numberOfIntegerDigits -= i;
  29440. digits = [];
  29441. // Convert string to array of digits without leading/trailing zeros.
  29442. for (j = 0; i <= zeros; i++, j++) {
  29443. digits[j] = +numStr.charAt(i);
  29444. }
  29445. }
  29446. // If the number overflows the maximum allowed digits then use an exponent.
  29447. if (numberOfIntegerDigits > MAX_DIGITS) {
  29448. digits = digits.splice(0, MAX_DIGITS - 1);
  29449. exponent = numberOfIntegerDigits - 1;
  29450. numberOfIntegerDigits = 1;
  29451. }
  29452. return { d: digits, e: exponent, i: numberOfIntegerDigits };
  29453. }
  29454. /**
  29455. * Round the parsed number to the specified number of decimal places
  29456. * This function changed the parsedNumber in-place
  29457. */
  29458. function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) {
  29459. var digits = parsedNumber.d;
  29460. var fractionLen = digits.length - parsedNumber.i;
  29461. // determine fractionSize if it is not specified; `+fractionSize` converts it to a number
  29462. fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize;
  29463. // The index of the digit to where rounding is to occur
  29464. var roundAt = fractionSize + parsedNumber.i;
  29465. var digit = digits[roundAt];
  29466. if (roundAt > 0) {
  29467. // Drop fractional digits beyond `roundAt`
  29468. digits.splice(Math.max(parsedNumber.i, roundAt));
  29469. // Set non-fractional digits beyond `roundAt` to 0
  29470. for (var j = roundAt; j < digits.length; j++) {
  29471. digits[j] = 0;
  29472. }
  29473. } else {
  29474. // We rounded to zero so reset the parsedNumber
  29475. fractionLen = Math.max(0, fractionLen);
  29476. parsedNumber.i = 1;
  29477. digits.length = Math.max(1, roundAt = fractionSize + 1);
  29478. digits[0] = 0;
  29479. for (var i = 1; i < roundAt; i++) digits[i] = 0;
  29480. }
  29481. if (digit >= 5) {
  29482. if (roundAt - 1 < 0) {
  29483. for (var k = 0; k > roundAt; k--) {
  29484. digits.unshift(0);
  29485. parsedNumber.i++;
  29486. }
  29487. digits.unshift(1);
  29488. parsedNumber.i++;
  29489. } else {
  29490. digits[roundAt - 1]++;
  29491. }
  29492. }
  29493. // Pad out with zeros to get the required fraction length
  29494. for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0);
  29495. // Do any carrying, e.g. a digit was rounded up to 10
  29496. var carry = digits.reduceRight(function(carry, d, i, digits) {
  29497. d = d + carry;
  29498. digits[i] = d % 10;
  29499. return Math.floor(d / 10);
  29500. }, 0);
  29501. if (carry) {
  29502. digits.unshift(carry);
  29503. parsedNumber.i++;
  29504. }
  29505. }
  29506. /**
  29507. * Format a number into a string
  29508. * @param {number} number The number to format
  29509. * @param {{
  29510. * minFrac, // the minimum number of digits required in the fraction part of the number
  29511. * maxFrac, // the maximum number of digits required in the fraction part of the number
  29512. * gSize, // number of digits in each group of separated digits
  29513. * lgSize, // number of digits in the last group of digits before the decimal separator
  29514. * negPre, // the string to go in front of a negative number (e.g. `-` or `(`))
  29515. * posPre, // the string to go in front of a positive number
  29516. * negSuf, // the string to go after a negative number (e.g. `)`)
  29517. * posSuf // the string to go after a positive number
  29518. * }} pattern
  29519. * @param {string} groupSep The string to separate groups of number (e.g. `,`)
  29520. * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`)
  29521. * @param {[type]} fractionSize The size of the fractional part of the number
  29522. * @return {string} The number formatted as a string
  29523. */
  29524. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  29525. if (!(isString(number) || isNumber(number)) || isNaN(number)) return '';
  29526. var isInfinity = !isFinite(number);
  29527. var isZero = false;
  29528. var numStr = Math.abs(number) + '',
  29529. formattedText = '',
  29530. parsedNumber;
  29531. if (isInfinity) {
  29532. formattedText = '\u221e';
  29533. } else {
  29534. parsedNumber = parse(numStr);
  29535. roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac);
  29536. var digits = parsedNumber.d;
  29537. var integerLen = parsedNumber.i;
  29538. var exponent = parsedNumber.e;
  29539. var decimals = [];
  29540. isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true);
  29541. // pad zeros for small numbers
  29542. while (integerLen < 0) {
  29543. digits.unshift(0);
  29544. integerLen++;
  29545. }
  29546. // extract decimals digits
  29547. if (integerLen > 0) {
  29548. decimals = digits.splice(integerLen);
  29549. } else {
  29550. decimals = digits;
  29551. digits = [0];
  29552. }
  29553. // format the integer digits with grouping separators
  29554. var groups = [];
  29555. if (digits.length >= pattern.lgSize) {
  29556. groups.unshift(digits.splice(-pattern.lgSize).join(''));
  29557. }
  29558. while (digits.length > pattern.gSize) {
  29559. groups.unshift(digits.splice(-pattern.gSize).join(''));
  29560. }
  29561. if (digits.length) {
  29562. groups.unshift(digits.join(''));
  29563. }
  29564. formattedText = groups.join(groupSep);
  29565. // append the decimal digits
  29566. if (decimals.length) {
  29567. formattedText += decimalSep + decimals.join('');
  29568. }
  29569. if (exponent) {
  29570. formattedText += 'e+' + exponent;
  29571. }
  29572. }
  29573. if (number < 0 && !isZero) {
  29574. return pattern.negPre + formattedText + pattern.negSuf;
  29575. } else {
  29576. return pattern.posPre + formattedText + pattern.posSuf;
  29577. }
  29578. }
  29579. function padNumber(num, digits, trim, negWrap) {
  29580. var neg = '';
  29581. if (num < 0 || (negWrap && num <= 0)) {
  29582. if (negWrap) {
  29583. num = -num + 1;
  29584. } else {
  29585. num = -num;
  29586. neg = '-';
  29587. }
  29588. }
  29589. num = '' + num;
  29590. while (num.length < digits) num = ZERO_CHAR + num;
  29591. if (trim) {
  29592. num = num.substr(num.length - digits);
  29593. }
  29594. return neg + num;
  29595. }
  29596. function dateGetter(name, size, offset, trim, negWrap) {
  29597. offset = offset || 0;
  29598. return function(date) {
  29599. var value = date['get' + name]();
  29600. if (offset > 0 || value > -offset) {
  29601. value += offset;
  29602. }
  29603. if (value === 0 && offset == -12) value = 12;
  29604. return padNumber(value, size, trim, negWrap);
  29605. };
  29606. }
  29607. function dateStrGetter(name, shortForm, standAlone) {
  29608. return function(date, formats) {
  29609. var value = date['get' + name]();
  29610. var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : '');
  29611. var get = uppercase(propPrefix + name);
  29612. return formats[get][value];
  29613. };
  29614. }
  29615. function timeZoneGetter(date, formats, offset) {
  29616. var zone = -1 * offset;
  29617. var paddedZone = (zone >= 0) ? "+" : "";
  29618. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  29619. padNumber(Math.abs(zone % 60), 2);
  29620. return paddedZone;
  29621. }
  29622. function getFirstThursdayOfYear(year) {
  29623. // 0 = index of January
  29624. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  29625. // 4 = index of Thursday (+1 to account for 1st = 5)
  29626. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  29627. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  29628. }
  29629. function getThursdayThisWeek(datetime) {
  29630. return new Date(datetime.getFullYear(), datetime.getMonth(),
  29631. // 4 = index of Thursday
  29632. datetime.getDate() + (4 - datetime.getDay()));
  29633. }
  29634. function weekGetter(size) {
  29635. return function(date) {
  29636. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  29637. thisThurs = getThursdayThisWeek(date);
  29638. var diff = +thisThurs - +firstThurs,
  29639. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  29640. return padNumber(result, size);
  29641. };
  29642. }
  29643. function ampmGetter(date, formats) {
  29644. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  29645. }
  29646. function eraGetter(date, formats) {
  29647. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  29648. }
  29649. function longEraGetter(date, formats) {
  29650. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  29651. }
  29652. var DATE_FORMATS = {
  29653. yyyy: dateGetter('FullYear', 4, 0, false, true),
  29654. yy: dateGetter('FullYear', 2, 0, true, true),
  29655. y: dateGetter('FullYear', 1, 0, false, true),
  29656. MMMM: dateStrGetter('Month'),
  29657. MMM: dateStrGetter('Month', true),
  29658. MM: dateGetter('Month', 2, 1),
  29659. M: dateGetter('Month', 1, 1),
  29660. LLLL: dateStrGetter('Month', false, true),
  29661. dd: dateGetter('Date', 2),
  29662. d: dateGetter('Date', 1),
  29663. HH: dateGetter('Hours', 2),
  29664. H: dateGetter('Hours', 1),
  29665. hh: dateGetter('Hours', 2, -12),
  29666. h: dateGetter('Hours', 1, -12),
  29667. mm: dateGetter('Minutes', 2),
  29668. m: dateGetter('Minutes', 1),
  29669. ss: dateGetter('Seconds', 2),
  29670. s: dateGetter('Seconds', 1),
  29671. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  29672. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  29673. sss: dateGetter('Milliseconds', 3),
  29674. EEEE: dateStrGetter('Day'),
  29675. EEE: dateStrGetter('Day', true),
  29676. a: ampmGetter,
  29677. Z: timeZoneGetter,
  29678. ww: weekGetter(2),
  29679. w: weekGetter(1),
  29680. G: eraGetter,
  29681. GG: eraGetter,
  29682. GGG: eraGetter,
  29683. GGGG: longEraGetter
  29684. };
  29685. var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  29686. NUMBER_STRING = /^\-?\d+$/;
  29687. /**
  29688. * @ngdoc filter
  29689. * @name date
  29690. * @kind function
  29691. *
  29692. * @description
  29693. * Formats `date` to a string based on the requested `format`.
  29694. *
  29695. * `format` string can be composed of the following elements:
  29696. *
  29697. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  29698. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  29699. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  29700. * * `'MMMM'`: Month in year (January-December)
  29701. * * `'MMM'`: Month in year (Jan-Dec)
  29702. * * `'MM'`: Month in year, padded (01-12)
  29703. * * `'M'`: Month in year (1-12)
  29704. * * `'LLLL'`: Stand-alone month in year (January-December)
  29705. * * `'dd'`: Day in month, padded (01-31)
  29706. * * `'d'`: Day in month (1-31)
  29707. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  29708. * * `'EEE'`: Day in Week, (Sun-Sat)
  29709. * * `'HH'`: Hour in day, padded (00-23)
  29710. * * `'H'`: Hour in day (0-23)
  29711. * * `'hh'`: Hour in AM/PM, padded (01-12)
  29712. * * `'h'`: Hour in AM/PM, (1-12)
  29713. * * `'mm'`: Minute in hour, padded (00-59)
  29714. * * `'m'`: Minute in hour (0-59)
  29715. * * `'ss'`: Second in minute, padded (00-59)
  29716. * * `'s'`: Second in minute (0-59)
  29717. * * `'sss'`: Millisecond in second, padded (000-999)
  29718. * * `'a'`: AM/PM marker
  29719. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  29720. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  29721. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  29722. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  29723. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  29724. *
  29725. * `format` string can also be one of the following predefined
  29726. * {@link guide/i18n localizable formats}:
  29727. *
  29728. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  29729. * (e.g. Sep 3, 2010 12:05:08 PM)
  29730. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  29731. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  29732. * (e.g. Friday, September 3, 2010)
  29733. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  29734. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  29735. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  29736. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  29737. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  29738. *
  29739. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  29740. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  29741. * (e.g. `"h 'o''clock'"`).
  29742. *
  29743. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  29744. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  29745. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  29746. * specified in the string input, the time is considered to be in the local timezone.
  29747. * @param {string=} format Formatting rules (see Description). If not specified,
  29748. * `mediumDate` is used.
  29749. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  29750. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  29751. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  29752. * If not specified, the timezone of the browser will be used.
  29753. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  29754. *
  29755. * @example
  29756. <example>
  29757. <file name="index.html">
  29758. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  29759. <span>{{1288323623006 | date:'medium'}}</span><br>
  29760. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  29761. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  29762. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  29763. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  29764. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  29765. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  29766. </file>
  29767. <file name="protractor.js" type="protractor">
  29768. it('should format date', function() {
  29769. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  29770. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  29771. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  29772. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  29773. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  29774. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  29775. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  29776. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  29777. });
  29778. </file>
  29779. </example>
  29780. */
  29781. dateFilter.$inject = ['$locale'];
  29782. function dateFilter($locale) {
  29783. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  29784. // 1 2 3 4 5 6 7 8 9 10 11
  29785. function jsonStringToDate(string) {
  29786. var match;
  29787. if (match = string.match(R_ISO8601_STR)) {
  29788. var date = new Date(0),
  29789. tzHour = 0,
  29790. tzMin = 0,
  29791. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  29792. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  29793. if (match[9]) {
  29794. tzHour = toInt(match[9] + match[10]);
  29795. tzMin = toInt(match[9] + match[11]);
  29796. }
  29797. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  29798. var h = toInt(match[4] || 0) - tzHour;
  29799. var m = toInt(match[5] || 0) - tzMin;
  29800. var s = toInt(match[6] || 0);
  29801. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  29802. timeSetter.call(date, h, m, s, ms);
  29803. return date;
  29804. }
  29805. return string;
  29806. }
  29807. return function(date, format, timezone) {
  29808. var text = '',
  29809. parts = [],
  29810. fn, match;
  29811. format = format || 'mediumDate';
  29812. format = $locale.DATETIME_FORMATS[format] || format;
  29813. if (isString(date)) {
  29814. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  29815. }
  29816. if (isNumber(date)) {
  29817. date = new Date(date);
  29818. }
  29819. if (!isDate(date) || !isFinite(date.getTime())) {
  29820. return date;
  29821. }
  29822. while (format) {
  29823. match = DATE_FORMATS_SPLIT.exec(format);
  29824. if (match) {
  29825. parts = concat(parts, match, 1);
  29826. format = parts.pop();
  29827. } else {
  29828. parts.push(format);
  29829. format = null;
  29830. }
  29831. }
  29832. var dateTimezoneOffset = date.getTimezoneOffset();
  29833. if (timezone) {
  29834. dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset);
  29835. date = convertTimezoneToLocal(date, timezone, true);
  29836. }
  29837. forEach(parts, function(value) {
  29838. fn = DATE_FORMATS[value];
  29839. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  29840. : value === "''" ? "'" : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  29841. });
  29842. return text;
  29843. };
  29844. }
  29845. /**
  29846. * @ngdoc filter
  29847. * @name json
  29848. * @kind function
  29849. *
  29850. * @description
  29851. * Allows you to convert a JavaScript object into JSON string.
  29852. *
  29853. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  29854. * the binding is automatically converted to JSON.
  29855. *
  29856. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  29857. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  29858. * @returns {string} JSON string.
  29859. *
  29860. *
  29861. * @example
  29862. <example>
  29863. <file name="index.html">
  29864. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  29865. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  29866. </file>
  29867. <file name="protractor.js" type="protractor">
  29868. it('should jsonify filtered objects', function() {
  29869. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  29870. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  29871. });
  29872. </file>
  29873. </example>
  29874. *
  29875. */
  29876. function jsonFilter() {
  29877. return function(object, spacing) {
  29878. if (isUndefined(spacing)) {
  29879. spacing = 2;
  29880. }
  29881. return toJson(object, spacing);
  29882. };
  29883. }
  29884. /**
  29885. * @ngdoc filter
  29886. * @name lowercase
  29887. * @kind function
  29888. * @description
  29889. * Converts string to lowercase.
  29890. * @see angular.lowercase
  29891. */
  29892. var lowercaseFilter = valueFn(lowercase);
  29893. /**
  29894. * @ngdoc filter
  29895. * @name uppercase
  29896. * @kind function
  29897. * @description
  29898. * Converts string to uppercase.
  29899. * @see angular.uppercase
  29900. */
  29901. var uppercaseFilter = valueFn(uppercase);
  29902. /**
  29903. * @ngdoc filter
  29904. * @name limitTo
  29905. * @kind function
  29906. *
  29907. * @description
  29908. * Creates a new array or string containing only a specified number of elements. The elements
  29909. * are taken from either the beginning or the end of the source array, string or number, as specified by
  29910. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  29911. * converted to a string.
  29912. *
  29913. * @param {Array|string|number} input Source array, string or number to be limited.
  29914. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  29915. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  29916. * If the number is negative, `limit` number of items from the end of the source array/string
  29917. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  29918. * the input will be returned unchanged.
  29919. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  29920. * indicates an offset from the end of `input`. Defaults to `0`.
  29921. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  29922. * had less than `limit` elements.
  29923. *
  29924. * @example
  29925. <example module="limitToExample">
  29926. <file name="index.html">
  29927. <script>
  29928. angular.module('limitToExample', [])
  29929. .controller('ExampleController', ['$scope', function($scope) {
  29930. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  29931. $scope.letters = "abcdefghi";
  29932. $scope.longNumber = 2345432342;
  29933. $scope.numLimit = 3;
  29934. $scope.letterLimit = 3;
  29935. $scope.longNumberLimit = 3;
  29936. }]);
  29937. </script>
  29938. <div ng-controller="ExampleController">
  29939. <label>
  29940. Limit {{numbers}} to:
  29941. <input type="number" step="1" ng-model="numLimit">
  29942. </label>
  29943. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  29944. <label>
  29945. Limit {{letters}} to:
  29946. <input type="number" step="1" ng-model="letterLimit">
  29947. </label>
  29948. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  29949. <label>
  29950. Limit {{longNumber}} to:
  29951. <input type="number" step="1" ng-model="longNumberLimit">
  29952. </label>
  29953. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  29954. </div>
  29955. </file>
  29956. <file name="protractor.js" type="protractor">
  29957. var numLimitInput = element(by.model('numLimit'));
  29958. var letterLimitInput = element(by.model('letterLimit'));
  29959. var longNumberLimitInput = element(by.model('longNumberLimit'));
  29960. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  29961. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  29962. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  29963. it('should limit the number array to first three items', function() {
  29964. expect(numLimitInput.getAttribute('value')).toBe('3');
  29965. expect(letterLimitInput.getAttribute('value')).toBe('3');
  29966. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  29967. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  29968. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  29969. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  29970. });
  29971. // There is a bug in safari and protractor that doesn't like the minus key
  29972. // it('should update the output when -3 is entered', function() {
  29973. // numLimitInput.clear();
  29974. // numLimitInput.sendKeys('-3');
  29975. // letterLimitInput.clear();
  29976. // letterLimitInput.sendKeys('-3');
  29977. // longNumberLimitInput.clear();
  29978. // longNumberLimitInput.sendKeys('-3');
  29979. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  29980. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  29981. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  29982. // });
  29983. it('should not exceed the maximum size of input array', function() {
  29984. numLimitInput.clear();
  29985. numLimitInput.sendKeys('100');
  29986. letterLimitInput.clear();
  29987. letterLimitInput.sendKeys('100');
  29988. longNumberLimitInput.clear();
  29989. longNumberLimitInput.sendKeys('100');
  29990. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  29991. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  29992. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  29993. });
  29994. </file>
  29995. </example>
  29996. */
  29997. function limitToFilter() {
  29998. return function(input, limit, begin) {
  29999. if (Math.abs(Number(limit)) === Infinity) {
  30000. limit = Number(limit);
  30001. } else {
  30002. limit = toInt(limit);
  30003. }
  30004. if (isNaN(limit)) return input;
  30005. if (isNumber(input)) input = input.toString();
  30006. if (!isArray(input) && !isString(input)) return input;
  30007. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  30008. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  30009. if (limit >= 0) {
  30010. return input.slice(begin, begin + limit);
  30011. } else {
  30012. if (begin === 0) {
  30013. return input.slice(limit, input.length);
  30014. } else {
  30015. return input.slice(Math.max(0, begin + limit), begin);
  30016. }
  30017. }
  30018. };
  30019. }
  30020. /**
  30021. * @ngdoc filter
  30022. * @name orderBy
  30023. * @kind function
  30024. *
  30025. * @description
  30026. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  30027. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  30028. * as expected, make sure they are actually being saved as numbers and not strings.
  30029. * Array-like values (e.g. NodeLists, jQuery objects, TypedArrays, Strings, etc) are also supported.
  30030. *
  30031. * @param {Array} array The array (or array-like object) to sort.
  30032. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  30033. * used by the comparator to determine the order of elements.
  30034. *
  30035. * Can be one of:
  30036. *
  30037. * - `function`: Getter function. The result of this function will be sorted using the
  30038. * `<`, `===`, `>` operator.
  30039. * - `string`: An Angular expression. The result of this expression is used to compare elements
  30040. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  30041. * 3 first characters of a property called `name`). The result of a constant expression
  30042. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  30043. * to sort object by the value of their `special name` property). An expression can be
  30044. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  30045. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  30046. * element itself is used to compare where sorting.
  30047. * - `Array`: An array of function or string predicates. The first predicate in the array
  30048. * is used for sorting, but when two items are equivalent, the next predicate is used.
  30049. *
  30050. * If the predicate is missing or empty then it defaults to `'+'`.
  30051. *
  30052. * @param {boolean=} reverse Reverse the order of the array.
  30053. * @returns {Array} Sorted copy of the source array.
  30054. *
  30055. *
  30056. * @example
  30057. * The example below demonstrates a simple ngRepeat, where the data is sorted
  30058. * by age in descending order (predicate is set to `'-age'`).
  30059. * `reverse` is not set, which means it defaults to `false`.
  30060. <example module="orderByExample">
  30061. <file name="index.html">
  30062. <div ng-controller="ExampleController">
  30063. <table class="friend">
  30064. <tr>
  30065. <th>Name</th>
  30066. <th>Phone Number</th>
  30067. <th>Age</th>
  30068. </tr>
  30069. <tr ng-repeat="friend in friends | orderBy:'-age'">
  30070. <td>{{friend.name}}</td>
  30071. <td>{{friend.phone}}</td>
  30072. <td>{{friend.age}}</td>
  30073. </tr>
  30074. </table>
  30075. </div>
  30076. </file>
  30077. <file name="script.js">
  30078. angular.module('orderByExample', [])
  30079. .controller('ExampleController', ['$scope', function($scope) {
  30080. $scope.friends =
  30081. [{name:'John', phone:'555-1212', age:10},
  30082. {name:'Mary', phone:'555-9876', age:19},
  30083. {name:'Mike', phone:'555-4321', age:21},
  30084. {name:'Adam', phone:'555-5678', age:35},
  30085. {name:'Julie', phone:'555-8765', age:29}];
  30086. }]);
  30087. </file>
  30088. </example>
  30089. *
  30090. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  30091. * as shown in the next example.
  30092. * @example
  30093. <example module="orderByExample">
  30094. <file name="index.html">
  30095. <div ng-controller="ExampleController">
  30096. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  30097. <hr/>
  30098. <button ng-click="predicate=''">Set to unsorted</button>
  30099. <table class="friend">
  30100. <tr>
  30101. <th>
  30102. <button ng-click="order('name')">Name</button>
  30103. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  30104. </th>
  30105. <th>
  30106. <button ng-click="order('phone')">Phone Number</button>
  30107. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  30108. </th>
  30109. <th>
  30110. <button ng-click="order('age')">Age</button>
  30111. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  30112. </th>
  30113. </tr>
  30114. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  30115. <td>{{friend.name}}</td>
  30116. <td>{{friend.phone}}</td>
  30117. <td>{{friend.age}}</td>
  30118. </tr>
  30119. </table>
  30120. </div>
  30121. </file>
  30122. <file name="script.js">
  30123. angular.module('orderByExample', [])
  30124. .controller('ExampleController', ['$scope', function($scope) {
  30125. $scope.friends =
  30126. [{name:'John', phone:'555-1212', age:10},
  30127. {name:'Mary', phone:'555-9876', age:19},
  30128. {name:'Mike', phone:'555-4321', age:21},
  30129. {name:'Adam', phone:'555-5678', age:35},
  30130. {name:'Julie', phone:'555-8765', age:29}];
  30131. $scope.predicate = 'age';
  30132. $scope.reverse = true;
  30133. $scope.order = function(predicate) {
  30134. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  30135. $scope.predicate = predicate;
  30136. };
  30137. }]);
  30138. </file>
  30139. <file name="style.css">
  30140. .sortorder:after {
  30141. content: '\25b2';
  30142. }
  30143. .sortorder.reverse:after {
  30144. content: '\25bc';
  30145. }
  30146. </file>
  30147. </example>
  30148. *
  30149. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  30150. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  30151. * desired parameters.
  30152. *
  30153. * Example:
  30154. *
  30155. * @example
  30156. <example module="orderByExample">
  30157. <file name="index.html">
  30158. <div ng-controller="ExampleController">
  30159. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  30160. <table class="friend">
  30161. <tr>
  30162. <th>
  30163. <button ng-click="order('name')">Name</button>
  30164. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  30165. </th>
  30166. <th>
  30167. <button ng-click="order('phone')">Phone Number</button>
  30168. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  30169. </th>
  30170. <th>
  30171. <button ng-click="order('age')">Age</button>
  30172. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  30173. </th>
  30174. </tr>
  30175. <tr ng-repeat="friend in friends">
  30176. <td>{{friend.name}}</td>
  30177. <td>{{friend.phone}}</td>
  30178. <td>{{friend.age}}</td>
  30179. </tr>
  30180. </table>
  30181. </div>
  30182. </file>
  30183. <file name="script.js">
  30184. angular.module('orderByExample', [])
  30185. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  30186. var orderBy = $filter('orderBy');
  30187. $scope.friends = [
  30188. { name: 'John', phone: '555-1212', age: 10 },
  30189. { name: 'Mary', phone: '555-9876', age: 19 },
  30190. { name: 'Mike', phone: '555-4321', age: 21 },
  30191. { name: 'Adam', phone: '555-5678', age: 35 },
  30192. { name: 'Julie', phone: '555-8765', age: 29 }
  30193. ];
  30194. $scope.order = function(predicate) {
  30195. $scope.predicate = predicate;
  30196. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  30197. $scope.friends = orderBy($scope.friends, predicate, $scope.reverse);
  30198. };
  30199. $scope.order('age', true);
  30200. }]);
  30201. </file>
  30202. <file name="style.css">
  30203. .sortorder:after {
  30204. content: '\25b2';
  30205. }
  30206. .sortorder.reverse:after {
  30207. content: '\25bc';
  30208. }
  30209. </file>
  30210. </example>
  30211. */
  30212. orderByFilter.$inject = ['$parse'];
  30213. function orderByFilter($parse) {
  30214. return function(array, sortPredicate, reverseOrder) {
  30215. if (array == null) return array;
  30216. if (!isArrayLike(array)) {
  30217. throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array);
  30218. }
  30219. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  30220. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  30221. var predicates = processPredicates(sortPredicate, reverseOrder);
  30222. // Add a predicate at the end that evaluates to the element index. This makes the
  30223. // sort stable as it works as a tie-breaker when all the input predicates cannot
  30224. // distinguish between two elements.
  30225. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  30226. // The next three lines are a version of a Swartzian Transform idiom from Perl
  30227. // (sometimes called the Decorate-Sort-Undecorate idiom)
  30228. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  30229. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  30230. compareValues.sort(doComparison);
  30231. array = compareValues.map(function(item) { return item.value; });
  30232. return array;
  30233. function getComparisonObject(value, index) {
  30234. return {
  30235. value: value,
  30236. predicateValues: predicates.map(function(predicate) {
  30237. return getPredicateValue(predicate.get(value), index);
  30238. })
  30239. };
  30240. }
  30241. function doComparison(v1, v2) {
  30242. var result = 0;
  30243. for (var index=0, length = predicates.length; index < length; ++index) {
  30244. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  30245. if (result) break;
  30246. }
  30247. return result;
  30248. }
  30249. };
  30250. function processPredicates(sortPredicate, reverseOrder) {
  30251. reverseOrder = reverseOrder ? -1 : 1;
  30252. return sortPredicate.map(function(predicate) {
  30253. var descending = 1, get = identity;
  30254. if (isFunction(predicate)) {
  30255. get = predicate;
  30256. } else if (isString(predicate)) {
  30257. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  30258. descending = predicate.charAt(0) == '-' ? -1 : 1;
  30259. predicate = predicate.substring(1);
  30260. }
  30261. if (predicate !== '') {
  30262. get = $parse(predicate);
  30263. if (get.constant) {
  30264. var key = get();
  30265. get = function(value) { return value[key]; };
  30266. }
  30267. }
  30268. }
  30269. return { get: get, descending: descending * reverseOrder };
  30270. });
  30271. }
  30272. function isPrimitive(value) {
  30273. switch (typeof value) {
  30274. case 'number': /* falls through */
  30275. case 'boolean': /* falls through */
  30276. case 'string':
  30277. return true;
  30278. default:
  30279. return false;
  30280. }
  30281. }
  30282. function objectValue(value, index) {
  30283. // If `valueOf` is a valid function use that
  30284. if (typeof value.valueOf === 'function') {
  30285. value = value.valueOf();
  30286. if (isPrimitive(value)) return value;
  30287. }
  30288. // If `toString` is a valid function and not the one from `Object.prototype` use that
  30289. if (hasCustomToString(value)) {
  30290. value = value.toString();
  30291. if (isPrimitive(value)) return value;
  30292. }
  30293. // We have a basic object so we use the position of the object in the collection
  30294. return index;
  30295. }
  30296. function getPredicateValue(value, index) {
  30297. var type = typeof value;
  30298. if (value === null) {
  30299. type = 'string';
  30300. value = 'null';
  30301. } else if (type === 'string') {
  30302. value = value.toLowerCase();
  30303. } else if (type === 'object') {
  30304. value = objectValue(value, index);
  30305. }
  30306. return { value: value, type: type };
  30307. }
  30308. function compare(v1, v2) {
  30309. var result = 0;
  30310. if (v1.type === v2.type) {
  30311. if (v1.value !== v2.value) {
  30312. result = v1.value < v2.value ? -1 : 1;
  30313. }
  30314. } else {
  30315. result = v1.type < v2.type ? -1 : 1;
  30316. }
  30317. return result;
  30318. }
  30319. }
  30320. function ngDirective(directive) {
  30321. if (isFunction(directive)) {
  30322. directive = {
  30323. link: directive
  30324. };
  30325. }
  30326. directive.restrict = directive.restrict || 'AC';
  30327. return valueFn(directive);
  30328. }
  30329. /**
  30330. * @ngdoc directive
  30331. * @name a
  30332. * @restrict E
  30333. *
  30334. * @description
  30335. * Modifies the default behavior of the html A tag so that the default action is prevented when
  30336. * the href attribute is empty.
  30337. *
  30338. * This change permits the easy creation of action links with the `ngClick` directive
  30339. * without changing the location or causing page reloads, e.g.:
  30340. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  30341. */
  30342. var htmlAnchorDirective = valueFn({
  30343. restrict: 'E',
  30344. compile: function(element, attr) {
  30345. if (!attr.href && !attr.xlinkHref) {
  30346. return function(scope, element) {
  30347. // If the linked element is not an anchor tag anymore, do nothing
  30348. if (element[0].nodeName.toLowerCase() !== 'a') return;
  30349. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  30350. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  30351. 'xlink:href' : 'href';
  30352. element.on('click', function(event) {
  30353. // if we have no href url, then don't navigate anywhere.
  30354. if (!element.attr(href)) {
  30355. event.preventDefault();
  30356. }
  30357. });
  30358. };
  30359. }
  30360. }
  30361. });
  30362. /**
  30363. * @ngdoc directive
  30364. * @name ngHref
  30365. * @restrict A
  30366. * @priority 99
  30367. *
  30368. * @description
  30369. * Using Angular markup like `{{hash}}` in an href attribute will
  30370. * make the link go to the wrong URL if the user clicks it before
  30371. * Angular has a chance to replace the `{{hash}}` markup with its
  30372. * value. Until Angular replaces the markup the link will be broken
  30373. * and will most likely return a 404 error. The `ngHref` directive
  30374. * solves this problem.
  30375. *
  30376. * The wrong way to write it:
  30377. * ```html
  30378. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  30379. * ```
  30380. *
  30381. * The correct way to write it:
  30382. * ```html
  30383. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  30384. * ```
  30385. *
  30386. * @element A
  30387. * @param {template} ngHref any string which can contain `{{}}` markup.
  30388. *
  30389. * @example
  30390. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  30391. * in links and their different behaviors:
  30392. <example>
  30393. <file name="index.html">
  30394. <input ng-model="value" /><br />
  30395. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  30396. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  30397. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  30398. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  30399. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  30400. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  30401. </file>
  30402. <file name="protractor.js" type="protractor">
  30403. it('should execute ng-click but not reload when href without value', function() {
  30404. element(by.id('link-1')).click();
  30405. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  30406. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  30407. });
  30408. it('should execute ng-click but not reload when href empty string', function() {
  30409. element(by.id('link-2')).click();
  30410. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  30411. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  30412. });
  30413. it('should execute ng-click and change url when ng-href specified', function() {
  30414. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  30415. element(by.id('link-3')).click();
  30416. // At this point, we navigate away from an Angular page, so we need
  30417. // to use browser.driver to get the base webdriver.
  30418. browser.wait(function() {
  30419. return browser.driver.getCurrentUrl().then(function(url) {
  30420. return url.match(/\/123$/);
  30421. });
  30422. }, 5000, 'page should navigate to /123');
  30423. });
  30424. it('should execute ng-click but not reload when href empty string and name specified', function() {
  30425. element(by.id('link-4')).click();
  30426. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  30427. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  30428. });
  30429. it('should execute ng-click but not reload when no href but name specified', function() {
  30430. element(by.id('link-5')).click();
  30431. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  30432. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  30433. });
  30434. it('should only change url when only ng-href', function() {
  30435. element(by.model('value')).clear();
  30436. element(by.model('value')).sendKeys('6');
  30437. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  30438. element(by.id('link-6')).click();
  30439. // At this point, we navigate away from an Angular page, so we need
  30440. // to use browser.driver to get the base webdriver.
  30441. browser.wait(function() {
  30442. return browser.driver.getCurrentUrl().then(function(url) {
  30443. return url.match(/\/6$/);
  30444. });
  30445. }, 5000, 'page should navigate to /6');
  30446. });
  30447. </file>
  30448. </example>
  30449. */
  30450. /**
  30451. * @ngdoc directive
  30452. * @name ngSrc
  30453. * @restrict A
  30454. * @priority 99
  30455. *
  30456. * @description
  30457. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  30458. * work right: The browser will fetch from the URL with the literal
  30459. * text `{{hash}}` until Angular replaces the expression inside
  30460. * `{{hash}}`. The `ngSrc` directive solves this problem.
  30461. *
  30462. * The buggy way to write it:
  30463. * ```html
  30464. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  30465. * ```
  30466. *
  30467. * The correct way to write it:
  30468. * ```html
  30469. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  30470. * ```
  30471. *
  30472. * @element IMG
  30473. * @param {template} ngSrc any string which can contain `{{}}` markup.
  30474. */
  30475. /**
  30476. * @ngdoc directive
  30477. * @name ngSrcset
  30478. * @restrict A
  30479. * @priority 99
  30480. *
  30481. * @description
  30482. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  30483. * work right: The browser will fetch from the URL with the literal
  30484. * text `{{hash}}` until Angular replaces the expression inside
  30485. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  30486. *
  30487. * The buggy way to write it:
  30488. * ```html
  30489. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  30490. * ```
  30491. *
  30492. * The correct way to write it:
  30493. * ```html
  30494. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  30495. * ```
  30496. *
  30497. * @element IMG
  30498. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  30499. */
  30500. /**
  30501. * @ngdoc directive
  30502. * @name ngDisabled
  30503. * @restrict A
  30504. * @priority 100
  30505. *
  30506. * @description
  30507. *
  30508. * This directive sets the `disabled` attribute on the element if the
  30509. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  30510. *
  30511. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  30512. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30513. *
  30514. * @example
  30515. <example>
  30516. <file name="index.html">
  30517. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  30518. <button ng-model="button" ng-disabled="checked">Button</button>
  30519. </file>
  30520. <file name="protractor.js" type="protractor">
  30521. it('should toggle button', function() {
  30522. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  30523. element(by.model('checked')).click();
  30524. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  30525. });
  30526. </file>
  30527. </example>
  30528. *
  30529. * @element INPUT
  30530. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  30531. * then the `disabled` attribute will be set on the element
  30532. */
  30533. /**
  30534. * @ngdoc directive
  30535. * @name ngChecked
  30536. * @restrict A
  30537. * @priority 100
  30538. *
  30539. * @description
  30540. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  30541. *
  30542. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  30543. * as this can lead to unexpected behavior.
  30544. *
  30545. * A special directive is necessary because we cannot use interpolation inside the `checked`
  30546. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30547. *
  30548. * @example
  30549. <example>
  30550. <file name="index.html">
  30551. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  30552. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  30553. </file>
  30554. <file name="protractor.js" type="protractor">
  30555. it('should check both checkBoxes', function() {
  30556. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  30557. element(by.model('master')).click();
  30558. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  30559. });
  30560. </file>
  30561. </example>
  30562. *
  30563. * @element INPUT
  30564. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  30565. * then the `checked` attribute will be set on the element
  30566. */
  30567. /**
  30568. * @ngdoc directive
  30569. * @name ngReadonly
  30570. * @restrict A
  30571. * @priority 100
  30572. *
  30573. * @description
  30574. *
  30575. * Sets the `readOnly` attribute on the element, if the expression inside `ngReadonly` is truthy.
  30576. *
  30577. * A special directive is necessary because we cannot use interpolation inside the `readOnly`
  30578. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30579. *
  30580. * @example
  30581. <example>
  30582. <file name="index.html">
  30583. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  30584. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  30585. </file>
  30586. <file name="protractor.js" type="protractor">
  30587. it('should toggle readonly attr', function() {
  30588. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  30589. element(by.model('checked')).click();
  30590. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  30591. });
  30592. </file>
  30593. </example>
  30594. *
  30595. * @element INPUT
  30596. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  30597. * then special attribute "readonly" will be set on the element
  30598. */
  30599. /**
  30600. * @ngdoc directive
  30601. * @name ngSelected
  30602. * @restrict A
  30603. * @priority 100
  30604. *
  30605. * @description
  30606. *
  30607. * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy.
  30608. *
  30609. * A special directive is necessary because we cannot use interpolation inside the `selected`
  30610. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30611. *
  30612. * @example
  30613. <example>
  30614. <file name="index.html">
  30615. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  30616. <select aria-label="ngSelected demo">
  30617. <option>Hello!</option>
  30618. <option id="greet" ng-selected="selected">Greetings!</option>
  30619. </select>
  30620. </file>
  30621. <file name="protractor.js" type="protractor">
  30622. it('should select Greetings!', function() {
  30623. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  30624. element(by.model('selected')).click();
  30625. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  30626. });
  30627. </file>
  30628. </example>
  30629. *
  30630. * @element OPTION
  30631. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  30632. * then special attribute "selected" will be set on the element
  30633. */
  30634. /**
  30635. * @ngdoc directive
  30636. * @name ngOpen
  30637. * @restrict A
  30638. * @priority 100
  30639. *
  30640. * @description
  30641. *
  30642. * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy.
  30643. *
  30644. * A special directive is necessary because we cannot use interpolation inside the `open`
  30645. * attribute. See the {@link guide/interpolation interpolation guide} for more info.
  30646. *
  30647. * @example
  30648. <example>
  30649. <file name="index.html">
  30650. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  30651. <details id="details" ng-open="open">
  30652. <summary>Show/Hide me</summary>
  30653. </details>
  30654. </file>
  30655. <file name="protractor.js" type="protractor">
  30656. it('should toggle open', function() {
  30657. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  30658. element(by.model('open')).click();
  30659. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  30660. });
  30661. </file>
  30662. </example>
  30663. *
  30664. * @element DETAILS
  30665. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  30666. * then special attribute "open" will be set on the element
  30667. */
  30668. var ngAttributeAliasDirectives = {};
  30669. // boolean attrs are evaluated
  30670. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  30671. // binding to multiple is not supported
  30672. if (propName == "multiple") return;
  30673. function defaultLinkFn(scope, element, attr) {
  30674. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  30675. attr.$set(attrName, !!value);
  30676. });
  30677. }
  30678. var normalized = directiveNormalize('ng-' + attrName);
  30679. var linkFn = defaultLinkFn;
  30680. if (propName === 'checked') {
  30681. linkFn = function(scope, element, attr) {
  30682. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  30683. if (attr.ngModel !== attr[normalized]) {
  30684. defaultLinkFn(scope, element, attr);
  30685. }
  30686. };
  30687. }
  30688. ngAttributeAliasDirectives[normalized] = function() {
  30689. return {
  30690. restrict: 'A',
  30691. priority: 100,
  30692. link: linkFn
  30693. };
  30694. };
  30695. });
  30696. // aliased input attrs are evaluated
  30697. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  30698. ngAttributeAliasDirectives[ngAttr] = function() {
  30699. return {
  30700. priority: 100,
  30701. link: function(scope, element, attr) {
  30702. //special case ngPattern when a literal regular expression value
  30703. //is used as the expression (this way we don't have to watch anything).
  30704. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  30705. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  30706. if (match) {
  30707. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  30708. return;
  30709. }
  30710. }
  30711. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  30712. attr.$set(ngAttr, value);
  30713. });
  30714. }
  30715. };
  30716. };
  30717. });
  30718. // ng-src, ng-srcset, ng-href are interpolated
  30719. forEach(['src', 'srcset', 'href'], function(attrName) {
  30720. var normalized = directiveNormalize('ng-' + attrName);
  30721. ngAttributeAliasDirectives[normalized] = function() {
  30722. return {
  30723. priority: 99, // it needs to run after the attributes are interpolated
  30724. link: function(scope, element, attr) {
  30725. var propName = attrName,
  30726. name = attrName;
  30727. if (attrName === 'href' &&
  30728. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  30729. name = 'xlinkHref';
  30730. attr.$attr[name] = 'xlink:href';
  30731. propName = null;
  30732. }
  30733. attr.$observe(normalized, function(value) {
  30734. if (!value) {
  30735. if (attrName === 'href') {
  30736. attr.$set(name, null);
  30737. }
  30738. return;
  30739. }
  30740. attr.$set(name, value);
  30741. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  30742. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  30743. // to set the property as well to achieve the desired effect.
  30744. // we use attr[attrName] value since $set can sanitize the url.
  30745. if (msie && propName) element.prop(propName, attr[name]);
  30746. });
  30747. }
  30748. };
  30749. };
  30750. });
  30751. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  30752. */
  30753. var nullFormCtrl = {
  30754. $addControl: noop,
  30755. $$renameControl: nullFormRenameControl,
  30756. $removeControl: noop,
  30757. $setValidity: noop,
  30758. $setDirty: noop,
  30759. $setPristine: noop,
  30760. $setSubmitted: noop
  30761. },
  30762. SUBMITTED_CLASS = 'ng-submitted';
  30763. function nullFormRenameControl(control, name) {
  30764. control.$name = name;
  30765. }
  30766. /**
  30767. * @ngdoc type
  30768. * @name form.FormController
  30769. *
  30770. * @property {boolean} $pristine True if user has not interacted with the form yet.
  30771. * @property {boolean} $dirty True if user has already interacted with the form.
  30772. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  30773. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  30774. * @property {boolean} $pending True if at least one containing control or form is pending.
  30775. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  30776. *
  30777. * @property {Object} $error Is an object hash, containing references to controls or
  30778. * forms with failing validators, where:
  30779. *
  30780. * - keys are validation tokens (error names),
  30781. * - values are arrays of controls or forms that have a failing validator for given error name.
  30782. *
  30783. * Built-in validation tokens:
  30784. *
  30785. * - `email`
  30786. * - `max`
  30787. * - `maxlength`
  30788. * - `min`
  30789. * - `minlength`
  30790. * - `number`
  30791. * - `pattern`
  30792. * - `required`
  30793. * - `url`
  30794. * - `date`
  30795. * - `datetimelocal`
  30796. * - `time`
  30797. * - `week`
  30798. * - `month`
  30799. *
  30800. * @description
  30801. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  30802. * such as being valid/invalid or dirty/pristine.
  30803. *
  30804. * Each {@link ng.directive:form form} directive creates an instance
  30805. * of `FormController`.
  30806. *
  30807. */
  30808. //asks for $scope to fool the BC controller module
  30809. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  30810. function FormController(element, attrs, $scope, $animate, $interpolate) {
  30811. var form = this,
  30812. controls = [];
  30813. // init state
  30814. form.$error = {};
  30815. form.$$success = {};
  30816. form.$pending = undefined;
  30817. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  30818. form.$dirty = false;
  30819. form.$pristine = true;
  30820. form.$valid = true;
  30821. form.$invalid = false;
  30822. form.$submitted = false;
  30823. form.$$parentForm = nullFormCtrl;
  30824. /**
  30825. * @ngdoc method
  30826. * @name form.FormController#$rollbackViewValue
  30827. *
  30828. * @description
  30829. * Rollback all form controls pending updates to the `$modelValue`.
  30830. *
  30831. * Updates may be pending by a debounced event or because the input is waiting for a some future
  30832. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  30833. * a form that uses `ng-model-options` to pend updates.
  30834. */
  30835. form.$rollbackViewValue = function() {
  30836. forEach(controls, function(control) {
  30837. control.$rollbackViewValue();
  30838. });
  30839. };
  30840. /**
  30841. * @ngdoc method
  30842. * @name form.FormController#$commitViewValue
  30843. *
  30844. * @description
  30845. * Commit all form controls pending updates to the `$modelValue`.
  30846. *
  30847. * Updates may be pending by a debounced event or because the input is waiting for a some future
  30848. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  30849. * usually handles calling this in response to input events.
  30850. */
  30851. form.$commitViewValue = function() {
  30852. forEach(controls, function(control) {
  30853. control.$commitViewValue();
  30854. });
  30855. };
  30856. /**
  30857. * @ngdoc method
  30858. * @name form.FormController#$addControl
  30859. * @param {object} control control object, either a {@link form.FormController} or an
  30860. * {@link ngModel.NgModelController}
  30861. *
  30862. * @description
  30863. * Register a control with the form. Input elements using ngModelController do this automatically
  30864. * when they are linked.
  30865. *
  30866. * Note that the current state of the control will not be reflected on the new parent form. This
  30867. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  30868. * state.
  30869. *
  30870. * However, if the method is used programmatically, for example by adding dynamically created controls,
  30871. * or controls that have been previously removed without destroying their corresponding DOM element,
  30872. * it's the developers responsibility to make sure the current state propagates to the parent form.
  30873. *
  30874. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  30875. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  30876. */
  30877. form.$addControl = function(control) {
  30878. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  30879. // and not added to the scope. Now we throw an error.
  30880. assertNotHasOwnProperty(control.$name, 'input');
  30881. controls.push(control);
  30882. if (control.$name) {
  30883. form[control.$name] = control;
  30884. }
  30885. control.$$parentForm = form;
  30886. };
  30887. // Private API: rename a form control
  30888. form.$$renameControl = function(control, newName) {
  30889. var oldName = control.$name;
  30890. if (form[oldName] === control) {
  30891. delete form[oldName];
  30892. }
  30893. form[newName] = control;
  30894. control.$name = newName;
  30895. };
  30896. /**
  30897. * @ngdoc method
  30898. * @name form.FormController#$removeControl
  30899. * @param {object} control control object, either a {@link form.FormController} or an
  30900. * {@link ngModel.NgModelController}
  30901. *
  30902. * @description
  30903. * Deregister a control from the form.
  30904. *
  30905. * Input elements using ngModelController do this automatically when they are destroyed.
  30906. *
  30907. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  30908. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  30909. * different from case to case. For example, removing the only `$dirty` control from a form may or
  30910. * may not mean that the form is still `$dirty`.
  30911. */
  30912. form.$removeControl = function(control) {
  30913. if (control.$name && form[control.$name] === control) {
  30914. delete form[control.$name];
  30915. }
  30916. forEach(form.$pending, function(value, name) {
  30917. form.$setValidity(name, null, control);
  30918. });
  30919. forEach(form.$error, function(value, name) {
  30920. form.$setValidity(name, null, control);
  30921. });
  30922. forEach(form.$$success, function(value, name) {
  30923. form.$setValidity(name, null, control);
  30924. });
  30925. arrayRemove(controls, control);
  30926. control.$$parentForm = nullFormCtrl;
  30927. };
  30928. /**
  30929. * @ngdoc method
  30930. * @name form.FormController#$setValidity
  30931. *
  30932. * @description
  30933. * Sets the validity of a form control.
  30934. *
  30935. * This method will also propagate to parent forms.
  30936. */
  30937. addSetValidityMethod({
  30938. ctrl: this,
  30939. $element: element,
  30940. set: function(object, property, controller) {
  30941. var list = object[property];
  30942. if (!list) {
  30943. object[property] = [controller];
  30944. } else {
  30945. var index = list.indexOf(controller);
  30946. if (index === -1) {
  30947. list.push(controller);
  30948. }
  30949. }
  30950. },
  30951. unset: function(object, property, controller) {
  30952. var list = object[property];
  30953. if (!list) {
  30954. return;
  30955. }
  30956. arrayRemove(list, controller);
  30957. if (list.length === 0) {
  30958. delete object[property];
  30959. }
  30960. },
  30961. $animate: $animate
  30962. });
  30963. /**
  30964. * @ngdoc method
  30965. * @name form.FormController#$setDirty
  30966. *
  30967. * @description
  30968. * Sets the form to a dirty state.
  30969. *
  30970. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  30971. * state (ng-dirty class). This method will also propagate to parent forms.
  30972. */
  30973. form.$setDirty = function() {
  30974. $animate.removeClass(element, PRISTINE_CLASS);
  30975. $animate.addClass(element, DIRTY_CLASS);
  30976. form.$dirty = true;
  30977. form.$pristine = false;
  30978. form.$$parentForm.$setDirty();
  30979. };
  30980. /**
  30981. * @ngdoc method
  30982. * @name form.FormController#$setPristine
  30983. *
  30984. * @description
  30985. * Sets the form to its pristine state.
  30986. *
  30987. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  30988. * state (ng-pristine class). This method will also propagate to all the controls contained
  30989. * in this form.
  30990. *
  30991. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  30992. * saving or resetting it.
  30993. */
  30994. form.$setPristine = function() {
  30995. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  30996. form.$dirty = false;
  30997. form.$pristine = true;
  30998. form.$submitted = false;
  30999. forEach(controls, function(control) {
  31000. control.$setPristine();
  31001. });
  31002. };
  31003. /**
  31004. * @ngdoc method
  31005. * @name form.FormController#$setUntouched
  31006. *
  31007. * @description
  31008. * Sets the form to its untouched state.
  31009. *
  31010. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  31011. * untouched state (ng-untouched class).
  31012. *
  31013. * Setting a form controls back to their untouched state is often useful when setting the form
  31014. * back to its pristine state.
  31015. */
  31016. form.$setUntouched = function() {
  31017. forEach(controls, function(control) {
  31018. control.$setUntouched();
  31019. });
  31020. };
  31021. /**
  31022. * @ngdoc method
  31023. * @name form.FormController#$setSubmitted
  31024. *
  31025. * @description
  31026. * Sets the form to its submitted state.
  31027. */
  31028. form.$setSubmitted = function() {
  31029. $animate.addClass(element, SUBMITTED_CLASS);
  31030. form.$submitted = true;
  31031. form.$$parentForm.$setSubmitted();
  31032. };
  31033. }
  31034. /**
  31035. * @ngdoc directive
  31036. * @name ngForm
  31037. * @restrict EAC
  31038. *
  31039. * @description
  31040. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  31041. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  31042. * sub-group of controls needs to be determined.
  31043. *
  31044. * Note: the purpose of `ngForm` is to group controls,
  31045. * but not to be a replacement for the `<form>` tag with all of its capabilities
  31046. * (e.g. posting to the server, ...).
  31047. *
  31048. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  31049. * related scope, under this name.
  31050. *
  31051. */
  31052. /**
  31053. * @ngdoc directive
  31054. * @name form
  31055. * @restrict E
  31056. *
  31057. * @description
  31058. * Directive that instantiates
  31059. * {@link form.FormController FormController}.
  31060. *
  31061. * If the `name` attribute is specified, the form controller is published onto the current scope under
  31062. * this name.
  31063. *
  31064. * # Alias: {@link ng.directive:ngForm `ngForm`}
  31065. *
  31066. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  31067. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  31068. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to
  31069. * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group
  31070. * of controls needs to be determined.
  31071. *
  31072. * # CSS classes
  31073. * - `ng-valid` is set if the form is valid.
  31074. * - `ng-invalid` is set if the form is invalid.
  31075. * - `ng-pending` is set if the form is pending.
  31076. * - `ng-pristine` is set if the form is pristine.
  31077. * - `ng-dirty` is set if the form is dirty.
  31078. * - `ng-submitted` is set if the form was submitted.
  31079. *
  31080. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  31081. *
  31082. *
  31083. * # Submitting a form and preventing the default action
  31084. *
  31085. * Since the role of forms in client-side Angular applications is different than in classical
  31086. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  31087. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  31088. * to handle the form submission in an application-specific way.
  31089. *
  31090. * For this reason, Angular prevents the default action (form submission to the server) unless the
  31091. * `<form>` element has an `action` attribute specified.
  31092. *
  31093. * You can use one of the following two ways to specify what javascript method should be called when
  31094. * a form is submitted:
  31095. *
  31096. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  31097. * - {@link ng.directive:ngClick ngClick} directive on the first
  31098. * button or input field of type submit (input[type=submit])
  31099. *
  31100. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  31101. * or {@link ng.directive:ngClick ngClick} directives.
  31102. * This is because of the following form submission rules in the HTML specification:
  31103. *
  31104. * - If a form has only one input field then hitting enter in this field triggers form submit
  31105. * (`ngSubmit`)
  31106. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  31107. * doesn't trigger submit
  31108. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  31109. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  31110. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  31111. *
  31112. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  31113. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  31114. * to have access to the updated model.
  31115. *
  31116. * ## Animation Hooks
  31117. *
  31118. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  31119. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  31120. * other validations that are performed within the form. Animations in ngForm are similar to how
  31121. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  31122. * as JS animations.
  31123. *
  31124. * The following example shows a simple way to utilize CSS transitions to style a form element
  31125. * that has been rendered as invalid after it has been validated:
  31126. *
  31127. * <pre>
  31128. * //be sure to include ngAnimate as a module to hook into more
  31129. * //advanced animations
  31130. * .my-form {
  31131. * transition:0.5s linear all;
  31132. * background: white;
  31133. * }
  31134. * .my-form.ng-invalid {
  31135. * background: red;
  31136. * color:white;
  31137. * }
  31138. * </pre>
  31139. *
  31140. * @example
  31141. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  31142. <file name="index.html">
  31143. <script>
  31144. angular.module('formExample', [])
  31145. .controller('FormController', ['$scope', function($scope) {
  31146. $scope.userType = 'guest';
  31147. }]);
  31148. </script>
  31149. <style>
  31150. .my-form {
  31151. transition:all linear 0.5s;
  31152. background: transparent;
  31153. }
  31154. .my-form.ng-invalid {
  31155. background: red;
  31156. }
  31157. </style>
  31158. <form name="myForm" ng-controller="FormController" class="my-form">
  31159. userType: <input name="input" ng-model="userType" required>
  31160. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  31161. <code>userType = {{userType}}</code><br>
  31162. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  31163. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  31164. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  31165. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  31166. </form>
  31167. </file>
  31168. <file name="protractor.js" type="protractor">
  31169. it('should initialize to model', function() {
  31170. var userType = element(by.binding('userType'));
  31171. var valid = element(by.binding('myForm.input.$valid'));
  31172. expect(userType.getText()).toContain('guest');
  31173. expect(valid.getText()).toContain('true');
  31174. });
  31175. it('should be invalid if empty', function() {
  31176. var userType = element(by.binding('userType'));
  31177. var valid = element(by.binding('myForm.input.$valid'));
  31178. var userInput = element(by.model('userType'));
  31179. userInput.clear();
  31180. userInput.sendKeys('');
  31181. expect(userType.getText()).toEqual('userType =');
  31182. expect(valid.getText()).toContain('false');
  31183. });
  31184. </file>
  31185. </example>
  31186. *
  31187. * @param {string=} name Name of the form. If specified, the form controller will be published into
  31188. * related scope, under this name.
  31189. */
  31190. var formDirectiveFactory = function(isNgForm) {
  31191. return ['$timeout', '$parse', function($timeout, $parse) {
  31192. var formDirective = {
  31193. name: 'form',
  31194. restrict: isNgForm ? 'EAC' : 'E',
  31195. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  31196. controller: FormController,
  31197. compile: function ngFormCompile(formElement, attr) {
  31198. // Setup initial state of the control
  31199. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  31200. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  31201. return {
  31202. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  31203. var controller = ctrls[0];
  31204. // if `action` attr is not present on the form, prevent the default action (submission)
  31205. if (!('action' in attr)) {
  31206. // we can't use jq events because if a form is destroyed during submission the default
  31207. // action is not prevented. see #1238
  31208. //
  31209. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  31210. // page reload if the form was destroyed by submission of the form via a click handler
  31211. // on a button in the form. Looks like an IE9 specific bug.
  31212. var handleFormSubmission = function(event) {
  31213. scope.$apply(function() {
  31214. controller.$commitViewValue();
  31215. controller.$setSubmitted();
  31216. });
  31217. event.preventDefault();
  31218. };
  31219. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  31220. // unregister the preventDefault listener so that we don't not leak memory but in a
  31221. // way that will achieve the prevention of the default action.
  31222. formElement.on('$destroy', function() {
  31223. $timeout(function() {
  31224. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  31225. }, 0, false);
  31226. });
  31227. }
  31228. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  31229. parentFormCtrl.$addControl(controller);
  31230. var setter = nameAttr ? getSetter(controller.$name) : noop;
  31231. if (nameAttr) {
  31232. setter(scope, controller);
  31233. attr.$observe(nameAttr, function(newValue) {
  31234. if (controller.$name === newValue) return;
  31235. setter(scope, undefined);
  31236. controller.$$parentForm.$$renameControl(controller, newValue);
  31237. setter = getSetter(controller.$name);
  31238. setter(scope, controller);
  31239. });
  31240. }
  31241. formElement.on('$destroy', function() {
  31242. controller.$$parentForm.$removeControl(controller);
  31243. setter(scope, undefined);
  31244. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  31245. });
  31246. }
  31247. };
  31248. }
  31249. };
  31250. return formDirective;
  31251. function getSetter(expression) {
  31252. if (expression === '') {
  31253. //create an assignable expression, so forms with an empty name can be renamed later
  31254. return $parse('this[""]').assign;
  31255. }
  31256. return $parse(expression).assign || noop;
  31257. }
  31258. }];
  31259. };
  31260. var formDirective = formDirectiveFactory();
  31261. var ngFormDirective = formDirectiveFactory(true);
  31262. /* global VALID_CLASS: false,
  31263. INVALID_CLASS: false,
  31264. PRISTINE_CLASS: false,
  31265. DIRTY_CLASS: false,
  31266. UNTOUCHED_CLASS: false,
  31267. TOUCHED_CLASS: false,
  31268. ngModelMinErr: false,
  31269. */
  31270. // Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  31271. 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)$/;
  31272. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  31273. // Note: We are being more lenient, because browsers are too.
  31274. // 1. Scheme
  31275. // 2. Slashes
  31276. // 3. Username
  31277. // 4. Password
  31278. // 5. Hostname
  31279. // 6. Port
  31280. // 7. Path
  31281. // 8. Query
  31282. // 9. Fragment
  31283. // 1111111111111111 222 333333 44444 555555555555555555555555 666 77777777 8888888 999
  31284. var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+\])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i;
  31285. 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;
  31286. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  31287. var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/;
  31288. var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  31289. var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/;
  31290. var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/;
  31291. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  31292. var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown';
  31293. var PARTIAL_VALIDATION_TYPES = createMap();
  31294. forEach('date,datetime-local,month,time,week'.split(','), function(type) {
  31295. PARTIAL_VALIDATION_TYPES[type] = true;
  31296. });
  31297. var inputType = {
  31298. /**
  31299. * @ngdoc input
  31300. * @name input[text]
  31301. *
  31302. * @description
  31303. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  31304. *
  31305. *
  31306. * @param {string} ngModel Assignable angular expression to data-bind to.
  31307. * @param {string=} name Property name of the form under which the control is published.
  31308. * @param {string=} required Adds `required` validation error key if the value is not entered.
  31309. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31310. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31311. * `required` when you want to data-bind to the `required` attribute.
  31312. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  31313. * minlength.
  31314. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  31315. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  31316. * any length.
  31317. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  31318. * that contains the regular expression body that will be converted to a regular expression
  31319. * as in the ngPattern directive.
  31320. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  31321. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  31322. * If the expression evaluates to a RegExp object, then this is used directly.
  31323. * If the expression evaluates to a string, then it will be converted to a RegExp
  31324. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  31325. * `new RegExp('^abc$')`.<br />
  31326. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  31327. * start at the index of the last search's match, thus not taking the whole input value into
  31328. * account.
  31329. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31330. * interaction with the input element.
  31331. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  31332. * This parameter is ignored for input[type=password] controls, which will never trim the
  31333. * input.
  31334. *
  31335. * @example
  31336. <example name="text-input-directive" module="textInputExample">
  31337. <file name="index.html">
  31338. <script>
  31339. angular.module('textInputExample', [])
  31340. .controller('ExampleController', ['$scope', function($scope) {
  31341. $scope.example = {
  31342. text: 'guest',
  31343. word: /^\s*\w*\s*$/
  31344. };
  31345. }]);
  31346. </script>
  31347. <form name="myForm" ng-controller="ExampleController">
  31348. <label>Single word:
  31349. <input type="text" name="input" ng-model="example.text"
  31350. ng-pattern="example.word" required ng-trim="false">
  31351. </label>
  31352. <div role="alert">
  31353. <span class="error" ng-show="myForm.input.$error.required">
  31354. Required!</span>
  31355. <span class="error" ng-show="myForm.input.$error.pattern">
  31356. Single word only!</span>
  31357. </div>
  31358. <tt>text = {{example.text}}</tt><br/>
  31359. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31360. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31361. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31362. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31363. </form>
  31364. </file>
  31365. <file name="protractor.js" type="protractor">
  31366. var text = element(by.binding('example.text'));
  31367. var valid = element(by.binding('myForm.input.$valid'));
  31368. var input = element(by.model('example.text'));
  31369. it('should initialize to model', function() {
  31370. expect(text.getText()).toContain('guest');
  31371. expect(valid.getText()).toContain('true');
  31372. });
  31373. it('should be invalid if empty', function() {
  31374. input.clear();
  31375. input.sendKeys('');
  31376. expect(text.getText()).toEqual('text =');
  31377. expect(valid.getText()).toContain('false');
  31378. });
  31379. it('should be invalid if multi word', function() {
  31380. input.clear();
  31381. input.sendKeys('hello world');
  31382. expect(valid.getText()).toContain('false');
  31383. });
  31384. </file>
  31385. </example>
  31386. */
  31387. 'text': textInputType,
  31388. /**
  31389. * @ngdoc input
  31390. * @name input[date]
  31391. *
  31392. * @description
  31393. * Input with date validation and transformation. In browsers that do not yet support
  31394. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  31395. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  31396. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  31397. * expected input format via a placeholder or label.
  31398. *
  31399. * The model must always be a Date object, otherwise Angular will throw an error.
  31400. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31401. *
  31402. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31403. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31404. *
  31405. * @param {string} ngModel Assignable angular expression to data-bind to.
  31406. * @param {string=} name Property name of the form under which the control is published.
  31407. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  31408. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  31409. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  31410. * constraint validation.
  31411. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  31412. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  31413. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  31414. * constraint validation.
  31415. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  31416. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31417. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  31418. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31419. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31420. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31421. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31422. * `required` when you want to data-bind to the `required` attribute.
  31423. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31424. * interaction with the input element.
  31425. *
  31426. * @example
  31427. <example name="date-input-directive" module="dateInputExample">
  31428. <file name="index.html">
  31429. <script>
  31430. angular.module('dateInputExample', [])
  31431. .controller('DateController', ['$scope', function($scope) {
  31432. $scope.example = {
  31433. value: new Date(2013, 9, 22)
  31434. };
  31435. }]);
  31436. </script>
  31437. <form name="myForm" ng-controller="DateController as dateCtrl">
  31438. <label for="exampleInput">Pick a date in 2013:</label>
  31439. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  31440. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  31441. <div role="alert">
  31442. <span class="error" ng-show="myForm.input.$error.required">
  31443. Required!</span>
  31444. <span class="error" ng-show="myForm.input.$error.date">
  31445. Not a valid date!</span>
  31446. </div>
  31447. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  31448. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31449. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31450. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31451. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31452. </form>
  31453. </file>
  31454. <file name="protractor.js" type="protractor">
  31455. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  31456. var valid = element(by.binding('myForm.input.$valid'));
  31457. var input = element(by.model('example.value'));
  31458. // currently protractor/webdriver does not support
  31459. // sending keys to all known HTML5 input controls
  31460. // for various browsers (see https://github.com/angular/protractor/issues/562).
  31461. function setInput(val) {
  31462. // set the value of the element and force validation.
  31463. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31464. "ipt.value = '" + val + "';" +
  31465. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31466. browser.executeScript(scr);
  31467. }
  31468. it('should initialize to model', function() {
  31469. expect(value.getText()).toContain('2013-10-22');
  31470. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31471. });
  31472. it('should be invalid if empty', function() {
  31473. setInput('');
  31474. expect(value.getText()).toEqual('value =');
  31475. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31476. });
  31477. it('should be invalid if over max', function() {
  31478. setInput('2015-01-01');
  31479. expect(value.getText()).toContain('');
  31480. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31481. });
  31482. </file>
  31483. </example>
  31484. */
  31485. 'date': createDateInputType('date', DATE_REGEXP,
  31486. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  31487. 'yyyy-MM-dd'),
  31488. /**
  31489. * @ngdoc input
  31490. * @name input[datetime-local]
  31491. *
  31492. * @description
  31493. * Input with datetime validation and transformation. In browsers that do not yet support
  31494. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31495. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  31496. *
  31497. * The model must always be a Date object, otherwise Angular will throw an error.
  31498. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31499. *
  31500. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31501. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31502. *
  31503. * @param {string} ngModel Assignable angular expression to data-bind to.
  31504. * @param {string=} name Property name of the form under which the control is published.
  31505. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31506. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  31507. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  31508. * Note that `min` will also add native HTML5 constraint validation.
  31509. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31510. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  31511. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  31512. * Note that `max` will also add native HTML5 constraint validation.
  31513. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  31514. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31515. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  31516. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31517. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31518. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31519. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31520. * `required` when you want to data-bind to the `required` attribute.
  31521. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31522. * interaction with the input element.
  31523. *
  31524. * @example
  31525. <example name="datetimelocal-input-directive" module="dateExample">
  31526. <file name="index.html">
  31527. <script>
  31528. angular.module('dateExample', [])
  31529. .controller('DateController', ['$scope', function($scope) {
  31530. $scope.example = {
  31531. value: new Date(2010, 11, 28, 14, 57)
  31532. };
  31533. }]);
  31534. </script>
  31535. <form name="myForm" ng-controller="DateController as dateCtrl">
  31536. <label for="exampleInput">Pick a date between in 2013:</label>
  31537. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  31538. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  31539. <div role="alert">
  31540. <span class="error" ng-show="myForm.input.$error.required">
  31541. Required!</span>
  31542. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  31543. Not a valid date!</span>
  31544. </div>
  31545. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  31546. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31547. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31548. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31549. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31550. </form>
  31551. </file>
  31552. <file name="protractor.js" type="protractor">
  31553. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  31554. var valid = element(by.binding('myForm.input.$valid'));
  31555. var input = element(by.model('example.value'));
  31556. // currently protractor/webdriver does not support
  31557. // sending keys to all known HTML5 input controls
  31558. // for various browsers (https://github.com/angular/protractor/issues/562).
  31559. function setInput(val) {
  31560. // set the value of the element and force validation.
  31561. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31562. "ipt.value = '" + val + "';" +
  31563. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31564. browser.executeScript(scr);
  31565. }
  31566. it('should initialize to model', function() {
  31567. expect(value.getText()).toContain('2010-12-28T14:57:00');
  31568. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31569. });
  31570. it('should be invalid if empty', function() {
  31571. setInput('');
  31572. expect(value.getText()).toEqual('value =');
  31573. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31574. });
  31575. it('should be invalid if over max', function() {
  31576. setInput('2015-01-01T23:59:00');
  31577. expect(value.getText()).toContain('');
  31578. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31579. });
  31580. </file>
  31581. </example>
  31582. */
  31583. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  31584. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  31585. 'yyyy-MM-ddTHH:mm:ss.sss'),
  31586. /**
  31587. * @ngdoc input
  31588. * @name input[time]
  31589. *
  31590. * @description
  31591. * Input with time validation and transformation. In browsers that do not yet support
  31592. * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31593. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  31594. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  31595. *
  31596. * The model must always be a Date object, otherwise Angular will throw an error.
  31597. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31598. *
  31599. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31600. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31601. *
  31602. * @param {string} ngModel Assignable angular expression to data-bind to.
  31603. * @param {string=} name Property name of the form under which the control is published.
  31604. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31605. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  31606. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  31607. * native HTML5 constraint validation.
  31608. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31609. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  31610. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  31611. * native HTML5 constraint validation.
  31612. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  31613. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31614. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  31615. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31616. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31617. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31618. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31619. * `required` when you want to data-bind to the `required` attribute.
  31620. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31621. * interaction with the input element.
  31622. *
  31623. * @example
  31624. <example name="time-input-directive" module="timeExample">
  31625. <file name="index.html">
  31626. <script>
  31627. angular.module('timeExample', [])
  31628. .controller('DateController', ['$scope', function($scope) {
  31629. $scope.example = {
  31630. value: new Date(1970, 0, 1, 14, 57, 0)
  31631. };
  31632. }]);
  31633. </script>
  31634. <form name="myForm" ng-controller="DateController as dateCtrl">
  31635. <label for="exampleInput">Pick a time between 8am and 5pm:</label>
  31636. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  31637. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  31638. <div role="alert">
  31639. <span class="error" ng-show="myForm.input.$error.required">
  31640. Required!</span>
  31641. <span class="error" ng-show="myForm.input.$error.time">
  31642. Not a valid date!</span>
  31643. </div>
  31644. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  31645. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31646. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31647. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31648. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31649. </form>
  31650. </file>
  31651. <file name="protractor.js" type="protractor">
  31652. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  31653. var valid = element(by.binding('myForm.input.$valid'));
  31654. var input = element(by.model('example.value'));
  31655. // currently protractor/webdriver does not support
  31656. // sending keys to all known HTML5 input controls
  31657. // for various browsers (https://github.com/angular/protractor/issues/562).
  31658. function setInput(val) {
  31659. // set the value of the element and force validation.
  31660. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31661. "ipt.value = '" + val + "';" +
  31662. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31663. browser.executeScript(scr);
  31664. }
  31665. it('should initialize to model', function() {
  31666. expect(value.getText()).toContain('14:57:00');
  31667. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31668. });
  31669. it('should be invalid if empty', function() {
  31670. setInput('');
  31671. expect(value.getText()).toEqual('value =');
  31672. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31673. });
  31674. it('should be invalid if over max', function() {
  31675. setInput('23:59:00');
  31676. expect(value.getText()).toContain('');
  31677. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31678. });
  31679. </file>
  31680. </example>
  31681. */
  31682. 'time': createDateInputType('time', TIME_REGEXP,
  31683. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  31684. 'HH:mm:ss.sss'),
  31685. /**
  31686. * @ngdoc input
  31687. * @name input[week]
  31688. *
  31689. * @description
  31690. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  31691. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31692. * week format (yyyy-W##), for example: `2013-W02`.
  31693. *
  31694. * The model must always be a Date object, otherwise Angular will throw an error.
  31695. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31696. *
  31697. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31698. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31699. *
  31700. * @param {string} ngModel Assignable angular expression to data-bind to.
  31701. * @param {string=} name Property name of the form under which the control is published.
  31702. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31703. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  31704. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  31705. * native HTML5 constraint validation.
  31706. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31707. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  31708. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  31709. * native HTML5 constraint validation.
  31710. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  31711. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31712. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  31713. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31714. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31715. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31716. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31717. * `required` when you want to data-bind to the `required` attribute.
  31718. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31719. * interaction with the input element.
  31720. *
  31721. * @example
  31722. <example name="week-input-directive" module="weekExample">
  31723. <file name="index.html">
  31724. <script>
  31725. angular.module('weekExample', [])
  31726. .controller('DateController', ['$scope', function($scope) {
  31727. $scope.example = {
  31728. value: new Date(2013, 0, 3)
  31729. };
  31730. }]);
  31731. </script>
  31732. <form name="myForm" ng-controller="DateController as dateCtrl">
  31733. <label>Pick a date between in 2013:
  31734. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  31735. placeholder="YYYY-W##" min="2012-W32"
  31736. max="2013-W52" required />
  31737. </label>
  31738. <div role="alert">
  31739. <span class="error" ng-show="myForm.input.$error.required">
  31740. Required!</span>
  31741. <span class="error" ng-show="myForm.input.$error.week">
  31742. Not a valid date!</span>
  31743. </div>
  31744. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  31745. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31746. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31747. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31748. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31749. </form>
  31750. </file>
  31751. <file name="protractor.js" type="protractor">
  31752. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  31753. var valid = element(by.binding('myForm.input.$valid'));
  31754. var input = element(by.model('example.value'));
  31755. // currently protractor/webdriver does not support
  31756. // sending keys to all known HTML5 input controls
  31757. // for various browsers (https://github.com/angular/protractor/issues/562).
  31758. function setInput(val) {
  31759. // set the value of the element and force validation.
  31760. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31761. "ipt.value = '" + val + "';" +
  31762. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31763. browser.executeScript(scr);
  31764. }
  31765. it('should initialize to model', function() {
  31766. expect(value.getText()).toContain('2013-W01');
  31767. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31768. });
  31769. it('should be invalid if empty', function() {
  31770. setInput('');
  31771. expect(value.getText()).toEqual('value =');
  31772. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31773. });
  31774. it('should be invalid if over max', function() {
  31775. setInput('2015-W01');
  31776. expect(value.getText()).toContain('');
  31777. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31778. });
  31779. </file>
  31780. </example>
  31781. */
  31782. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  31783. /**
  31784. * @ngdoc input
  31785. * @name input[month]
  31786. *
  31787. * @description
  31788. * Input with month validation and transformation. In browsers that do not yet support
  31789. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  31790. * month format (yyyy-MM), for example: `2009-01`.
  31791. *
  31792. * The model must always be a Date object, otherwise Angular will throw an error.
  31793. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  31794. * If the model is not set to the first of the month, the next view to model update will set it
  31795. * to the first of the month.
  31796. *
  31797. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  31798. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  31799. *
  31800. * @param {string} ngModel Assignable angular expression to data-bind to.
  31801. * @param {string=} name Property name of the form under which the control is published.
  31802. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31803. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  31804. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  31805. * native HTML5 constraint validation.
  31806. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31807. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  31808. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  31809. * native HTML5 constraint validation.
  31810. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  31811. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  31812. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  31813. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  31814. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31815. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31816. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31817. * `required` when you want to data-bind to the `required` attribute.
  31818. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31819. * interaction with the input element.
  31820. *
  31821. * @example
  31822. <example name="month-input-directive" module="monthExample">
  31823. <file name="index.html">
  31824. <script>
  31825. angular.module('monthExample', [])
  31826. .controller('DateController', ['$scope', function($scope) {
  31827. $scope.example = {
  31828. value: new Date(2013, 9, 1)
  31829. };
  31830. }]);
  31831. </script>
  31832. <form name="myForm" ng-controller="DateController as dateCtrl">
  31833. <label for="exampleInput">Pick a month in 2013:</label>
  31834. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  31835. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  31836. <div role="alert">
  31837. <span class="error" ng-show="myForm.input.$error.required">
  31838. Required!</span>
  31839. <span class="error" ng-show="myForm.input.$error.month">
  31840. Not a valid month!</span>
  31841. </div>
  31842. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  31843. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31844. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31845. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31846. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31847. </form>
  31848. </file>
  31849. <file name="protractor.js" type="protractor">
  31850. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  31851. var valid = element(by.binding('myForm.input.$valid'));
  31852. var input = element(by.model('example.value'));
  31853. // currently protractor/webdriver does not support
  31854. // sending keys to all known HTML5 input controls
  31855. // for various browsers (https://github.com/angular/protractor/issues/562).
  31856. function setInput(val) {
  31857. // set the value of the element and force validation.
  31858. var scr = "var ipt = document.getElementById('exampleInput'); " +
  31859. "ipt.value = '" + val + "';" +
  31860. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  31861. browser.executeScript(scr);
  31862. }
  31863. it('should initialize to model', function() {
  31864. expect(value.getText()).toContain('2013-10');
  31865. expect(valid.getText()).toContain('myForm.input.$valid = true');
  31866. });
  31867. it('should be invalid if empty', function() {
  31868. setInput('');
  31869. expect(value.getText()).toEqual('value =');
  31870. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31871. });
  31872. it('should be invalid if over max', function() {
  31873. setInput('2015-01');
  31874. expect(value.getText()).toContain('');
  31875. expect(valid.getText()).toContain('myForm.input.$valid = false');
  31876. });
  31877. </file>
  31878. </example>
  31879. */
  31880. 'month': createDateInputType('month', MONTH_REGEXP,
  31881. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  31882. 'yyyy-MM'),
  31883. /**
  31884. * @ngdoc input
  31885. * @name input[number]
  31886. *
  31887. * @description
  31888. * Text input with number validation and transformation. Sets the `number` validation
  31889. * error if not a valid number.
  31890. *
  31891. * <div class="alert alert-warning">
  31892. * The model must always be of type `number` otherwise Angular will throw an error.
  31893. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  31894. * error docs for more information and an example of how to convert your model if necessary.
  31895. * </div>
  31896. *
  31897. * ## Issues with HTML5 constraint validation
  31898. *
  31899. * In browsers that follow the
  31900. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  31901. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  31902. * If a non-number is entered in the input, the browser will report the value as an empty string,
  31903. * which means the view / model values in `ngModel` and subsequently the scope value
  31904. * will also be an empty string.
  31905. *
  31906. *
  31907. * @param {string} ngModel Assignable angular expression to data-bind to.
  31908. * @param {string=} name Property name of the form under which the control is published.
  31909. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  31910. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  31911. * @param {string=} required Sets `required` validation error key if the value is not entered.
  31912. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  31913. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  31914. * `required` when you want to data-bind to the `required` attribute.
  31915. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  31916. * minlength.
  31917. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  31918. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  31919. * any length.
  31920. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  31921. * that contains the regular expression body that will be converted to a regular expression
  31922. * as in the ngPattern directive.
  31923. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  31924. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  31925. * If the expression evaluates to a RegExp object, then this is used directly.
  31926. * If the expression evaluates to a string, then it will be converted to a RegExp
  31927. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  31928. * `new RegExp('^abc$')`.<br />
  31929. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  31930. * start at the index of the last search's match, thus not taking the whole input value into
  31931. * account.
  31932. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  31933. * interaction with the input element.
  31934. *
  31935. * @example
  31936. <example name="number-input-directive" module="numberExample">
  31937. <file name="index.html">
  31938. <script>
  31939. angular.module('numberExample', [])
  31940. .controller('ExampleController', ['$scope', function($scope) {
  31941. $scope.example = {
  31942. value: 12
  31943. };
  31944. }]);
  31945. </script>
  31946. <form name="myForm" ng-controller="ExampleController">
  31947. <label>Number:
  31948. <input type="number" name="input" ng-model="example.value"
  31949. min="0" max="99" required>
  31950. </label>
  31951. <div role="alert">
  31952. <span class="error" ng-show="myForm.input.$error.required">
  31953. Required!</span>
  31954. <span class="error" ng-show="myForm.input.$error.number">
  31955. Not valid number!</span>
  31956. </div>
  31957. <tt>value = {{example.value}}</tt><br/>
  31958. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  31959. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  31960. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  31961. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  31962. </form>
  31963. </file>
  31964. <file name="protractor.js" type="protractor">
  31965. var value = element(by.binding('example.value'));
  31966. var valid = element(by.binding('myForm.input.$valid'));
  31967. var input = element(by.model('example.value'));
  31968. it('should initialize to model', function() {
  31969. expect(value.getText()).toContain('12');
  31970. expect(valid.getText()).toContain('true');
  31971. });
  31972. it('should be invalid if empty', function() {
  31973. input.clear();
  31974. input.sendKeys('');
  31975. expect(value.getText()).toEqual('value =');
  31976. expect(valid.getText()).toContain('false');
  31977. });
  31978. it('should be invalid if over max', function() {
  31979. input.clear();
  31980. input.sendKeys('123');
  31981. expect(value.getText()).toEqual('value =');
  31982. expect(valid.getText()).toContain('false');
  31983. });
  31984. </file>
  31985. </example>
  31986. */
  31987. 'number': numberInputType,
  31988. /**
  31989. * @ngdoc input
  31990. * @name input[url]
  31991. *
  31992. * @description
  31993. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  31994. * valid URL.
  31995. *
  31996. * <div class="alert alert-warning">
  31997. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  31998. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  31999. * the built-in validators (see the {@link guide/forms Forms guide})
  32000. * </div>
  32001. *
  32002. * @param {string} ngModel Assignable angular expression to data-bind to.
  32003. * @param {string=} name Property name of the form under which the control is published.
  32004. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32005. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32006. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32007. * `required` when you want to data-bind to the `required` attribute.
  32008. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32009. * minlength.
  32010. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32011. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  32012. * any length.
  32013. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  32014. * that contains the regular expression body that will be converted to a regular expression
  32015. * as in the ngPattern directive.
  32016. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32017. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32018. * If the expression evaluates to a RegExp object, then this is used directly.
  32019. * If the expression evaluates to a string, then it will be converted to a RegExp
  32020. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32021. * `new RegExp('^abc$')`.<br />
  32022. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32023. * start at the index of the last search's match, thus not taking the whole input value into
  32024. * account.
  32025. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32026. * interaction with the input element.
  32027. *
  32028. * @example
  32029. <example name="url-input-directive" module="urlExample">
  32030. <file name="index.html">
  32031. <script>
  32032. angular.module('urlExample', [])
  32033. .controller('ExampleController', ['$scope', function($scope) {
  32034. $scope.url = {
  32035. text: 'http://google.com'
  32036. };
  32037. }]);
  32038. </script>
  32039. <form name="myForm" ng-controller="ExampleController">
  32040. <label>URL:
  32041. <input type="url" name="input" ng-model="url.text" required>
  32042. <label>
  32043. <div role="alert">
  32044. <span class="error" ng-show="myForm.input.$error.required">
  32045. Required!</span>
  32046. <span class="error" ng-show="myForm.input.$error.url">
  32047. Not valid url!</span>
  32048. </div>
  32049. <tt>text = {{url.text}}</tt><br/>
  32050. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  32051. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  32052. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32053. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32054. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  32055. </form>
  32056. </file>
  32057. <file name="protractor.js" type="protractor">
  32058. var text = element(by.binding('url.text'));
  32059. var valid = element(by.binding('myForm.input.$valid'));
  32060. var input = element(by.model('url.text'));
  32061. it('should initialize to model', function() {
  32062. expect(text.getText()).toContain('http://google.com');
  32063. expect(valid.getText()).toContain('true');
  32064. });
  32065. it('should be invalid if empty', function() {
  32066. input.clear();
  32067. input.sendKeys('');
  32068. expect(text.getText()).toEqual('text =');
  32069. expect(valid.getText()).toContain('false');
  32070. });
  32071. it('should be invalid if not url', function() {
  32072. input.clear();
  32073. input.sendKeys('box');
  32074. expect(valid.getText()).toContain('false');
  32075. });
  32076. </file>
  32077. </example>
  32078. */
  32079. 'url': urlInputType,
  32080. /**
  32081. * @ngdoc input
  32082. * @name input[email]
  32083. *
  32084. * @description
  32085. * Text input with email validation. Sets the `email` validation error key if not a valid email
  32086. * address.
  32087. *
  32088. * <div class="alert alert-warning">
  32089. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  32090. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  32091. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  32092. * </div>
  32093. *
  32094. * @param {string} ngModel Assignable angular expression to data-bind to.
  32095. * @param {string=} name Property name of the form under which the control is published.
  32096. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32097. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32098. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32099. * `required` when you want to data-bind to the `required` attribute.
  32100. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32101. * minlength.
  32102. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32103. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  32104. * any length.
  32105. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  32106. * that contains the regular expression body that will be converted to a regular expression
  32107. * as in the ngPattern directive.
  32108. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32109. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32110. * If the expression evaluates to a RegExp object, then this is used directly.
  32111. * If the expression evaluates to a string, then it will be converted to a RegExp
  32112. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32113. * `new RegExp('^abc$')`.<br />
  32114. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32115. * start at the index of the last search's match, thus not taking the whole input value into
  32116. * account.
  32117. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32118. * interaction with the input element.
  32119. *
  32120. * @example
  32121. <example name="email-input-directive" module="emailExample">
  32122. <file name="index.html">
  32123. <script>
  32124. angular.module('emailExample', [])
  32125. .controller('ExampleController', ['$scope', function($scope) {
  32126. $scope.email = {
  32127. text: 'me@example.com'
  32128. };
  32129. }]);
  32130. </script>
  32131. <form name="myForm" ng-controller="ExampleController">
  32132. <label>Email:
  32133. <input type="email" name="input" ng-model="email.text" required>
  32134. </label>
  32135. <div role="alert">
  32136. <span class="error" ng-show="myForm.input.$error.required">
  32137. Required!</span>
  32138. <span class="error" ng-show="myForm.input.$error.email">
  32139. Not valid email!</span>
  32140. </div>
  32141. <tt>text = {{email.text}}</tt><br/>
  32142. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  32143. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  32144. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32145. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32146. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  32147. </form>
  32148. </file>
  32149. <file name="protractor.js" type="protractor">
  32150. var text = element(by.binding('email.text'));
  32151. var valid = element(by.binding('myForm.input.$valid'));
  32152. var input = element(by.model('email.text'));
  32153. it('should initialize to model', function() {
  32154. expect(text.getText()).toContain('me@example.com');
  32155. expect(valid.getText()).toContain('true');
  32156. });
  32157. it('should be invalid if empty', function() {
  32158. input.clear();
  32159. input.sendKeys('');
  32160. expect(text.getText()).toEqual('text =');
  32161. expect(valid.getText()).toContain('false');
  32162. });
  32163. it('should be invalid if not email', function() {
  32164. input.clear();
  32165. input.sendKeys('xxx');
  32166. expect(valid.getText()).toContain('false');
  32167. });
  32168. </file>
  32169. </example>
  32170. */
  32171. 'email': emailInputType,
  32172. /**
  32173. * @ngdoc input
  32174. * @name input[radio]
  32175. *
  32176. * @description
  32177. * HTML radio button.
  32178. *
  32179. * @param {string} ngModel Assignable angular expression to data-bind to.
  32180. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  32181. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  32182. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  32183. * @param {string=} name Property name of the form under which the control is published.
  32184. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32185. * interaction with the input element.
  32186. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  32187. * is selected. Should be used instead of the `value` attribute if you need
  32188. * a non-string `ngModel` (`boolean`, `array`, ...).
  32189. *
  32190. * @example
  32191. <example name="radio-input-directive" module="radioExample">
  32192. <file name="index.html">
  32193. <script>
  32194. angular.module('radioExample', [])
  32195. .controller('ExampleController', ['$scope', function($scope) {
  32196. $scope.color = {
  32197. name: 'blue'
  32198. };
  32199. $scope.specialValue = {
  32200. "id": "12345",
  32201. "value": "green"
  32202. };
  32203. }]);
  32204. </script>
  32205. <form name="myForm" ng-controller="ExampleController">
  32206. <label>
  32207. <input type="radio" ng-model="color.name" value="red">
  32208. Red
  32209. </label><br/>
  32210. <label>
  32211. <input type="radio" ng-model="color.name" ng-value="specialValue">
  32212. Green
  32213. </label><br/>
  32214. <label>
  32215. <input type="radio" ng-model="color.name" value="blue">
  32216. Blue
  32217. </label><br/>
  32218. <tt>color = {{color.name | json}}</tt><br/>
  32219. </form>
  32220. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  32221. </file>
  32222. <file name="protractor.js" type="protractor">
  32223. it('should change state', function() {
  32224. var color = element(by.binding('color.name'));
  32225. expect(color.getText()).toContain('blue');
  32226. element.all(by.model('color.name')).get(0).click();
  32227. expect(color.getText()).toContain('red');
  32228. });
  32229. </file>
  32230. </example>
  32231. */
  32232. 'radio': radioInputType,
  32233. /**
  32234. * @ngdoc input
  32235. * @name input[checkbox]
  32236. *
  32237. * @description
  32238. * HTML checkbox.
  32239. *
  32240. * @param {string} ngModel Assignable angular expression to data-bind to.
  32241. * @param {string=} name Property name of the form under which the control is published.
  32242. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  32243. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  32244. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32245. * interaction with the input element.
  32246. *
  32247. * @example
  32248. <example name="checkbox-input-directive" module="checkboxExample">
  32249. <file name="index.html">
  32250. <script>
  32251. angular.module('checkboxExample', [])
  32252. .controller('ExampleController', ['$scope', function($scope) {
  32253. $scope.checkboxModel = {
  32254. value1 : true,
  32255. value2 : 'YES'
  32256. };
  32257. }]);
  32258. </script>
  32259. <form name="myForm" ng-controller="ExampleController">
  32260. <label>Value1:
  32261. <input type="checkbox" ng-model="checkboxModel.value1">
  32262. </label><br/>
  32263. <label>Value2:
  32264. <input type="checkbox" ng-model="checkboxModel.value2"
  32265. ng-true-value="'YES'" ng-false-value="'NO'">
  32266. </label><br/>
  32267. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  32268. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  32269. </form>
  32270. </file>
  32271. <file name="protractor.js" type="protractor">
  32272. it('should change state', function() {
  32273. var value1 = element(by.binding('checkboxModel.value1'));
  32274. var value2 = element(by.binding('checkboxModel.value2'));
  32275. expect(value1.getText()).toContain('true');
  32276. expect(value2.getText()).toContain('YES');
  32277. element(by.model('checkboxModel.value1')).click();
  32278. element(by.model('checkboxModel.value2')).click();
  32279. expect(value1.getText()).toContain('false');
  32280. expect(value2.getText()).toContain('NO');
  32281. });
  32282. </file>
  32283. </example>
  32284. */
  32285. 'checkbox': checkboxInputType,
  32286. 'hidden': noop,
  32287. 'button': noop,
  32288. 'submit': noop,
  32289. 'reset': noop,
  32290. 'file': noop
  32291. };
  32292. function stringBasedInputType(ctrl) {
  32293. ctrl.$formatters.push(function(value) {
  32294. return ctrl.$isEmpty(value) ? value : value.toString();
  32295. });
  32296. }
  32297. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32298. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32299. stringBasedInputType(ctrl);
  32300. }
  32301. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32302. var type = lowercase(element[0].type);
  32303. // In composition mode, users are still inputing intermediate text buffer,
  32304. // hold the listener until composition is done.
  32305. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  32306. if (!$sniffer.android) {
  32307. var composing = false;
  32308. element.on('compositionstart', function() {
  32309. composing = true;
  32310. });
  32311. element.on('compositionend', function() {
  32312. composing = false;
  32313. listener();
  32314. });
  32315. }
  32316. var timeout;
  32317. var listener = function(ev) {
  32318. if (timeout) {
  32319. $browser.defer.cancel(timeout);
  32320. timeout = null;
  32321. }
  32322. if (composing) return;
  32323. var value = element.val(),
  32324. event = ev && ev.type;
  32325. // By default we will trim the value
  32326. // If the attribute ng-trim exists we will avoid trimming
  32327. // If input type is 'password', the value is never trimmed
  32328. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  32329. value = trim(value);
  32330. }
  32331. // If a control is suffering from bad input (due to native validators), browsers discard its
  32332. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  32333. // control's value is the same empty value twice in a row.
  32334. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  32335. ctrl.$setViewValue(value, event);
  32336. }
  32337. };
  32338. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  32339. // input event on backspace, delete or cut
  32340. if ($sniffer.hasEvent('input')) {
  32341. element.on('input', listener);
  32342. } else {
  32343. var deferListener = function(ev, input, origValue) {
  32344. if (!timeout) {
  32345. timeout = $browser.defer(function() {
  32346. timeout = null;
  32347. if (!input || input.value !== origValue) {
  32348. listener(ev);
  32349. }
  32350. });
  32351. }
  32352. };
  32353. element.on('keydown', function(event) {
  32354. var key = event.keyCode;
  32355. // ignore
  32356. // command modifiers arrows
  32357. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  32358. deferListener(event, this, this.value);
  32359. });
  32360. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  32361. if ($sniffer.hasEvent('paste')) {
  32362. element.on('paste cut', deferListener);
  32363. }
  32364. }
  32365. // if user paste into input using mouse on older browser
  32366. // or form autocomplete on newer browser, we need "change" event to catch it
  32367. element.on('change', listener);
  32368. // Some native input types (date-family) have the ability to change validity without
  32369. // firing any input/change events.
  32370. // For these event types, when native validators are present and the browser supports the type,
  32371. // check for validity changes on various DOM events.
  32372. if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) {
  32373. element.on(PARTIAL_VALIDATION_EVENTS, function(ev) {
  32374. if (!timeout) {
  32375. var validity = this[VALIDITY_STATE_PROPERTY];
  32376. var origBadInput = validity.badInput;
  32377. var origTypeMismatch = validity.typeMismatch;
  32378. timeout = $browser.defer(function() {
  32379. timeout = null;
  32380. if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) {
  32381. listener(ev);
  32382. }
  32383. });
  32384. }
  32385. });
  32386. }
  32387. ctrl.$render = function() {
  32388. // Workaround for Firefox validation #12102.
  32389. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  32390. if (element.val() !== value) {
  32391. element.val(value);
  32392. }
  32393. };
  32394. }
  32395. function weekParser(isoWeek, existingDate) {
  32396. if (isDate(isoWeek)) {
  32397. return isoWeek;
  32398. }
  32399. if (isString(isoWeek)) {
  32400. WEEK_REGEXP.lastIndex = 0;
  32401. var parts = WEEK_REGEXP.exec(isoWeek);
  32402. if (parts) {
  32403. var year = +parts[1],
  32404. week = +parts[2],
  32405. hours = 0,
  32406. minutes = 0,
  32407. seconds = 0,
  32408. milliseconds = 0,
  32409. firstThurs = getFirstThursdayOfYear(year),
  32410. addDays = (week - 1) * 7;
  32411. if (existingDate) {
  32412. hours = existingDate.getHours();
  32413. minutes = existingDate.getMinutes();
  32414. seconds = existingDate.getSeconds();
  32415. milliseconds = existingDate.getMilliseconds();
  32416. }
  32417. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  32418. }
  32419. }
  32420. return NaN;
  32421. }
  32422. function createDateParser(regexp, mapping) {
  32423. return function(iso, date) {
  32424. var parts, map;
  32425. if (isDate(iso)) {
  32426. return iso;
  32427. }
  32428. if (isString(iso)) {
  32429. // When a date is JSON'ified to wraps itself inside of an extra
  32430. // set of double quotes. This makes the date parsing code unable
  32431. // to match the date string and parse it as a date.
  32432. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  32433. iso = iso.substring(1, iso.length - 1);
  32434. }
  32435. if (ISO_DATE_REGEXP.test(iso)) {
  32436. return new Date(iso);
  32437. }
  32438. regexp.lastIndex = 0;
  32439. parts = regexp.exec(iso);
  32440. if (parts) {
  32441. parts.shift();
  32442. if (date) {
  32443. map = {
  32444. yyyy: date.getFullYear(),
  32445. MM: date.getMonth() + 1,
  32446. dd: date.getDate(),
  32447. HH: date.getHours(),
  32448. mm: date.getMinutes(),
  32449. ss: date.getSeconds(),
  32450. sss: date.getMilliseconds() / 1000
  32451. };
  32452. } else {
  32453. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  32454. }
  32455. forEach(parts, function(part, index) {
  32456. if (index < mapping.length) {
  32457. map[mapping[index]] = +part;
  32458. }
  32459. });
  32460. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  32461. }
  32462. }
  32463. return NaN;
  32464. };
  32465. }
  32466. function createDateInputType(type, regexp, parseDate, format) {
  32467. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  32468. badInputChecker(scope, element, attr, ctrl);
  32469. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32470. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  32471. var previousDate;
  32472. ctrl.$$parserName = type;
  32473. ctrl.$parsers.push(function(value) {
  32474. if (ctrl.$isEmpty(value)) return null;
  32475. if (regexp.test(value)) {
  32476. // Note: We cannot read ctrl.$modelValue, as there might be a different
  32477. // parser/formatter in the processing chain so that the model
  32478. // contains some different data format!
  32479. var parsedDate = parseDate(value, previousDate);
  32480. if (timezone) {
  32481. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  32482. }
  32483. return parsedDate;
  32484. }
  32485. return undefined;
  32486. });
  32487. ctrl.$formatters.push(function(value) {
  32488. if (value && !isDate(value)) {
  32489. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  32490. }
  32491. if (isValidDate(value)) {
  32492. previousDate = value;
  32493. if (previousDate && timezone) {
  32494. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  32495. }
  32496. return $filter('date')(value, format, timezone);
  32497. } else {
  32498. previousDate = null;
  32499. return '';
  32500. }
  32501. });
  32502. if (isDefined(attr.min) || attr.ngMin) {
  32503. var minVal;
  32504. ctrl.$validators.min = function(value) {
  32505. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  32506. };
  32507. attr.$observe('min', function(val) {
  32508. minVal = parseObservedDateValue(val);
  32509. ctrl.$validate();
  32510. });
  32511. }
  32512. if (isDefined(attr.max) || attr.ngMax) {
  32513. var maxVal;
  32514. ctrl.$validators.max = function(value) {
  32515. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  32516. };
  32517. attr.$observe('max', function(val) {
  32518. maxVal = parseObservedDateValue(val);
  32519. ctrl.$validate();
  32520. });
  32521. }
  32522. function isValidDate(value) {
  32523. // Invalid Date: getTime() returns NaN
  32524. return value && !(value.getTime && value.getTime() !== value.getTime());
  32525. }
  32526. function parseObservedDateValue(val) {
  32527. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  32528. }
  32529. };
  32530. }
  32531. function badInputChecker(scope, element, attr, ctrl) {
  32532. var node = element[0];
  32533. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  32534. if (nativeValidation) {
  32535. ctrl.$parsers.push(function(value) {
  32536. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  32537. return validity.badInput || validity.typeMismatch ? undefined : value;
  32538. });
  32539. }
  32540. }
  32541. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32542. badInputChecker(scope, element, attr, ctrl);
  32543. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32544. ctrl.$$parserName = 'number';
  32545. ctrl.$parsers.push(function(value) {
  32546. if (ctrl.$isEmpty(value)) return null;
  32547. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  32548. return undefined;
  32549. });
  32550. ctrl.$formatters.push(function(value) {
  32551. if (!ctrl.$isEmpty(value)) {
  32552. if (!isNumber(value)) {
  32553. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  32554. }
  32555. value = value.toString();
  32556. }
  32557. return value;
  32558. });
  32559. if (isDefined(attr.min) || attr.ngMin) {
  32560. var minVal;
  32561. ctrl.$validators.min = function(value) {
  32562. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  32563. };
  32564. attr.$observe('min', function(val) {
  32565. if (isDefined(val) && !isNumber(val)) {
  32566. val = parseFloat(val, 10);
  32567. }
  32568. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  32569. // TODO(matsko): implement validateLater to reduce number of validations
  32570. ctrl.$validate();
  32571. });
  32572. }
  32573. if (isDefined(attr.max) || attr.ngMax) {
  32574. var maxVal;
  32575. ctrl.$validators.max = function(value) {
  32576. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  32577. };
  32578. attr.$observe('max', function(val) {
  32579. if (isDefined(val) && !isNumber(val)) {
  32580. val = parseFloat(val, 10);
  32581. }
  32582. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  32583. // TODO(matsko): implement validateLater to reduce number of validations
  32584. ctrl.$validate();
  32585. });
  32586. }
  32587. }
  32588. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32589. // Note: no badInputChecker here by purpose as `url` is only a validation
  32590. // in browsers, i.e. we can always read out input.value even if it is not valid!
  32591. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32592. stringBasedInputType(ctrl);
  32593. ctrl.$$parserName = 'url';
  32594. ctrl.$validators.url = function(modelValue, viewValue) {
  32595. var value = modelValue || viewValue;
  32596. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  32597. };
  32598. }
  32599. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  32600. // Note: no badInputChecker here by purpose as `url` is only a validation
  32601. // in browsers, i.e. we can always read out input.value even if it is not valid!
  32602. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  32603. stringBasedInputType(ctrl);
  32604. ctrl.$$parserName = 'email';
  32605. ctrl.$validators.email = function(modelValue, viewValue) {
  32606. var value = modelValue || viewValue;
  32607. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  32608. };
  32609. }
  32610. function radioInputType(scope, element, attr, ctrl) {
  32611. // make the name unique, if not defined
  32612. if (isUndefined(attr.name)) {
  32613. element.attr('name', nextUid());
  32614. }
  32615. var listener = function(ev) {
  32616. if (element[0].checked) {
  32617. ctrl.$setViewValue(attr.value, ev && ev.type);
  32618. }
  32619. };
  32620. element.on('click', listener);
  32621. ctrl.$render = function() {
  32622. var value = attr.value;
  32623. element[0].checked = (value == ctrl.$viewValue);
  32624. };
  32625. attr.$observe('value', ctrl.$render);
  32626. }
  32627. function parseConstantExpr($parse, context, name, expression, fallback) {
  32628. var parseFn;
  32629. if (isDefined(expression)) {
  32630. parseFn = $parse(expression);
  32631. if (!parseFn.constant) {
  32632. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  32633. '`{1}`.', name, expression);
  32634. }
  32635. return parseFn(context);
  32636. }
  32637. return fallback;
  32638. }
  32639. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  32640. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  32641. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  32642. var listener = function(ev) {
  32643. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  32644. };
  32645. element.on('click', listener);
  32646. ctrl.$render = function() {
  32647. element[0].checked = ctrl.$viewValue;
  32648. };
  32649. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  32650. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  32651. // it to a boolean.
  32652. ctrl.$isEmpty = function(value) {
  32653. return value === false;
  32654. };
  32655. ctrl.$formatters.push(function(value) {
  32656. return equals(value, trueValue);
  32657. });
  32658. ctrl.$parsers.push(function(value) {
  32659. return value ? trueValue : falseValue;
  32660. });
  32661. }
  32662. /**
  32663. * @ngdoc directive
  32664. * @name textarea
  32665. * @restrict E
  32666. *
  32667. * @description
  32668. * HTML textarea element control with angular data-binding. The data-binding and validation
  32669. * properties of this element are exactly the same as those of the
  32670. * {@link ng.directive:input input element}.
  32671. *
  32672. * @param {string} ngModel Assignable angular expression to data-bind to.
  32673. * @param {string=} name Property name of the form under which the control is published.
  32674. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32675. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  32676. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  32677. * `required` when you want to data-bind to the `required` attribute.
  32678. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32679. * minlength.
  32680. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32681. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  32682. * length.
  32683. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32684. * does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32685. * If the expression evaluates to a RegExp object, then this is used directly.
  32686. * If the expression evaluates to a string, then it will be converted to a RegExp
  32687. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32688. * `new RegExp('^abc$')`.<br />
  32689. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32690. * start at the index of the last search's match, thus not taking the whole input value into
  32691. * account.
  32692. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32693. * interaction with the input element.
  32694. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  32695. */
  32696. /**
  32697. * @ngdoc directive
  32698. * @name input
  32699. * @restrict E
  32700. *
  32701. * @description
  32702. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  32703. * input state control, and validation.
  32704. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  32705. *
  32706. * <div class="alert alert-warning">
  32707. * **Note:** Not every feature offered is available for all input types.
  32708. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  32709. * </div>
  32710. *
  32711. * @param {string} ngModel Assignable angular expression to data-bind to.
  32712. * @param {string=} name Property name of the form under which the control is published.
  32713. * @param {string=} required Sets `required` validation error key if the value is not entered.
  32714. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  32715. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  32716. * minlength.
  32717. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  32718. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  32719. * length.
  32720. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue}
  32721. * value does not match a RegExp found by evaluating the Angular expression given in the attribute value.
  32722. * If the expression evaluates to a RegExp object, then this is used directly.
  32723. * If the expression evaluates to a string, then it will be converted to a RegExp
  32724. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  32725. * `new RegExp('^abc$')`.<br />
  32726. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  32727. * start at the index of the last search's match, thus not taking the whole input value into
  32728. * account.
  32729. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  32730. * interaction with the input element.
  32731. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  32732. * This parameter is ignored for input[type=password] controls, which will never trim the
  32733. * input.
  32734. *
  32735. * @example
  32736. <example name="input-directive" module="inputExample">
  32737. <file name="index.html">
  32738. <script>
  32739. angular.module('inputExample', [])
  32740. .controller('ExampleController', ['$scope', function($scope) {
  32741. $scope.user = {name: 'guest', last: 'visitor'};
  32742. }]);
  32743. </script>
  32744. <div ng-controller="ExampleController">
  32745. <form name="myForm">
  32746. <label>
  32747. User name:
  32748. <input type="text" name="userName" ng-model="user.name" required>
  32749. </label>
  32750. <div role="alert">
  32751. <span class="error" ng-show="myForm.userName.$error.required">
  32752. Required!</span>
  32753. </div>
  32754. <label>
  32755. Last name:
  32756. <input type="text" name="lastName" ng-model="user.last"
  32757. ng-minlength="3" ng-maxlength="10">
  32758. </label>
  32759. <div role="alert">
  32760. <span class="error" ng-show="myForm.lastName.$error.minlength">
  32761. Too short!</span>
  32762. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  32763. Too long!</span>
  32764. </div>
  32765. </form>
  32766. <hr>
  32767. <tt>user = {{user}}</tt><br/>
  32768. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  32769. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  32770. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  32771. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  32772. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  32773. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  32774. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  32775. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  32776. </div>
  32777. </file>
  32778. <file name="protractor.js" type="protractor">
  32779. var user = element(by.exactBinding('user'));
  32780. var userNameValid = element(by.binding('myForm.userName.$valid'));
  32781. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  32782. var lastNameError = element(by.binding('myForm.lastName.$error'));
  32783. var formValid = element(by.binding('myForm.$valid'));
  32784. var userNameInput = element(by.model('user.name'));
  32785. var userLastInput = element(by.model('user.last'));
  32786. it('should initialize to model', function() {
  32787. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  32788. expect(userNameValid.getText()).toContain('true');
  32789. expect(formValid.getText()).toContain('true');
  32790. });
  32791. it('should be invalid if empty when required', function() {
  32792. userNameInput.clear();
  32793. userNameInput.sendKeys('');
  32794. expect(user.getText()).toContain('{"last":"visitor"}');
  32795. expect(userNameValid.getText()).toContain('false');
  32796. expect(formValid.getText()).toContain('false');
  32797. });
  32798. it('should be valid if empty when min length is set', function() {
  32799. userLastInput.clear();
  32800. userLastInput.sendKeys('');
  32801. expect(user.getText()).toContain('{"name":"guest","last":""}');
  32802. expect(lastNameValid.getText()).toContain('true');
  32803. expect(formValid.getText()).toContain('true');
  32804. });
  32805. it('should be invalid if less than required min length', function() {
  32806. userLastInput.clear();
  32807. userLastInput.sendKeys('xx');
  32808. expect(user.getText()).toContain('{"name":"guest"}');
  32809. expect(lastNameValid.getText()).toContain('false');
  32810. expect(lastNameError.getText()).toContain('minlength');
  32811. expect(formValid.getText()).toContain('false');
  32812. });
  32813. it('should be invalid if longer than max length', function() {
  32814. userLastInput.clear();
  32815. userLastInput.sendKeys('some ridiculously long name');
  32816. expect(user.getText()).toContain('{"name":"guest"}');
  32817. expect(lastNameValid.getText()).toContain('false');
  32818. expect(lastNameError.getText()).toContain('maxlength');
  32819. expect(formValid.getText()).toContain('false');
  32820. });
  32821. </file>
  32822. </example>
  32823. */
  32824. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  32825. function($browser, $sniffer, $filter, $parse) {
  32826. return {
  32827. restrict: 'E',
  32828. require: ['?ngModel'],
  32829. link: {
  32830. pre: function(scope, element, attr, ctrls) {
  32831. if (ctrls[0]) {
  32832. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  32833. $browser, $filter, $parse);
  32834. }
  32835. }
  32836. }
  32837. };
  32838. }];
  32839. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  32840. /**
  32841. * @ngdoc directive
  32842. * @name ngValue
  32843. *
  32844. * @description
  32845. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  32846. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  32847. * the bound value.
  32848. *
  32849. * `ngValue` is useful when dynamically generating lists of radio buttons using
  32850. * {@link ngRepeat `ngRepeat`}, as shown below.
  32851. *
  32852. * Likewise, `ngValue` can be used to generate `<option>` elements for
  32853. * the {@link select `select`} element. In that case however, only strings are supported
  32854. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  32855. * Support for `select` models with non-string values is available via `ngOptions`.
  32856. *
  32857. * @element input
  32858. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  32859. * of the `input` element
  32860. *
  32861. * @example
  32862. <example name="ngValue-directive" module="valueExample">
  32863. <file name="index.html">
  32864. <script>
  32865. angular.module('valueExample', [])
  32866. .controller('ExampleController', ['$scope', function($scope) {
  32867. $scope.names = ['pizza', 'unicorns', 'robots'];
  32868. $scope.my = { favorite: 'unicorns' };
  32869. }]);
  32870. </script>
  32871. <form ng-controller="ExampleController">
  32872. <h2>Which is your favorite?</h2>
  32873. <label ng-repeat="name in names" for="{{name}}">
  32874. {{name}}
  32875. <input type="radio"
  32876. ng-model="my.favorite"
  32877. ng-value="name"
  32878. id="{{name}}"
  32879. name="favorite">
  32880. </label>
  32881. <div>You chose {{my.favorite}}</div>
  32882. </form>
  32883. </file>
  32884. <file name="protractor.js" type="protractor">
  32885. var favorite = element(by.binding('my.favorite'));
  32886. it('should initialize to model', function() {
  32887. expect(favorite.getText()).toContain('unicorns');
  32888. });
  32889. it('should bind the values to the inputs', function() {
  32890. element.all(by.model('my.favorite')).get(0).click();
  32891. expect(favorite.getText()).toContain('pizza');
  32892. });
  32893. </file>
  32894. </example>
  32895. */
  32896. var ngValueDirective = function() {
  32897. return {
  32898. restrict: 'A',
  32899. priority: 100,
  32900. compile: function(tpl, tplAttr) {
  32901. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  32902. return function ngValueConstantLink(scope, elm, attr) {
  32903. attr.$set('value', scope.$eval(attr.ngValue));
  32904. };
  32905. } else {
  32906. return function ngValueLink(scope, elm, attr) {
  32907. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  32908. attr.$set('value', value);
  32909. });
  32910. };
  32911. }
  32912. }
  32913. };
  32914. };
  32915. /**
  32916. * @ngdoc directive
  32917. * @name ngBind
  32918. * @restrict AC
  32919. *
  32920. * @description
  32921. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  32922. * with the value of a given expression, and to update the text content when the value of that
  32923. * expression changes.
  32924. *
  32925. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  32926. * `{{ expression }}` which is similar but less verbose.
  32927. *
  32928. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  32929. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  32930. * element attribute, it makes the bindings invisible to the user while the page is loading.
  32931. *
  32932. * An alternative solution to this problem would be using the
  32933. * {@link ng.directive:ngCloak ngCloak} directive.
  32934. *
  32935. *
  32936. * @element ANY
  32937. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  32938. *
  32939. * @example
  32940. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  32941. <example module="bindExample">
  32942. <file name="index.html">
  32943. <script>
  32944. angular.module('bindExample', [])
  32945. .controller('ExampleController', ['$scope', function($scope) {
  32946. $scope.name = 'Whirled';
  32947. }]);
  32948. </script>
  32949. <div ng-controller="ExampleController">
  32950. <label>Enter name: <input type="text" ng-model="name"></label><br>
  32951. Hello <span ng-bind="name"></span>!
  32952. </div>
  32953. </file>
  32954. <file name="protractor.js" type="protractor">
  32955. it('should check ng-bind', function() {
  32956. var nameInput = element(by.model('name'));
  32957. expect(element(by.binding('name')).getText()).toBe('Whirled');
  32958. nameInput.clear();
  32959. nameInput.sendKeys('world');
  32960. expect(element(by.binding('name')).getText()).toBe('world');
  32961. });
  32962. </file>
  32963. </example>
  32964. */
  32965. var ngBindDirective = ['$compile', function($compile) {
  32966. return {
  32967. restrict: 'AC',
  32968. compile: function ngBindCompile(templateElement) {
  32969. $compile.$$addBindingClass(templateElement);
  32970. return function ngBindLink(scope, element, attr) {
  32971. $compile.$$addBindingInfo(element, attr.ngBind);
  32972. element = element[0];
  32973. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  32974. element.textContent = isUndefined(value) ? '' : value;
  32975. });
  32976. };
  32977. }
  32978. };
  32979. }];
  32980. /**
  32981. * @ngdoc directive
  32982. * @name ngBindTemplate
  32983. *
  32984. * @description
  32985. * The `ngBindTemplate` directive specifies that the element
  32986. * text content should be replaced with the interpolation of the template
  32987. * in the `ngBindTemplate` attribute.
  32988. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  32989. * expressions. This directive is needed since some HTML elements
  32990. * (such as TITLE and OPTION) cannot contain SPAN elements.
  32991. *
  32992. * @element ANY
  32993. * @param {string} ngBindTemplate template of form
  32994. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  32995. *
  32996. * @example
  32997. * Try it here: enter text in text box and watch the greeting change.
  32998. <example module="bindExample">
  32999. <file name="index.html">
  33000. <script>
  33001. angular.module('bindExample', [])
  33002. .controller('ExampleController', ['$scope', function($scope) {
  33003. $scope.salutation = 'Hello';
  33004. $scope.name = 'World';
  33005. }]);
  33006. </script>
  33007. <div ng-controller="ExampleController">
  33008. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  33009. <label>Name: <input type="text" ng-model="name"></label><br>
  33010. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  33011. </div>
  33012. </file>
  33013. <file name="protractor.js" type="protractor">
  33014. it('should check ng-bind', function() {
  33015. var salutationElem = element(by.binding('salutation'));
  33016. var salutationInput = element(by.model('salutation'));
  33017. var nameInput = element(by.model('name'));
  33018. expect(salutationElem.getText()).toBe('Hello World!');
  33019. salutationInput.clear();
  33020. salutationInput.sendKeys('Greetings');
  33021. nameInput.clear();
  33022. nameInput.sendKeys('user');
  33023. expect(salutationElem.getText()).toBe('Greetings user!');
  33024. });
  33025. </file>
  33026. </example>
  33027. */
  33028. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  33029. return {
  33030. compile: function ngBindTemplateCompile(templateElement) {
  33031. $compile.$$addBindingClass(templateElement);
  33032. return function ngBindTemplateLink(scope, element, attr) {
  33033. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  33034. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  33035. element = element[0];
  33036. attr.$observe('ngBindTemplate', function(value) {
  33037. element.textContent = isUndefined(value) ? '' : value;
  33038. });
  33039. };
  33040. }
  33041. };
  33042. }];
  33043. /**
  33044. * @ngdoc directive
  33045. * @name ngBindHtml
  33046. *
  33047. * @description
  33048. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  33049. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  33050. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  33051. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  33052. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  33053. *
  33054. * You may also bypass sanitization for values you know are safe. To do so, bind to
  33055. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  33056. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  33057. *
  33058. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  33059. * will have an exception (instead of an exploit.)
  33060. *
  33061. * @element ANY
  33062. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  33063. *
  33064. * @example
  33065. <example module="bindHtmlExample" deps="angular-sanitize.js">
  33066. <file name="index.html">
  33067. <div ng-controller="ExampleController">
  33068. <p ng-bind-html="myHTML"></p>
  33069. </div>
  33070. </file>
  33071. <file name="script.js">
  33072. angular.module('bindHtmlExample', ['ngSanitize'])
  33073. .controller('ExampleController', ['$scope', function($scope) {
  33074. $scope.myHTML =
  33075. 'I am an <code>HTML</code>string with ' +
  33076. '<a href="#">links!</a> and other <em>stuff</em>';
  33077. }]);
  33078. </file>
  33079. <file name="protractor.js" type="protractor">
  33080. it('should check ng-bind-html', function() {
  33081. expect(element(by.binding('myHTML')).getText()).toBe(
  33082. 'I am an HTMLstring with links! and other stuff');
  33083. });
  33084. </file>
  33085. </example>
  33086. */
  33087. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  33088. return {
  33089. restrict: 'A',
  33090. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  33091. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  33092. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  33093. return (value || '').toString();
  33094. });
  33095. $compile.$$addBindingClass(tElement);
  33096. return function ngBindHtmlLink(scope, element, attr) {
  33097. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  33098. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  33099. // we re-evaluate the expr because we want a TrustedValueHolderType
  33100. // for $sce, not a string
  33101. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  33102. });
  33103. };
  33104. }
  33105. };
  33106. }];
  33107. /**
  33108. * @ngdoc directive
  33109. * @name ngChange
  33110. *
  33111. * @description
  33112. * Evaluate the given expression when the user changes the input.
  33113. * The expression is evaluated immediately, unlike the JavaScript onchange event
  33114. * which only triggers at the end of a change (usually, when the user leaves the
  33115. * form element or presses the return key).
  33116. *
  33117. * The `ngChange` expression is only evaluated when a change in the input value causes
  33118. * a new value to be committed to the model.
  33119. *
  33120. * It will not be evaluated:
  33121. * * if the value returned from the `$parsers` transformation pipeline has not changed
  33122. * * if the input has continued to be invalid since the model will stay `null`
  33123. * * if the model is changed programmatically and not by a change to the input value
  33124. *
  33125. *
  33126. * Note, this directive requires `ngModel` to be present.
  33127. *
  33128. * @element input
  33129. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  33130. * in input value.
  33131. *
  33132. * @example
  33133. * <example name="ngChange-directive" module="changeExample">
  33134. * <file name="index.html">
  33135. * <script>
  33136. * angular.module('changeExample', [])
  33137. * .controller('ExampleController', ['$scope', function($scope) {
  33138. * $scope.counter = 0;
  33139. * $scope.change = function() {
  33140. * $scope.counter++;
  33141. * };
  33142. * }]);
  33143. * </script>
  33144. * <div ng-controller="ExampleController">
  33145. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  33146. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  33147. * <label for="ng-change-example2">Confirmed</label><br />
  33148. * <tt>debug = {{confirmed}}</tt><br/>
  33149. * <tt>counter = {{counter}}</tt><br/>
  33150. * </div>
  33151. * </file>
  33152. * <file name="protractor.js" type="protractor">
  33153. * var counter = element(by.binding('counter'));
  33154. * var debug = element(by.binding('confirmed'));
  33155. *
  33156. * it('should evaluate the expression if changing from view', function() {
  33157. * expect(counter.getText()).toContain('0');
  33158. *
  33159. * element(by.id('ng-change-example1')).click();
  33160. *
  33161. * expect(counter.getText()).toContain('1');
  33162. * expect(debug.getText()).toContain('true');
  33163. * });
  33164. *
  33165. * it('should not evaluate the expression if changing from model', function() {
  33166. * element(by.id('ng-change-example2')).click();
  33167. * expect(counter.getText()).toContain('0');
  33168. * expect(debug.getText()).toContain('true');
  33169. * });
  33170. * </file>
  33171. * </example>
  33172. */
  33173. var ngChangeDirective = valueFn({
  33174. restrict: 'A',
  33175. require: 'ngModel',
  33176. link: function(scope, element, attr, ctrl) {
  33177. ctrl.$viewChangeListeners.push(function() {
  33178. scope.$eval(attr.ngChange);
  33179. });
  33180. }
  33181. });
  33182. function classDirective(name, selector) {
  33183. name = 'ngClass' + name;
  33184. return ['$animate', function($animate) {
  33185. return {
  33186. restrict: 'AC',
  33187. link: function(scope, element, attr) {
  33188. var oldVal;
  33189. scope.$watch(attr[name], ngClassWatchAction, true);
  33190. attr.$observe('class', function(value) {
  33191. ngClassWatchAction(scope.$eval(attr[name]));
  33192. });
  33193. if (name !== 'ngClass') {
  33194. scope.$watch('$index', function($index, old$index) {
  33195. // jshint bitwise: false
  33196. var mod = $index & 1;
  33197. if (mod !== (old$index & 1)) {
  33198. var classes = arrayClasses(scope.$eval(attr[name]));
  33199. mod === selector ?
  33200. addClasses(classes) :
  33201. removeClasses(classes);
  33202. }
  33203. });
  33204. }
  33205. function addClasses(classes) {
  33206. var newClasses = digestClassCounts(classes, 1);
  33207. attr.$addClass(newClasses);
  33208. }
  33209. function removeClasses(classes) {
  33210. var newClasses = digestClassCounts(classes, -1);
  33211. attr.$removeClass(newClasses);
  33212. }
  33213. function digestClassCounts(classes, count) {
  33214. // Use createMap() to prevent class assumptions involving property
  33215. // names in Object.prototype
  33216. var classCounts = element.data('$classCounts') || createMap();
  33217. var classesToUpdate = [];
  33218. forEach(classes, function(className) {
  33219. if (count > 0 || classCounts[className]) {
  33220. classCounts[className] = (classCounts[className] || 0) + count;
  33221. if (classCounts[className] === +(count > 0)) {
  33222. classesToUpdate.push(className);
  33223. }
  33224. }
  33225. });
  33226. element.data('$classCounts', classCounts);
  33227. return classesToUpdate.join(' ');
  33228. }
  33229. function updateClasses(oldClasses, newClasses) {
  33230. var toAdd = arrayDifference(newClasses, oldClasses);
  33231. var toRemove = arrayDifference(oldClasses, newClasses);
  33232. toAdd = digestClassCounts(toAdd, 1);
  33233. toRemove = digestClassCounts(toRemove, -1);
  33234. if (toAdd && toAdd.length) {
  33235. $animate.addClass(element, toAdd);
  33236. }
  33237. if (toRemove && toRemove.length) {
  33238. $animate.removeClass(element, toRemove);
  33239. }
  33240. }
  33241. function ngClassWatchAction(newVal) {
  33242. if (selector === true || scope.$index % 2 === selector) {
  33243. var newClasses = arrayClasses(newVal || []);
  33244. if (!oldVal) {
  33245. addClasses(newClasses);
  33246. } else if (!equals(newVal,oldVal)) {
  33247. var oldClasses = arrayClasses(oldVal);
  33248. updateClasses(oldClasses, newClasses);
  33249. }
  33250. }
  33251. oldVal = shallowCopy(newVal);
  33252. }
  33253. }
  33254. };
  33255. function arrayDifference(tokens1, tokens2) {
  33256. var values = [];
  33257. outer:
  33258. for (var i = 0; i < tokens1.length; i++) {
  33259. var token = tokens1[i];
  33260. for (var j = 0; j < tokens2.length; j++) {
  33261. if (token == tokens2[j]) continue outer;
  33262. }
  33263. values.push(token);
  33264. }
  33265. return values;
  33266. }
  33267. function arrayClasses(classVal) {
  33268. var classes = [];
  33269. if (isArray(classVal)) {
  33270. forEach(classVal, function(v) {
  33271. classes = classes.concat(arrayClasses(v));
  33272. });
  33273. return classes;
  33274. } else if (isString(classVal)) {
  33275. return classVal.split(' ');
  33276. } else if (isObject(classVal)) {
  33277. forEach(classVal, function(v, k) {
  33278. if (v) {
  33279. classes = classes.concat(k.split(' '));
  33280. }
  33281. });
  33282. return classes;
  33283. }
  33284. return classVal;
  33285. }
  33286. }];
  33287. }
  33288. /**
  33289. * @ngdoc directive
  33290. * @name ngClass
  33291. * @restrict AC
  33292. *
  33293. * @description
  33294. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  33295. * an expression that represents all classes to be added.
  33296. *
  33297. * The directive operates in three different ways, depending on which of three types the expression
  33298. * evaluates to:
  33299. *
  33300. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  33301. * names.
  33302. *
  33303. * 2. If the expression evaluates to an object, then for each key-value pair of the
  33304. * object with a truthy value the corresponding key is used as a class name.
  33305. *
  33306. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  33307. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  33308. * to give you more control over what CSS classes appear. See the code below for an example of this.
  33309. *
  33310. *
  33311. * The directive won't add duplicate classes if a particular class was already set.
  33312. *
  33313. * When the expression changes, the previously added classes are removed and only then are the
  33314. * new classes added.
  33315. *
  33316. * @animations
  33317. * | Animation | Occurs |
  33318. * |----------------------------------|-------------------------------------|
  33319. * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element |
  33320. * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element |
  33321. *
  33322. * @element ANY
  33323. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  33324. * of the evaluation can be a string representing space delimited class
  33325. * names, an array, or a map of class names to boolean values. In the case of a map, the
  33326. * names of the properties whose values are truthy will be added as css classes to the
  33327. * element.
  33328. *
  33329. * @example Example that demonstrates basic bindings via ngClass directive.
  33330. <example>
  33331. <file name="index.html">
  33332. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  33333. <label>
  33334. <input type="checkbox" ng-model="deleted">
  33335. deleted (apply "strike" class)
  33336. </label><br>
  33337. <label>
  33338. <input type="checkbox" ng-model="important">
  33339. important (apply "bold" class)
  33340. </label><br>
  33341. <label>
  33342. <input type="checkbox" ng-model="error">
  33343. error (apply "has-error" class)
  33344. </label>
  33345. <hr>
  33346. <p ng-class="style">Using String Syntax</p>
  33347. <input type="text" ng-model="style"
  33348. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  33349. <hr>
  33350. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  33351. <input ng-model="style1"
  33352. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  33353. <input ng-model="style2"
  33354. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  33355. <input ng-model="style3"
  33356. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  33357. <hr>
  33358. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  33359. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  33360. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  33361. </file>
  33362. <file name="style.css">
  33363. .strike {
  33364. text-decoration: line-through;
  33365. }
  33366. .bold {
  33367. font-weight: bold;
  33368. }
  33369. .red {
  33370. color: red;
  33371. }
  33372. .has-error {
  33373. color: red;
  33374. background-color: yellow;
  33375. }
  33376. .orange {
  33377. color: orange;
  33378. }
  33379. </file>
  33380. <file name="protractor.js" type="protractor">
  33381. var ps = element.all(by.css('p'));
  33382. it('should let you toggle the class', function() {
  33383. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  33384. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  33385. element(by.model('important')).click();
  33386. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  33387. element(by.model('error')).click();
  33388. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  33389. });
  33390. it('should let you toggle string example', function() {
  33391. expect(ps.get(1).getAttribute('class')).toBe('');
  33392. element(by.model('style')).clear();
  33393. element(by.model('style')).sendKeys('red');
  33394. expect(ps.get(1).getAttribute('class')).toBe('red');
  33395. });
  33396. it('array example should have 3 classes', function() {
  33397. expect(ps.get(2).getAttribute('class')).toBe('');
  33398. element(by.model('style1')).sendKeys('bold');
  33399. element(by.model('style2')).sendKeys('strike');
  33400. element(by.model('style3')).sendKeys('red');
  33401. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  33402. });
  33403. it('array with map example should have 2 classes', function() {
  33404. expect(ps.last().getAttribute('class')).toBe('');
  33405. element(by.model('style4')).sendKeys('bold');
  33406. element(by.model('warning')).click();
  33407. expect(ps.last().getAttribute('class')).toBe('bold orange');
  33408. });
  33409. </file>
  33410. </example>
  33411. ## Animations
  33412. The example below demonstrates how to perform animations using ngClass.
  33413. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  33414. <file name="index.html">
  33415. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  33416. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  33417. <br>
  33418. <span class="base-class" ng-class="myVar">Sample Text</span>
  33419. </file>
  33420. <file name="style.css">
  33421. .base-class {
  33422. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  33423. }
  33424. .base-class.my-class {
  33425. color: red;
  33426. font-size:3em;
  33427. }
  33428. </file>
  33429. <file name="protractor.js" type="protractor">
  33430. it('should check ng-class', function() {
  33431. expect(element(by.css('.base-class')).getAttribute('class')).not.
  33432. toMatch(/my-class/);
  33433. element(by.id('setbtn')).click();
  33434. expect(element(by.css('.base-class')).getAttribute('class')).
  33435. toMatch(/my-class/);
  33436. element(by.id('clearbtn')).click();
  33437. expect(element(by.css('.base-class')).getAttribute('class')).not.
  33438. toMatch(/my-class/);
  33439. });
  33440. </file>
  33441. </example>
  33442. ## ngClass and pre-existing CSS3 Transitions/Animations
  33443. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  33444. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  33445. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  33446. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  33447. {@link $animate#removeClass $animate.removeClass}.
  33448. */
  33449. var ngClassDirective = classDirective('', true);
  33450. /**
  33451. * @ngdoc directive
  33452. * @name ngClassOdd
  33453. * @restrict AC
  33454. *
  33455. * @description
  33456. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  33457. * {@link ng.directive:ngClass ngClass}, except they work in
  33458. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  33459. *
  33460. * This directive can be applied only within the scope of an
  33461. * {@link ng.directive:ngRepeat ngRepeat}.
  33462. *
  33463. * @element ANY
  33464. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  33465. * of the evaluation can be a string representing space delimited class names or an array.
  33466. *
  33467. * @example
  33468. <example>
  33469. <file name="index.html">
  33470. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  33471. <li ng-repeat="name in names">
  33472. <span ng-class-odd="'odd'" ng-class-even="'even'">
  33473. {{name}}
  33474. </span>
  33475. </li>
  33476. </ol>
  33477. </file>
  33478. <file name="style.css">
  33479. .odd {
  33480. color: red;
  33481. }
  33482. .even {
  33483. color: blue;
  33484. }
  33485. </file>
  33486. <file name="protractor.js" type="protractor">
  33487. it('should check ng-class-odd and ng-class-even', function() {
  33488. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  33489. toMatch(/odd/);
  33490. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  33491. toMatch(/even/);
  33492. });
  33493. </file>
  33494. </example>
  33495. */
  33496. var ngClassOddDirective = classDirective('Odd', 0);
  33497. /**
  33498. * @ngdoc directive
  33499. * @name ngClassEven
  33500. * @restrict AC
  33501. *
  33502. * @description
  33503. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  33504. * {@link ng.directive:ngClass ngClass}, except they work in
  33505. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  33506. *
  33507. * This directive can be applied only within the scope of an
  33508. * {@link ng.directive:ngRepeat ngRepeat}.
  33509. *
  33510. * @element ANY
  33511. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  33512. * result of the evaluation can be a string representing space delimited class names or an array.
  33513. *
  33514. * @example
  33515. <example>
  33516. <file name="index.html">
  33517. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  33518. <li ng-repeat="name in names">
  33519. <span ng-class-odd="'odd'" ng-class-even="'even'">
  33520. {{name}} &nbsp; &nbsp; &nbsp;
  33521. </span>
  33522. </li>
  33523. </ol>
  33524. </file>
  33525. <file name="style.css">
  33526. .odd {
  33527. color: red;
  33528. }
  33529. .even {
  33530. color: blue;
  33531. }
  33532. </file>
  33533. <file name="protractor.js" type="protractor">
  33534. it('should check ng-class-odd and ng-class-even', function() {
  33535. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  33536. toMatch(/odd/);
  33537. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  33538. toMatch(/even/);
  33539. });
  33540. </file>
  33541. </example>
  33542. */
  33543. var ngClassEvenDirective = classDirective('Even', 1);
  33544. /**
  33545. * @ngdoc directive
  33546. * @name ngCloak
  33547. * @restrict AC
  33548. *
  33549. * @description
  33550. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  33551. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  33552. * directive to avoid the undesirable flicker effect caused by the html template display.
  33553. *
  33554. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  33555. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  33556. * of the browser view.
  33557. *
  33558. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  33559. * `angular.min.js`.
  33560. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  33561. *
  33562. * ```css
  33563. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  33564. * display: none !important;
  33565. * }
  33566. * ```
  33567. *
  33568. * When this css rule is loaded by the browser, all html elements (including their children) that
  33569. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  33570. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  33571. * the compiled element visible.
  33572. *
  33573. * For the best result, the `angular.js` script must be loaded in the head section of the html
  33574. * document; alternatively, the css rule above must be included in the external stylesheet of the
  33575. * application.
  33576. *
  33577. * @element ANY
  33578. *
  33579. * @example
  33580. <example>
  33581. <file name="index.html">
  33582. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  33583. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  33584. </file>
  33585. <file name="protractor.js" type="protractor">
  33586. it('should remove the template directive and css class', function() {
  33587. expect($('#template1').getAttribute('ng-cloak')).
  33588. toBeNull();
  33589. expect($('#template2').getAttribute('ng-cloak')).
  33590. toBeNull();
  33591. });
  33592. </file>
  33593. </example>
  33594. *
  33595. */
  33596. var ngCloakDirective = ngDirective({
  33597. compile: function(element, attr) {
  33598. attr.$set('ngCloak', undefined);
  33599. element.removeClass('ng-cloak');
  33600. }
  33601. });
  33602. /**
  33603. * @ngdoc directive
  33604. * @name ngController
  33605. *
  33606. * @description
  33607. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  33608. * supports the principles behind the Model-View-Controller design pattern.
  33609. *
  33610. * MVC components in angular:
  33611. *
  33612. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  33613. * are accessed through bindings.
  33614. * * View — The template (HTML with data bindings) that is rendered into the View.
  33615. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  33616. * logic behind the application to decorate the scope with functions and values
  33617. *
  33618. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  33619. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  33620. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  33621. * and executed twice.
  33622. *
  33623. * @element ANY
  33624. * @scope
  33625. * @priority 500
  33626. * @param {expression} ngController Name of a constructor function registered with the current
  33627. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  33628. * that on the current scope evaluates to a constructor function.
  33629. *
  33630. * The controller instance can be published into a scope property by specifying
  33631. * `ng-controller="as propertyName"`.
  33632. *
  33633. * If the current `$controllerProvider` is configured to use globals (via
  33634. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  33635. * also be the name of a globally accessible constructor function (not recommended).
  33636. *
  33637. * @example
  33638. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  33639. * greeting are methods declared on the controller (see source tab). These methods can
  33640. * easily be called from the angular markup. Any changes to the data are automatically reflected
  33641. * in the View without the need for a manual update.
  33642. *
  33643. * Two different declaration styles are included below:
  33644. *
  33645. * * one binds methods and properties directly onto the controller using `this`:
  33646. * `ng-controller="SettingsController1 as settings"`
  33647. * * one injects `$scope` into the controller:
  33648. * `ng-controller="SettingsController2"`
  33649. *
  33650. * The second option is more common in the Angular community, and is generally used in boilerplates
  33651. * and in this guide. However, there are advantages to binding properties directly to the controller
  33652. * and avoiding scope.
  33653. *
  33654. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  33655. * multiple controllers apply to an element.
  33656. * * If you are writing your controllers as classes you have easier access to the properties and
  33657. * methods, which will appear on the scope, from inside the controller code.
  33658. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  33659. * inheritance masking primitives.
  33660. *
  33661. * This example demonstrates the `controller as` syntax.
  33662. *
  33663. * <example name="ngControllerAs" module="controllerAsExample">
  33664. * <file name="index.html">
  33665. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  33666. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  33667. * <button ng-click="settings.greet()">greet</button><br/>
  33668. * Contact:
  33669. * <ul>
  33670. * <li ng-repeat="contact in settings.contacts">
  33671. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  33672. * <option>phone</option>
  33673. * <option>email</option>
  33674. * </select>
  33675. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  33676. * <button ng-click="settings.clearContact(contact)">clear</button>
  33677. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  33678. * </li>
  33679. * <li><button ng-click="settings.addContact()">add</button></li>
  33680. * </ul>
  33681. * </div>
  33682. * </file>
  33683. * <file name="app.js">
  33684. * angular.module('controllerAsExample', [])
  33685. * .controller('SettingsController1', SettingsController1);
  33686. *
  33687. * function SettingsController1() {
  33688. * this.name = "John Smith";
  33689. * this.contacts = [
  33690. * {type: 'phone', value: '408 555 1212'},
  33691. * {type: 'email', value: 'john.smith@example.org'} ];
  33692. * }
  33693. *
  33694. * SettingsController1.prototype.greet = function() {
  33695. * alert(this.name);
  33696. * };
  33697. *
  33698. * SettingsController1.prototype.addContact = function() {
  33699. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  33700. * };
  33701. *
  33702. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  33703. * var index = this.contacts.indexOf(contactToRemove);
  33704. * this.contacts.splice(index, 1);
  33705. * };
  33706. *
  33707. * SettingsController1.prototype.clearContact = function(contact) {
  33708. * contact.type = 'phone';
  33709. * contact.value = '';
  33710. * };
  33711. * </file>
  33712. * <file name="protractor.js" type="protractor">
  33713. * it('should check controller as', function() {
  33714. * var container = element(by.id('ctrl-as-exmpl'));
  33715. * expect(container.element(by.model('settings.name'))
  33716. * .getAttribute('value')).toBe('John Smith');
  33717. *
  33718. * var firstRepeat =
  33719. * container.element(by.repeater('contact in settings.contacts').row(0));
  33720. * var secondRepeat =
  33721. * container.element(by.repeater('contact in settings.contacts').row(1));
  33722. *
  33723. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33724. * .toBe('408 555 1212');
  33725. *
  33726. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  33727. * .toBe('john.smith@example.org');
  33728. *
  33729. * firstRepeat.element(by.buttonText('clear')).click();
  33730. *
  33731. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33732. * .toBe('');
  33733. *
  33734. * container.element(by.buttonText('add')).click();
  33735. *
  33736. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  33737. * .element(by.model('contact.value'))
  33738. * .getAttribute('value'))
  33739. * .toBe('yourname@example.org');
  33740. * });
  33741. * </file>
  33742. * </example>
  33743. *
  33744. * This example demonstrates the "attach to `$scope`" style of controller.
  33745. *
  33746. * <example name="ngController" module="controllerExample">
  33747. * <file name="index.html">
  33748. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  33749. * <label>Name: <input type="text" ng-model="name"/></label>
  33750. * <button ng-click="greet()">greet</button><br/>
  33751. * Contact:
  33752. * <ul>
  33753. * <li ng-repeat="contact in contacts">
  33754. * <select ng-model="contact.type" id="select_{{$index}}">
  33755. * <option>phone</option>
  33756. * <option>email</option>
  33757. * </select>
  33758. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  33759. * <button ng-click="clearContact(contact)">clear</button>
  33760. * <button ng-click="removeContact(contact)">X</button>
  33761. * </li>
  33762. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  33763. * </ul>
  33764. * </div>
  33765. * </file>
  33766. * <file name="app.js">
  33767. * angular.module('controllerExample', [])
  33768. * .controller('SettingsController2', ['$scope', SettingsController2]);
  33769. *
  33770. * function SettingsController2($scope) {
  33771. * $scope.name = "John Smith";
  33772. * $scope.contacts = [
  33773. * {type:'phone', value:'408 555 1212'},
  33774. * {type:'email', value:'john.smith@example.org'} ];
  33775. *
  33776. * $scope.greet = function() {
  33777. * alert($scope.name);
  33778. * };
  33779. *
  33780. * $scope.addContact = function() {
  33781. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  33782. * };
  33783. *
  33784. * $scope.removeContact = function(contactToRemove) {
  33785. * var index = $scope.contacts.indexOf(contactToRemove);
  33786. * $scope.contacts.splice(index, 1);
  33787. * };
  33788. *
  33789. * $scope.clearContact = function(contact) {
  33790. * contact.type = 'phone';
  33791. * contact.value = '';
  33792. * };
  33793. * }
  33794. * </file>
  33795. * <file name="protractor.js" type="protractor">
  33796. * it('should check controller', function() {
  33797. * var container = element(by.id('ctrl-exmpl'));
  33798. *
  33799. * expect(container.element(by.model('name'))
  33800. * .getAttribute('value')).toBe('John Smith');
  33801. *
  33802. * var firstRepeat =
  33803. * container.element(by.repeater('contact in contacts').row(0));
  33804. * var secondRepeat =
  33805. * container.element(by.repeater('contact in contacts').row(1));
  33806. *
  33807. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33808. * .toBe('408 555 1212');
  33809. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  33810. * .toBe('john.smith@example.org');
  33811. *
  33812. * firstRepeat.element(by.buttonText('clear')).click();
  33813. *
  33814. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  33815. * .toBe('');
  33816. *
  33817. * container.element(by.buttonText('add')).click();
  33818. *
  33819. * expect(container.element(by.repeater('contact in contacts').row(2))
  33820. * .element(by.model('contact.value'))
  33821. * .getAttribute('value'))
  33822. * .toBe('yourname@example.org');
  33823. * });
  33824. * </file>
  33825. *</example>
  33826. */
  33827. var ngControllerDirective = [function() {
  33828. return {
  33829. restrict: 'A',
  33830. scope: true,
  33831. controller: '@',
  33832. priority: 500
  33833. };
  33834. }];
  33835. /**
  33836. * @ngdoc directive
  33837. * @name ngCsp
  33838. *
  33839. * @element html
  33840. * @description
  33841. *
  33842. * Angular has some features that can break certain
  33843. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  33844. *
  33845. * If you intend to implement these rules then you must tell Angular not to use these features.
  33846. *
  33847. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  33848. *
  33849. *
  33850. * The following rules affect Angular:
  33851. *
  33852. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  33853. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  33854. * increase in the speed of evaluating Angular expressions.
  33855. *
  33856. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  33857. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  33858. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  33859. * `angular-csp.css` in your HTML manually.
  33860. *
  33861. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  33862. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  33863. * however, triggers a CSP error to be logged in the console:
  33864. *
  33865. * ```
  33866. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  33867. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  33868. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  33869. * ```
  33870. *
  33871. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  33872. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  33873. * the `angular.js` file.
  33874. *
  33875. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  33876. *
  33877. * You can specify which of the CSP related Angular features should be deactivated by providing
  33878. * a value for the `ng-csp` attribute. The options are as follows:
  33879. *
  33880. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  33881. *
  33882. * * no-unsafe-eval: this stops Angular from optimizing $parse with unsafe eval of strings
  33883. *
  33884. * You can use these values in the following combinations:
  33885. *
  33886. *
  33887. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  33888. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  33889. * of Angular.
  33890. *
  33891. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  33892. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  33893. * of Angular.
  33894. *
  33895. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  33896. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  33897. *
  33898. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  33899. * run eval - no automatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  33900. *
  33901. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  33902. * styles nor use eval, which is the same as an empty: ng-csp.
  33903. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  33904. *
  33905. * @example
  33906. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  33907. ```html
  33908. <!doctype html>
  33909. <html ng-app ng-csp>
  33910. ...
  33911. ...
  33912. </html>
  33913. ```
  33914. * @example
  33915. // Note: the suffix `.csp` in the example name triggers
  33916. // csp mode in our http server!
  33917. <example name="example.csp" module="cspExample" ng-csp="true">
  33918. <file name="index.html">
  33919. <div ng-controller="MainController as ctrl">
  33920. <div>
  33921. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  33922. <span id="counter">
  33923. {{ctrl.counter}}
  33924. </span>
  33925. </div>
  33926. <div>
  33927. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  33928. <span id="evilError">
  33929. {{ctrl.evilError}}
  33930. </span>
  33931. </div>
  33932. </div>
  33933. </file>
  33934. <file name="script.js">
  33935. angular.module('cspExample', [])
  33936. .controller('MainController', function() {
  33937. this.counter = 0;
  33938. this.inc = function() {
  33939. this.counter++;
  33940. };
  33941. this.evil = function() {
  33942. // jshint evil:true
  33943. try {
  33944. eval('1+2');
  33945. } catch (e) {
  33946. this.evilError = e.message;
  33947. }
  33948. };
  33949. });
  33950. </file>
  33951. <file name="protractor.js" type="protractor">
  33952. var util, webdriver;
  33953. var incBtn = element(by.id('inc'));
  33954. var counter = element(by.id('counter'));
  33955. var evilBtn = element(by.id('evil'));
  33956. var evilError = element(by.id('evilError'));
  33957. function getAndClearSevereErrors() {
  33958. return browser.manage().logs().get('browser').then(function(browserLog) {
  33959. return browserLog.filter(function(logEntry) {
  33960. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  33961. });
  33962. });
  33963. }
  33964. function clearErrors() {
  33965. getAndClearSevereErrors();
  33966. }
  33967. function expectNoErrors() {
  33968. getAndClearSevereErrors().then(function(filteredLog) {
  33969. expect(filteredLog.length).toEqual(0);
  33970. if (filteredLog.length) {
  33971. console.log('browser console errors: ' + util.inspect(filteredLog));
  33972. }
  33973. });
  33974. }
  33975. function expectError(regex) {
  33976. getAndClearSevereErrors().then(function(filteredLog) {
  33977. var found = false;
  33978. filteredLog.forEach(function(log) {
  33979. if (log.message.match(regex)) {
  33980. found = true;
  33981. }
  33982. });
  33983. if (!found) {
  33984. throw new Error('expected an error that matches ' + regex);
  33985. }
  33986. });
  33987. }
  33988. beforeEach(function() {
  33989. util = require('util');
  33990. webdriver = require('protractor/node_modules/selenium-webdriver');
  33991. });
  33992. // For now, we only test on Chrome,
  33993. // as Safari does not load the page with Protractor's injected scripts,
  33994. // and Firefox webdriver always disables content security policy (#6358)
  33995. if (browser.params.browser !== 'chrome') {
  33996. return;
  33997. }
  33998. it('should not report errors when the page is loaded', function() {
  33999. // clear errors so we are not dependent on previous tests
  34000. clearErrors();
  34001. // Need to reload the page as the page is already loaded when
  34002. // we come here
  34003. browser.driver.getCurrentUrl().then(function(url) {
  34004. browser.get(url);
  34005. });
  34006. expectNoErrors();
  34007. });
  34008. it('should evaluate expressions', function() {
  34009. expect(counter.getText()).toEqual('0');
  34010. incBtn.click();
  34011. expect(counter.getText()).toEqual('1');
  34012. expectNoErrors();
  34013. });
  34014. it('should throw and report an error when using "eval"', function() {
  34015. evilBtn.click();
  34016. expect(evilError.getText()).toMatch(/Content Security Policy/);
  34017. expectError(/Content Security Policy/);
  34018. });
  34019. </file>
  34020. </example>
  34021. */
  34022. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  34023. // bootstrap the system (before $parse is instantiated), for this reason we just have
  34024. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  34025. /**
  34026. * @ngdoc directive
  34027. * @name ngClick
  34028. *
  34029. * @description
  34030. * The ngClick directive allows you to specify custom behavior when
  34031. * an element is clicked.
  34032. *
  34033. * @element ANY
  34034. * @priority 0
  34035. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  34036. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  34037. *
  34038. * @example
  34039. <example>
  34040. <file name="index.html">
  34041. <button ng-click="count = count + 1" ng-init="count=0">
  34042. Increment
  34043. </button>
  34044. <span>
  34045. count: {{count}}
  34046. </span>
  34047. </file>
  34048. <file name="protractor.js" type="protractor">
  34049. it('should check ng-click', function() {
  34050. expect(element(by.binding('count')).getText()).toMatch('0');
  34051. element(by.css('button')).click();
  34052. expect(element(by.binding('count')).getText()).toMatch('1');
  34053. });
  34054. </file>
  34055. </example>
  34056. */
  34057. /*
  34058. * A collection of directives that allows creation of custom event handlers that are defined as
  34059. * angular expressions and are compiled and executed within the current scope.
  34060. */
  34061. var ngEventDirectives = {};
  34062. // For events that might fire synchronously during DOM manipulation
  34063. // we need to execute their event handlers asynchronously using $evalAsync,
  34064. // so that they are not executed in an inconsistent state.
  34065. var forceAsyncEvents = {
  34066. 'blur': true,
  34067. 'focus': true
  34068. };
  34069. forEach(
  34070. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  34071. function(eventName) {
  34072. var directiveName = directiveNormalize('ng-' + eventName);
  34073. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  34074. return {
  34075. restrict: 'A',
  34076. compile: function($element, attr) {
  34077. // We expose the powerful $event object on the scope that provides access to the Window,
  34078. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  34079. // checks at the cost of speed since event handler expressions are not executed as
  34080. // frequently as regular change detection.
  34081. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  34082. return function ngEventHandler(scope, element) {
  34083. element.on(eventName, function(event) {
  34084. var callback = function() {
  34085. fn(scope, {$event:event});
  34086. };
  34087. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  34088. scope.$evalAsync(callback);
  34089. } else {
  34090. scope.$apply(callback);
  34091. }
  34092. });
  34093. };
  34094. }
  34095. };
  34096. }];
  34097. }
  34098. );
  34099. /**
  34100. * @ngdoc directive
  34101. * @name ngDblclick
  34102. *
  34103. * @description
  34104. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  34105. *
  34106. * @element ANY
  34107. * @priority 0
  34108. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  34109. * a dblclick. (The Event object is available as `$event`)
  34110. *
  34111. * @example
  34112. <example>
  34113. <file name="index.html">
  34114. <button ng-dblclick="count = count + 1" ng-init="count=0">
  34115. Increment (on double click)
  34116. </button>
  34117. count: {{count}}
  34118. </file>
  34119. </example>
  34120. */
  34121. /**
  34122. * @ngdoc directive
  34123. * @name ngMousedown
  34124. *
  34125. * @description
  34126. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  34127. *
  34128. * @element ANY
  34129. * @priority 0
  34130. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  34131. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  34132. *
  34133. * @example
  34134. <example>
  34135. <file name="index.html">
  34136. <button ng-mousedown="count = count + 1" ng-init="count=0">
  34137. Increment (on mouse down)
  34138. </button>
  34139. count: {{count}}
  34140. </file>
  34141. </example>
  34142. */
  34143. /**
  34144. * @ngdoc directive
  34145. * @name ngMouseup
  34146. *
  34147. * @description
  34148. * Specify custom behavior on mouseup event.
  34149. *
  34150. * @element ANY
  34151. * @priority 0
  34152. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  34153. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  34154. *
  34155. * @example
  34156. <example>
  34157. <file name="index.html">
  34158. <button ng-mouseup="count = count + 1" ng-init="count=0">
  34159. Increment (on mouse up)
  34160. </button>
  34161. count: {{count}}
  34162. </file>
  34163. </example>
  34164. */
  34165. /**
  34166. * @ngdoc directive
  34167. * @name ngMouseover
  34168. *
  34169. * @description
  34170. * Specify custom behavior on mouseover event.
  34171. *
  34172. * @element ANY
  34173. * @priority 0
  34174. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  34175. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  34176. *
  34177. * @example
  34178. <example>
  34179. <file name="index.html">
  34180. <button ng-mouseover="count = count + 1" ng-init="count=0">
  34181. Increment (when mouse is over)
  34182. </button>
  34183. count: {{count}}
  34184. </file>
  34185. </example>
  34186. */
  34187. /**
  34188. * @ngdoc directive
  34189. * @name ngMouseenter
  34190. *
  34191. * @description
  34192. * Specify custom behavior on mouseenter event.
  34193. *
  34194. * @element ANY
  34195. * @priority 0
  34196. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  34197. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  34198. *
  34199. * @example
  34200. <example>
  34201. <file name="index.html">
  34202. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  34203. Increment (when mouse enters)
  34204. </button>
  34205. count: {{count}}
  34206. </file>
  34207. </example>
  34208. */
  34209. /**
  34210. * @ngdoc directive
  34211. * @name ngMouseleave
  34212. *
  34213. * @description
  34214. * Specify custom behavior on mouseleave event.
  34215. *
  34216. * @element ANY
  34217. * @priority 0
  34218. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  34219. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  34220. *
  34221. * @example
  34222. <example>
  34223. <file name="index.html">
  34224. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  34225. Increment (when mouse leaves)
  34226. </button>
  34227. count: {{count}}
  34228. </file>
  34229. </example>
  34230. */
  34231. /**
  34232. * @ngdoc directive
  34233. * @name ngMousemove
  34234. *
  34235. * @description
  34236. * Specify custom behavior on mousemove event.
  34237. *
  34238. * @element ANY
  34239. * @priority 0
  34240. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  34241. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  34242. *
  34243. * @example
  34244. <example>
  34245. <file name="index.html">
  34246. <button ng-mousemove="count = count + 1" ng-init="count=0">
  34247. Increment (when mouse moves)
  34248. </button>
  34249. count: {{count}}
  34250. </file>
  34251. </example>
  34252. */
  34253. /**
  34254. * @ngdoc directive
  34255. * @name ngKeydown
  34256. *
  34257. * @description
  34258. * Specify custom behavior on keydown event.
  34259. *
  34260. * @element ANY
  34261. * @priority 0
  34262. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  34263. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  34264. *
  34265. * @example
  34266. <example>
  34267. <file name="index.html">
  34268. <input ng-keydown="count = count + 1" ng-init="count=0">
  34269. key down count: {{count}}
  34270. </file>
  34271. </example>
  34272. */
  34273. /**
  34274. * @ngdoc directive
  34275. * @name ngKeyup
  34276. *
  34277. * @description
  34278. * Specify custom behavior on keyup event.
  34279. *
  34280. * @element ANY
  34281. * @priority 0
  34282. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  34283. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  34284. *
  34285. * @example
  34286. <example>
  34287. <file name="index.html">
  34288. <p>Typing in the input box below updates the key count</p>
  34289. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  34290. <p>Typing in the input box below updates the keycode</p>
  34291. <input ng-keyup="event=$event">
  34292. <p>event keyCode: {{ event.keyCode }}</p>
  34293. <p>event altKey: {{ event.altKey }}</p>
  34294. </file>
  34295. </example>
  34296. */
  34297. /**
  34298. * @ngdoc directive
  34299. * @name ngKeypress
  34300. *
  34301. * @description
  34302. * Specify custom behavior on keypress event.
  34303. *
  34304. * @element ANY
  34305. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  34306. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  34307. * and can be interrogated for keyCode, altKey, etc.)
  34308. *
  34309. * @example
  34310. <example>
  34311. <file name="index.html">
  34312. <input ng-keypress="count = count + 1" ng-init="count=0">
  34313. key press count: {{count}}
  34314. </file>
  34315. </example>
  34316. */
  34317. /**
  34318. * @ngdoc directive
  34319. * @name ngSubmit
  34320. *
  34321. * @description
  34322. * Enables binding angular expressions to onsubmit events.
  34323. *
  34324. * Additionally it prevents the default action (which for form means sending the request to the
  34325. * server and reloading the current page), but only if the form does not contain `action`,
  34326. * `data-action`, or `x-action` attributes.
  34327. *
  34328. * <div class="alert alert-warning">
  34329. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  34330. * `ngSubmit` handlers together. See the
  34331. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  34332. * for a detailed discussion of when `ngSubmit` may be triggered.
  34333. * </div>
  34334. *
  34335. * @element form
  34336. * @priority 0
  34337. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  34338. * ({@link guide/expression#-event- Event object is available as `$event`})
  34339. *
  34340. * @example
  34341. <example module="submitExample">
  34342. <file name="index.html">
  34343. <script>
  34344. angular.module('submitExample', [])
  34345. .controller('ExampleController', ['$scope', function($scope) {
  34346. $scope.list = [];
  34347. $scope.text = 'hello';
  34348. $scope.submit = function() {
  34349. if ($scope.text) {
  34350. $scope.list.push(this.text);
  34351. $scope.text = '';
  34352. }
  34353. };
  34354. }]);
  34355. </script>
  34356. <form ng-submit="submit()" ng-controller="ExampleController">
  34357. Enter text and hit enter:
  34358. <input type="text" ng-model="text" name="text" />
  34359. <input type="submit" id="submit" value="Submit" />
  34360. <pre>list={{list}}</pre>
  34361. </form>
  34362. </file>
  34363. <file name="protractor.js" type="protractor">
  34364. it('should check ng-submit', function() {
  34365. expect(element(by.binding('list')).getText()).toBe('list=[]');
  34366. element(by.css('#submit')).click();
  34367. expect(element(by.binding('list')).getText()).toContain('hello');
  34368. expect(element(by.model('text')).getAttribute('value')).toBe('');
  34369. });
  34370. it('should ignore empty strings', function() {
  34371. expect(element(by.binding('list')).getText()).toBe('list=[]');
  34372. element(by.css('#submit')).click();
  34373. element(by.css('#submit')).click();
  34374. expect(element(by.binding('list')).getText()).toContain('hello');
  34375. });
  34376. </file>
  34377. </example>
  34378. */
  34379. /**
  34380. * @ngdoc directive
  34381. * @name ngFocus
  34382. *
  34383. * @description
  34384. * Specify custom behavior on focus event.
  34385. *
  34386. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  34387. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  34388. * during an `$apply` to ensure a consistent state.
  34389. *
  34390. * @element window, input, select, textarea, a
  34391. * @priority 0
  34392. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  34393. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  34394. *
  34395. * @example
  34396. * See {@link ng.directive:ngClick ngClick}
  34397. */
  34398. /**
  34399. * @ngdoc directive
  34400. * @name ngBlur
  34401. *
  34402. * @description
  34403. * Specify custom behavior on blur event.
  34404. *
  34405. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  34406. * an element has lost focus.
  34407. *
  34408. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  34409. * (e.g. removing a focussed input),
  34410. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  34411. * during an `$apply` to ensure a consistent state.
  34412. *
  34413. * @element window, input, select, textarea, a
  34414. * @priority 0
  34415. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  34416. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  34417. *
  34418. * @example
  34419. * See {@link ng.directive:ngClick ngClick}
  34420. */
  34421. /**
  34422. * @ngdoc directive
  34423. * @name ngCopy
  34424. *
  34425. * @description
  34426. * Specify custom behavior on copy event.
  34427. *
  34428. * @element window, input, select, textarea, a
  34429. * @priority 0
  34430. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  34431. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  34432. *
  34433. * @example
  34434. <example>
  34435. <file name="index.html">
  34436. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  34437. copied: {{copied}}
  34438. </file>
  34439. </example>
  34440. */
  34441. /**
  34442. * @ngdoc directive
  34443. * @name ngCut
  34444. *
  34445. * @description
  34446. * Specify custom behavior on cut event.
  34447. *
  34448. * @element window, input, select, textarea, a
  34449. * @priority 0
  34450. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  34451. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  34452. *
  34453. * @example
  34454. <example>
  34455. <file name="index.html">
  34456. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  34457. cut: {{cut}}
  34458. </file>
  34459. </example>
  34460. */
  34461. /**
  34462. * @ngdoc directive
  34463. * @name ngPaste
  34464. *
  34465. * @description
  34466. * Specify custom behavior on paste event.
  34467. *
  34468. * @element window, input, select, textarea, a
  34469. * @priority 0
  34470. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  34471. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  34472. *
  34473. * @example
  34474. <example>
  34475. <file name="index.html">
  34476. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  34477. pasted: {{paste}}
  34478. </file>
  34479. </example>
  34480. */
  34481. /**
  34482. * @ngdoc directive
  34483. * @name ngIf
  34484. * @restrict A
  34485. * @multiElement
  34486. *
  34487. * @description
  34488. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  34489. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  34490. * value then the element is removed from the DOM, otherwise a clone of the
  34491. * element is reinserted into the DOM.
  34492. *
  34493. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  34494. * element in the DOM rather than changing its visibility via the `display` css property. A common
  34495. * case when this difference is significant is when using css selectors that rely on an element's
  34496. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  34497. *
  34498. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  34499. * is created when the element is restored. The scope created within `ngIf` inherits from
  34500. * its parent scope using
  34501. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  34502. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  34503. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  34504. * variable within the child scope will override (hide) the value in the parent scope.
  34505. *
  34506. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  34507. * is if an element's class attribute is directly modified after it's compiled, using something like
  34508. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  34509. * the added class will be lost because the original compiled state is used to regenerate the element.
  34510. *
  34511. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  34512. * and `leave` effects.
  34513. *
  34514. * @animations
  34515. * | Animation | Occurs |
  34516. * |----------------------------------|-------------------------------------|
  34517. * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container |
  34518. * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM |
  34519. *
  34520. * @element ANY
  34521. * @scope
  34522. * @priority 600
  34523. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  34524. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  34525. * element is added to the DOM tree.
  34526. *
  34527. * @example
  34528. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  34529. <file name="index.html">
  34530. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  34531. Show when checked:
  34532. <span ng-if="checked" class="animate-if">
  34533. This is removed when the checkbox is unchecked.
  34534. </span>
  34535. </file>
  34536. <file name="animations.css">
  34537. .animate-if {
  34538. background:white;
  34539. border:1px solid black;
  34540. padding:10px;
  34541. }
  34542. .animate-if.ng-enter, .animate-if.ng-leave {
  34543. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  34544. }
  34545. .animate-if.ng-enter,
  34546. .animate-if.ng-leave.ng-leave-active {
  34547. opacity:0;
  34548. }
  34549. .animate-if.ng-leave,
  34550. .animate-if.ng-enter.ng-enter-active {
  34551. opacity:1;
  34552. }
  34553. </file>
  34554. </example>
  34555. */
  34556. var ngIfDirective = ['$animate', '$compile', function($animate, $compile) {
  34557. return {
  34558. multiElement: true,
  34559. transclude: 'element',
  34560. priority: 600,
  34561. terminal: true,
  34562. restrict: 'A',
  34563. $$tlb: true,
  34564. link: function($scope, $element, $attr, ctrl, $transclude) {
  34565. var block, childScope, previousElements;
  34566. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  34567. if (value) {
  34568. if (!childScope) {
  34569. $transclude(function(clone, newScope) {
  34570. childScope = newScope;
  34571. clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf);
  34572. // Note: We only need the first/last node of the cloned nodes.
  34573. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  34574. // by a directive with templateUrl when its template arrives.
  34575. block = {
  34576. clone: clone
  34577. };
  34578. $animate.enter(clone, $element.parent(), $element);
  34579. });
  34580. }
  34581. } else {
  34582. if (previousElements) {
  34583. previousElements.remove();
  34584. previousElements = null;
  34585. }
  34586. if (childScope) {
  34587. childScope.$destroy();
  34588. childScope = null;
  34589. }
  34590. if (block) {
  34591. previousElements = getBlockNodes(block.clone);
  34592. $animate.leave(previousElements).then(function() {
  34593. previousElements = null;
  34594. });
  34595. block = null;
  34596. }
  34597. }
  34598. });
  34599. }
  34600. };
  34601. }];
  34602. /**
  34603. * @ngdoc directive
  34604. * @name ngInclude
  34605. * @restrict ECA
  34606. *
  34607. * @description
  34608. * Fetches, compiles and includes an external HTML fragment.
  34609. *
  34610. * By default, the template URL is restricted to the same domain and protocol as the
  34611. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  34612. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  34613. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  34614. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  34615. * ng.$sce Strict Contextual Escaping}.
  34616. *
  34617. * In addition, the browser's
  34618. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  34619. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  34620. * policy may further restrict whether the template is successfully loaded.
  34621. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  34622. * access on some browsers.
  34623. *
  34624. * @animations
  34625. * | Animation | Occurs |
  34626. * |----------------------------------|-------------------------------------|
  34627. * | {@link ng.$animate#enter enter} | when the expression changes, on the new include |
  34628. * | {@link ng.$animate#leave leave} | when the expression changes, on the old include |
  34629. *
  34630. * The enter and leave animation occur concurrently.
  34631. *
  34632. * @scope
  34633. * @priority 400
  34634. *
  34635. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  34636. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  34637. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  34638. * <div class="alert alert-warning">
  34639. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  34640. * a function with the name on the window element, which will usually throw a
  34641. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  34642. * different form that {@link guide/directive#normalization matches} `onload`.
  34643. * </div>
  34644. *
  34645. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  34646. * $anchorScroll} to scroll the viewport after the content is loaded.
  34647. *
  34648. * - If the attribute is not set, disable scrolling.
  34649. * - If the attribute is set without value, enable scrolling.
  34650. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  34651. *
  34652. * @example
  34653. <example module="includeExample" deps="angular-animate.js" animations="true">
  34654. <file name="index.html">
  34655. <div ng-controller="ExampleController">
  34656. <select ng-model="template" ng-options="t.name for t in templates">
  34657. <option value="">(blank)</option>
  34658. </select>
  34659. url of the template: <code>{{template.url}}</code>
  34660. <hr/>
  34661. <div class="slide-animate-container">
  34662. <div class="slide-animate" ng-include="template.url"></div>
  34663. </div>
  34664. </div>
  34665. </file>
  34666. <file name="script.js">
  34667. angular.module('includeExample', ['ngAnimate'])
  34668. .controller('ExampleController', ['$scope', function($scope) {
  34669. $scope.templates =
  34670. [ { name: 'template1.html', url: 'template1.html'},
  34671. { name: 'template2.html', url: 'template2.html'} ];
  34672. $scope.template = $scope.templates[0];
  34673. }]);
  34674. </file>
  34675. <file name="template1.html">
  34676. Content of template1.html
  34677. </file>
  34678. <file name="template2.html">
  34679. Content of template2.html
  34680. </file>
  34681. <file name="animations.css">
  34682. .slide-animate-container {
  34683. position:relative;
  34684. background:white;
  34685. border:1px solid black;
  34686. height:40px;
  34687. overflow:hidden;
  34688. }
  34689. .slide-animate {
  34690. padding:10px;
  34691. }
  34692. .slide-animate.ng-enter, .slide-animate.ng-leave {
  34693. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  34694. position:absolute;
  34695. top:0;
  34696. left:0;
  34697. right:0;
  34698. bottom:0;
  34699. display:block;
  34700. padding:10px;
  34701. }
  34702. .slide-animate.ng-enter {
  34703. top:-50px;
  34704. }
  34705. .slide-animate.ng-enter.ng-enter-active {
  34706. top:0;
  34707. }
  34708. .slide-animate.ng-leave {
  34709. top:0;
  34710. }
  34711. .slide-animate.ng-leave.ng-leave-active {
  34712. top:50px;
  34713. }
  34714. </file>
  34715. <file name="protractor.js" type="protractor">
  34716. var templateSelect = element(by.model('template'));
  34717. var includeElem = element(by.css('[ng-include]'));
  34718. it('should load template1.html', function() {
  34719. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  34720. });
  34721. it('should load template2.html', function() {
  34722. if (browser.params.browser == 'firefox') {
  34723. // Firefox can't handle using selects
  34724. // See https://github.com/angular/protractor/issues/480
  34725. return;
  34726. }
  34727. templateSelect.click();
  34728. templateSelect.all(by.css('option')).get(2).click();
  34729. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  34730. });
  34731. it('should change to blank', function() {
  34732. if (browser.params.browser == 'firefox') {
  34733. // Firefox can't handle using selects
  34734. return;
  34735. }
  34736. templateSelect.click();
  34737. templateSelect.all(by.css('option')).get(0).click();
  34738. expect(includeElem.isPresent()).toBe(false);
  34739. });
  34740. </file>
  34741. </example>
  34742. */
  34743. /**
  34744. * @ngdoc event
  34745. * @name ngInclude#$includeContentRequested
  34746. * @eventType emit on the scope ngInclude was declared in
  34747. * @description
  34748. * Emitted every time the ngInclude content is requested.
  34749. *
  34750. * @param {Object} angularEvent Synthetic event object.
  34751. * @param {String} src URL of content to load.
  34752. */
  34753. /**
  34754. * @ngdoc event
  34755. * @name ngInclude#$includeContentLoaded
  34756. * @eventType emit on the current ngInclude scope
  34757. * @description
  34758. * Emitted every time the ngInclude content is reloaded.
  34759. *
  34760. * @param {Object} angularEvent Synthetic event object.
  34761. * @param {String} src URL of content to load.
  34762. */
  34763. /**
  34764. * @ngdoc event
  34765. * @name ngInclude#$includeContentError
  34766. * @eventType emit on the scope ngInclude was declared in
  34767. * @description
  34768. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  34769. *
  34770. * @param {Object} angularEvent Synthetic event object.
  34771. * @param {String} src URL of content to load.
  34772. */
  34773. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  34774. function($templateRequest, $anchorScroll, $animate) {
  34775. return {
  34776. restrict: 'ECA',
  34777. priority: 400,
  34778. terminal: true,
  34779. transclude: 'element',
  34780. controller: angular.noop,
  34781. compile: function(element, attr) {
  34782. var srcExp = attr.ngInclude || attr.src,
  34783. onloadExp = attr.onload || '',
  34784. autoScrollExp = attr.autoscroll;
  34785. return function(scope, $element, $attr, ctrl, $transclude) {
  34786. var changeCounter = 0,
  34787. currentScope,
  34788. previousElement,
  34789. currentElement;
  34790. var cleanupLastIncludeContent = function() {
  34791. if (previousElement) {
  34792. previousElement.remove();
  34793. previousElement = null;
  34794. }
  34795. if (currentScope) {
  34796. currentScope.$destroy();
  34797. currentScope = null;
  34798. }
  34799. if (currentElement) {
  34800. $animate.leave(currentElement).then(function() {
  34801. previousElement = null;
  34802. });
  34803. previousElement = currentElement;
  34804. currentElement = null;
  34805. }
  34806. };
  34807. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  34808. var afterAnimation = function() {
  34809. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  34810. $anchorScroll();
  34811. }
  34812. };
  34813. var thisChangeId = ++changeCounter;
  34814. if (src) {
  34815. //set the 2nd param to true to ignore the template request error so that the inner
  34816. //contents and scope can be cleaned up.
  34817. $templateRequest(src, true).then(function(response) {
  34818. if (scope.$$destroyed) return;
  34819. if (thisChangeId !== changeCounter) return;
  34820. var newScope = scope.$new();
  34821. ctrl.template = response;
  34822. // Note: This will also link all children of ng-include that were contained in the original
  34823. // html. If that content contains controllers, ... they could pollute/change the scope.
  34824. // However, using ng-include on an element with additional content does not make sense...
  34825. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  34826. // function is called before linking the content, which would apply child
  34827. // directives to non existing elements.
  34828. var clone = $transclude(newScope, function(clone) {
  34829. cleanupLastIncludeContent();
  34830. $animate.enter(clone, null, $element).then(afterAnimation);
  34831. });
  34832. currentScope = newScope;
  34833. currentElement = clone;
  34834. currentScope.$emit('$includeContentLoaded', src);
  34835. scope.$eval(onloadExp);
  34836. }, function() {
  34837. if (scope.$$destroyed) return;
  34838. if (thisChangeId === changeCounter) {
  34839. cleanupLastIncludeContent();
  34840. scope.$emit('$includeContentError', src);
  34841. }
  34842. });
  34843. scope.$emit('$includeContentRequested', src);
  34844. } else {
  34845. cleanupLastIncludeContent();
  34846. ctrl.template = null;
  34847. }
  34848. });
  34849. };
  34850. }
  34851. };
  34852. }];
  34853. // This directive is called during the $transclude call of the first `ngInclude` directive.
  34854. // It will replace and compile the content of the element with the loaded template.
  34855. // We need this directive so that the element content is already filled when
  34856. // the link function of another directive on the same element as ngInclude
  34857. // is called.
  34858. var ngIncludeFillContentDirective = ['$compile',
  34859. function($compile) {
  34860. return {
  34861. restrict: 'ECA',
  34862. priority: -400,
  34863. require: 'ngInclude',
  34864. link: function(scope, $element, $attr, ctrl) {
  34865. if (toString.call($element[0]).match(/SVG/)) {
  34866. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  34867. // support innerHTML, so detect this here and try to generate the contents
  34868. // specially.
  34869. $element.empty();
  34870. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  34871. function namespaceAdaptedClone(clone) {
  34872. $element.append(clone);
  34873. }, {futureParentElement: $element});
  34874. return;
  34875. }
  34876. $element.html(ctrl.template);
  34877. $compile($element.contents())(scope);
  34878. }
  34879. };
  34880. }];
  34881. /**
  34882. * @ngdoc directive
  34883. * @name ngInit
  34884. * @restrict AC
  34885. *
  34886. * @description
  34887. * The `ngInit` directive allows you to evaluate an expression in the
  34888. * current scope.
  34889. *
  34890. * <div class="alert alert-danger">
  34891. * This directive can be abused to add unnecessary amounts of logic into your templates.
  34892. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  34893. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  34894. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  34895. * rather than `ngInit` to initialize values on a scope.
  34896. * </div>
  34897. *
  34898. * <div class="alert alert-warning">
  34899. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  34900. * sure you have parentheses to ensure correct operator precedence:
  34901. * <pre class="prettyprint">
  34902. * `<div ng-init="test1 = ($index | toString)"></div>`
  34903. * </pre>
  34904. * </div>
  34905. *
  34906. * @priority 450
  34907. *
  34908. * @element ANY
  34909. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  34910. *
  34911. * @example
  34912. <example module="initExample">
  34913. <file name="index.html">
  34914. <script>
  34915. angular.module('initExample', [])
  34916. .controller('ExampleController', ['$scope', function($scope) {
  34917. $scope.list = [['a', 'b'], ['c', 'd']];
  34918. }]);
  34919. </script>
  34920. <div ng-controller="ExampleController">
  34921. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  34922. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  34923. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  34924. </div>
  34925. </div>
  34926. </div>
  34927. </file>
  34928. <file name="protractor.js" type="protractor">
  34929. it('should alias index positions', function() {
  34930. var elements = element.all(by.css('.example-init'));
  34931. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  34932. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  34933. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  34934. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  34935. });
  34936. </file>
  34937. </example>
  34938. */
  34939. var ngInitDirective = ngDirective({
  34940. priority: 450,
  34941. compile: function() {
  34942. return {
  34943. pre: function(scope, element, attrs) {
  34944. scope.$eval(attrs.ngInit);
  34945. }
  34946. };
  34947. }
  34948. });
  34949. /**
  34950. * @ngdoc directive
  34951. * @name ngList
  34952. *
  34953. * @description
  34954. * Text input that converts between a delimited string and an array of strings. The default
  34955. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  34956. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  34957. *
  34958. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  34959. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  34960. * list item is respected. This implies that the user of the directive is responsible for
  34961. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  34962. * tab or newline character.
  34963. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  34964. * when joining the list items back together) and whitespace around each list item is stripped
  34965. * before it is added to the model.
  34966. *
  34967. * ### Example with Validation
  34968. *
  34969. * <example name="ngList-directive" module="listExample">
  34970. * <file name="app.js">
  34971. * angular.module('listExample', [])
  34972. * .controller('ExampleController', ['$scope', function($scope) {
  34973. * $scope.names = ['morpheus', 'neo', 'trinity'];
  34974. * }]);
  34975. * </file>
  34976. * <file name="index.html">
  34977. * <form name="myForm" ng-controller="ExampleController">
  34978. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  34979. * <span role="alert">
  34980. * <span class="error" ng-show="myForm.namesInput.$error.required">
  34981. * Required!</span>
  34982. * </span>
  34983. * <br>
  34984. * <tt>names = {{names}}</tt><br/>
  34985. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  34986. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  34987. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  34988. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  34989. * </form>
  34990. * </file>
  34991. * <file name="protractor.js" type="protractor">
  34992. * var listInput = element(by.model('names'));
  34993. * var names = element(by.exactBinding('names'));
  34994. * var valid = element(by.binding('myForm.namesInput.$valid'));
  34995. * var error = element(by.css('span.error'));
  34996. *
  34997. * it('should initialize to model', function() {
  34998. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  34999. * expect(valid.getText()).toContain('true');
  35000. * expect(error.getCssValue('display')).toBe('none');
  35001. * });
  35002. *
  35003. * it('should be invalid if empty', function() {
  35004. * listInput.clear();
  35005. * listInput.sendKeys('');
  35006. *
  35007. * expect(names.getText()).toContain('');
  35008. * expect(valid.getText()).toContain('false');
  35009. * expect(error.getCssValue('display')).not.toBe('none');
  35010. * });
  35011. * </file>
  35012. * </example>
  35013. *
  35014. * ### Example - splitting on newline
  35015. * <example name="ngList-directive-newlines">
  35016. * <file name="index.html">
  35017. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  35018. * <pre>{{ list | json }}</pre>
  35019. * </file>
  35020. * <file name="protractor.js" type="protractor">
  35021. * it("should split the text by newlines", function() {
  35022. * var listInput = element(by.model('list'));
  35023. * var output = element(by.binding('list | json'));
  35024. * listInput.sendKeys('abc\ndef\nghi');
  35025. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  35026. * });
  35027. * </file>
  35028. * </example>
  35029. *
  35030. * @element input
  35031. * @param {string=} ngList optional delimiter that should be used to split the value.
  35032. */
  35033. var ngListDirective = function() {
  35034. return {
  35035. restrict: 'A',
  35036. priority: 100,
  35037. require: 'ngModel',
  35038. link: function(scope, element, attr, ctrl) {
  35039. // We want to control whitespace trimming so we use this convoluted approach
  35040. // to access the ngList attribute, which doesn't pre-trim the attribute
  35041. var ngList = element.attr(attr.$attr.ngList) || ', ';
  35042. var trimValues = attr.ngTrim !== 'false';
  35043. var separator = trimValues ? trim(ngList) : ngList;
  35044. var parse = function(viewValue) {
  35045. // If the viewValue is invalid (say required but empty) it will be `undefined`
  35046. if (isUndefined(viewValue)) return;
  35047. var list = [];
  35048. if (viewValue) {
  35049. forEach(viewValue.split(separator), function(value) {
  35050. if (value) list.push(trimValues ? trim(value) : value);
  35051. });
  35052. }
  35053. return list;
  35054. };
  35055. ctrl.$parsers.push(parse);
  35056. ctrl.$formatters.push(function(value) {
  35057. if (isArray(value)) {
  35058. return value.join(ngList);
  35059. }
  35060. return undefined;
  35061. });
  35062. // Override the standard $isEmpty because an empty array means the input is empty.
  35063. ctrl.$isEmpty = function(value) {
  35064. return !value || !value.length;
  35065. };
  35066. }
  35067. };
  35068. };
  35069. /* global VALID_CLASS: true,
  35070. INVALID_CLASS: true,
  35071. PRISTINE_CLASS: true,
  35072. DIRTY_CLASS: true,
  35073. UNTOUCHED_CLASS: true,
  35074. TOUCHED_CLASS: true,
  35075. */
  35076. var VALID_CLASS = 'ng-valid',
  35077. INVALID_CLASS = 'ng-invalid',
  35078. PRISTINE_CLASS = 'ng-pristine',
  35079. DIRTY_CLASS = 'ng-dirty',
  35080. UNTOUCHED_CLASS = 'ng-untouched',
  35081. TOUCHED_CLASS = 'ng-touched',
  35082. PENDING_CLASS = 'ng-pending',
  35083. EMPTY_CLASS = 'ng-empty',
  35084. NOT_EMPTY_CLASS = 'ng-not-empty';
  35085. var ngModelMinErr = minErr('ngModel');
  35086. /**
  35087. * @ngdoc type
  35088. * @name ngModel.NgModelController
  35089. *
  35090. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  35091. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  35092. * is set.
  35093. * @property {*} $modelValue The value in the model that the control is bound to.
  35094. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  35095. the control reads value from the DOM. The functions are called in array order, each passing
  35096. its return value through to the next. The last return value is forwarded to the
  35097. {@link ngModel.NgModelController#$validators `$validators`} collection.
  35098. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  35099. `$viewValue`}.
  35100. Returning `undefined` from a parser means a parse error occurred. In that case,
  35101. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  35102. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  35103. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  35104. *
  35105. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  35106. the model value changes. The functions are called in reverse array order, each passing the value through to the
  35107. next. The last return value is used as the actual DOM value.
  35108. Used to format / convert values for display in the control.
  35109. * ```js
  35110. * function formatter(value) {
  35111. * if (value) {
  35112. * return value.toUpperCase();
  35113. * }
  35114. * }
  35115. * ngModel.$formatters.push(formatter);
  35116. * ```
  35117. *
  35118. * @property {Object.<string, function>} $validators A collection of validators that are applied
  35119. * whenever the model value changes. The key value within the object refers to the name of the
  35120. * validator while the function refers to the validation operation. The validation operation is
  35121. * provided with the model value as an argument and must return a true or false value depending
  35122. * on the response of that validation.
  35123. *
  35124. * ```js
  35125. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  35126. * var value = modelValue || viewValue;
  35127. * return /[0-9]+/.test(value) &&
  35128. * /[a-z]+/.test(value) &&
  35129. * /[A-Z]+/.test(value) &&
  35130. * /\W+/.test(value);
  35131. * };
  35132. * ```
  35133. *
  35134. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  35135. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  35136. * is expected to return a promise when it is run during the model validation process. Once the promise
  35137. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  35138. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  35139. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  35140. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  35141. * will only run once all synchronous validators have passed.
  35142. *
  35143. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  35144. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  35145. *
  35146. * ```js
  35147. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  35148. * var value = modelValue || viewValue;
  35149. *
  35150. * // Lookup user by username
  35151. * return $http.get('/api/users/' + value).
  35152. * then(function resolved() {
  35153. * //username exists, this means validation fails
  35154. * return $q.reject('exists');
  35155. * }, function rejected() {
  35156. * //username does not exist, therefore this validation passes
  35157. * return true;
  35158. * });
  35159. * };
  35160. * ```
  35161. *
  35162. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  35163. * view value has changed. It is called with no arguments, and its return value is ignored.
  35164. * This can be used in place of additional $watches against the model value.
  35165. *
  35166. * @property {Object} $error An object hash with all failing validator ids as keys.
  35167. * @property {Object} $pending An object hash with all pending validator ids as keys.
  35168. *
  35169. * @property {boolean} $untouched True if control has not lost focus yet.
  35170. * @property {boolean} $touched True if control has lost focus.
  35171. * @property {boolean} $pristine True if user has not interacted with the control yet.
  35172. * @property {boolean} $dirty True if user has already interacted with the control.
  35173. * @property {boolean} $valid True if there is no error.
  35174. * @property {boolean} $invalid True if at least one error on the control.
  35175. * @property {string} $name The name attribute of the control.
  35176. *
  35177. * @description
  35178. *
  35179. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  35180. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  35181. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  35182. * listening to DOM events.
  35183. * Such DOM related logic should be provided by other directives which make use of
  35184. * `NgModelController` for data-binding to control elements.
  35185. * Angular provides this DOM logic for most {@link input `input`} elements.
  35186. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  35187. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  35188. *
  35189. * @example
  35190. * ### Custom Control Example
  35191. * This example shows how to use `NgModelController` with a custom control to achieve
  35192. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  35193. * collaborate together to achieve the desired result.
  35194. *
  35195. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  35196. * contents be edited in place by the user.
  35197. *
  35198. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  35199. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  35200. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  35201. * that content using the `$sce` service.
  35202. *
  35203. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  35204. <file name="style.css">
  35205. [contenteditable] {
  35206. border: 1px solid black;
  35207. background-color: white;
  35208. min-height: 20px;
  35209. }
  35210. .ng-invalid {
  35211. border: 1px solid red;
  35212. }
  35213. </file>
  35214. <file name="script.js">
  35215. angular.module('customControl', ['ngSanitize']).
  35216. directive('contenteditable', ['$sce', function($sce) {
  35217. return {
  35218. restrict: 'A', // only activate on element attribute
  35219. require: '?ngModel', // get a hold of NgModelController
  35220. link: function(scope, element, attrs, ngModel) {
  35221. if (!ngModel) return; // do nothing if no ng-model
  35222. // Specify how UI should be updated
  35223. ngModel.$render = function() {
  35224. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  35225. };
  35226. // Listen for change events to enable binding
  35227. element.on('blur keyup change', function() {
  35228. scope.$evalAsync(read);
  35229. });
  35230. read(); // initialize
  35231. // Write data to the model
  35232. function read() {
  35233. var html = element.html();
  35234. // When we clear the content editable the browser leaves a <br> behind
  35235. // If strip-br attribute is provided then we strip this out
  35236. if ( attrs.stripBr && html == '<br>' ) {
  35237. html = '';
  35238. }
  35239. ngModel.$setViewValue(html);
  35240. }
  35241. }
  35242. };
  35243. }]);
  35244. </file>
  35245. <file name="index.html">
  35246. <form name="myForm">
  35247. <div contenteditable
  35248. name="myWidget" ng-model="userContent"
  35249. strip-br="true"
  35250. required>Change me!</div>
  35251. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  35252. <hr>
  35253. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  35254. </form>
  35255. </file>
  35256. <file name="protractor.js" type="protractor">
  35257. it('should data-bind and become invalid', function() {
  35258. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  35259. // SafariDriver can't handle contenteditable
  35260. // and Firefox driver can't clear contenteditables very well
  35261. return;
  35262. }
  35263. var contentEditable = element(by.css('[contenteditable]'));
  35264. var content = 'Change me!';
  35265. expect(contentEditable.getText()).toEqual(content);
  35266. contentEditable.clear();
  35267. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  35268. expect(contentEditable.getText()).toEqual('');
  35269. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  35270. });
  35271. </file>
  35272. * </example>
  35273. *
  35274. *
  35275. */
  35276. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  35277. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  35278. this.$viewValue = Number.NaN;
  35279. this.$modelValue = Number.NaN;
  35280. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  35281. this.$validators = {};
  35282. this.$asyncValidators = {};
  35283. this.$parsers = [];
  35284. this.$formatters = [];
  35285. this.$viewChangeListeners = [];
  35286. this.$untouched = true;
  35287. this.$touched = false;
  35288. this.$pristine = true;
  35289. this.$dirty = false;
  35290. this.$valid = true;
  35291. this.$invalid = false;
  35292. this.$error = {}; // keep invalid keys here
  35293. this.$$success = {}; // keep valid keys here
  35294. this.$pending = undefined; // keep pending keys here
  35295. this.$name = $interpolate($attr.name || '', false)($scope);
  35296. this.$$parentForm = nullFormCtrl;
  35297. var parsedNgModel = $parse($attr.ngModel),
  35298. parsedNgModelAssign = parsedNgModel.assign,
  35299. ngModelGet = parsedNgModel,
  35300. ngModelSet = parsedNgModelAssign,
  35301. pendingDebounce = null,
  35302. parserValid,
  35303. ctrl = this;
  35304. this.$$setOptions = function(options) {
  35305. ctrl.$options = options;
  35306. if (options && options.getterSetter) {
  35307. var invokeModelGetter = $parse($attr.ngModel + '()'),
  35308. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  35309. ngModelGet = function($scope) {
  35310. var modelValue = parsedNgModel($scope);
  35311. if (isFunction(modelValue)) {
  35312. modelValue = invokeModelGetter($scope);
  35313. }
  35314. return modelValue;
  35315. };
  35316. ngModelSet = function($scope, newValue) {
  35317. if (isFunction(parsedNgModel($scope))) {
  35318. invokeModelSetter($scope, {$$$p: newValue});
  35319. } else {
  35320. parsedNgModelAssign($scope, newValue);
  35321. }
  35322. };
  35323. } else if (!parsedNgModel.assign) {
  35324. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  35325. $attr.ngModel, startingTag($element));
  35326. }
  35327. };
  35328. /**
  35329. * @ngdoc method
  35330. * @name ngModel.NgModelController#$render
  35331. *
  35332. * @description
  35333. * Called when the view needs to be updated. It is expected that the user of the ng-model
  35334. * directive will implement this method.
  35335. *
  35336. * The `$render()` method is invoked in the following situations:
  35337. *
  35338. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  35339. * committed value then `$render()` is called to update the input control.
  35340. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  35341. * the `$viewValue` are different from last time.
  35342. *
  35343. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  35344. * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue`
  35345. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  35346. * invoked if you only change a property on the objects.
  35347. */
  35348. this.$render = noop;
  35349. /**
  35350. * @ngdoc method
  35351. * @name ngModel.NgModelController#$isEmpty
  35352. *
  35353. * @description
  35354. * This is called when we need to determine if the value of an input is empty.
  35355. *
  35356. * For instance, the required directive does this to work out if the input has data or not.
  35357. *
  35358. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  35359. *
  35360. * You can override this for input directives whose concept of being empty is different from the
  35361. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  35362. * implies empty.
  35363. *
  35364. * @param {*} value The value of the input to check for emptiness.
  35365. * @returns {boolean} True if `value` is "empty".
  35366. */
  35367. this.$isEmpty = function(value) {
  35368. return isUndefined(value) || value === '' || value === null || value !== value;
  35369. };
  35370. this.$$updateEmptyClasses = function(value) {
  35371. if (ctrl.$isEmpty(value)) {
  35372. $animate.removeClass($element, NOT_EMPTY_CLASS);
  35373. $animate.addClass($element, EMPTY_CLASS);
  35374. } else {
  35375. $animate.removeClass($element, EMPTY_CLASS);
  35376. $animate.addClass($element, NOT_EMPTY_CLASS);
  35377. }
  35378. };
  35379. var currentValidationRunId = 0;
  35380. /**
  35381. * @ngdoc method
  35382. * @name ngModel.NgModelController#$setValidity
  35383. *
  35384. * @description
  35385. * Change the validity state, and notify the form.
  35386. *
  35387. * This method can be called within $parsers/$formatters or a custom validation implementation.
  35388. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  35389. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  35390. *
  35391. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  35392. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  35393. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  35394. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  35395. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  35396. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  35397. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  35398. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  35399. * Skipped is used by Angular when validators do not run because of parse errors and
  35400. * when `$asyncValidators` do not run because any of the `$validators` failed.
  35401. */
  35402. addSetValidityMethod({
  35403. ctrl: this,
  35404. $element: $element,
  35405. set: function(object, property) {
  35406. object[property] = true;
  35407. },
  35408. unset: function(object, property) {
  35409. delete object[property];
  35410. },
  35411. $animate: $animate
  35412. });
  35413. /**
  35414. * @ngdoc method
  35415. * @name ngModel.NgModelController#$setPristine
  35416. *
  35417. * @description
  35418. * Sets the control to its pristine state.
  35419. *
  35420. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  35421. * state (`ng-pristine` class). A model is considered to be pristine when the control
  35422. * has not been changed from when first compiled.
  35423. */
  35424. this.$setPristine = function() {
  35425. ctrl.$dirty = false;
  35426. ctrl.$pristine = true;
  35427. $animate.removeClass($element, DIRTY_CLASS);
  35428. $animate.addClass($element, PRISTINE_CLASS);
  35429. };
  35430. /**
  35431. * @ngdoc method
  35432. * @name ngModel.NgModelController#$setDirty
  35433. *
  35434. * @description
  35435. * Sets the control to its dirty state.
  35436. *
  35437. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  35438. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  35439. * from when first compiled.
  35440. */
  35441. this.$setDirty = function() {
  35442. ctrl.$dirty = true;
  35443. ctrl.$pristine = false;
  35444. $animate.removeClass($element, PRISTINE_CLASS);
  35445. $animate.addClass($element, DIRTY_CLASS);
  35446. ctrl.$$parentForm.$setDirty();
  35447. };
  35448. /**
  35449. * @ngdoc method
  35450. * @name ngModel.NgModelController#$setUntouched
  35451. *
  35452. * @description
  35453. * Sets the control to its untouched state.
  35454. *
  35455. * This method can be called to remove the `ng-touched` class and set the control to its
  35456. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  35457. * by default, however this function can be used to restore that state if the model has
  35458. * already been touched by the user.
  35459. */
  35460. this.$setUntouched = function() {
  35461. ctrl.$touched = false;
  35462. ctrl.$untouched = true;
  35463. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  35464. };
  35465. /**
  35466. * @ngdoc method
  35467. * @name ngModel.NgModelController#$setTouched
  35468. *
  35469. * @description
  35470. * Sets the control to its touched state.
  35471. *
  35472. * This method can be called to remove the `ng-untouched` class and set the control to its
  35473. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  35474. * first focused the control element and then shifted focus away from the control (blur event).
  35475. */
  35476. this.$setTouched = function() {
  35477. ctrl.$touched = true;
  35478. ctrl.$untouched = false;
  35479. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  35480. };
  35481. /**
  35482. * @ngdoc method
  35483. * @name ngModel.NgModelController#$rollbackViewValue
  35484. *
  35485. * @description
  35486. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  35487. * which may be caused by a pending debounced event or because the input is waiting for a some
  35488. * future event.
  35489. *
  35490. * If you have an input that uses `ng-model-options` to set up debounced updates or updates that
  35491. * depend on special events such as blur, you can have a situation where there is a period when
  35492. * the `$viewValue` is out of sync with the ngModel's `$modelValue`.
  35493. *
  35494. * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update
  35495. * and reset the input to the last committed view value.
  35496. *
  35497. * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue`
  35498. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  35499. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  35500. *
  35501. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  35502. * input which may have such events pending. This is important in order to make sure that the
  35503. * input field will be updated with the new model value and any pending operations are cancelled.
  35504. *
  35505. * <example name="ng-model-cancel-update" module="cancel-update-example">
  35506. * <file name="app.js">
  35507. * angular.module('cancel-update-example', [])
  35508. *
  35509. * .controller('CancelUpdateController', ['$scope', function($scope) {
  35510. * $scope.model = {};
  35511. *
  35512. * $scope.setEmpty = function(e, value, rollback) {
  35513. * if (e.keyCode == 27) {
  35514. * e.preventDefault();
  35515. * if (rollback) {
  35516. * $scope.myForm[value].$rollbackViewValue();
  35517. * }
  35518. * $scope.model[value] = '';
  35519. * }
  35520. * };
  35521. * }]);
  35522. * </file>
  35523. * <file name="index.html">
  35524. * <div ng-controller="CancelUpdateController">
  35525. * <p>Both of these inputs are only updated if they are blurred. Hitting escape should
  35526. * empty them. Follow these steps and observe the difference:</p>
  35527. * <ol>
  35528. * <li>Type something in the input. You will see that the model is not yet updated</li>
  35529. * <li>Press the Escape key.
  35530. * <ol>
  35531. * <li> In the first example, nothing happens, because the model is already '', and no
  35532. * update is detected. If you blur the input, the model will be set to the current view.
  35533. * </li>
  35534. * <li> In the second example, the pending update is cancelled, and the input is set back
  35535. * to the last committed view value (''). Blurring the input does nothing.
  35536. * </li>
  35537. * </ol>
  35538. * </li>
  35539. * </ol>
  35540. *
  35541. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  35542. * <div>
  35543. * <p id="inputDescription1">Without $rollbackViewValue():</p>
  35544. * <input name="value1" aria-describedby="inputDescription1" ng-model="model.value1"
  35545. * ng-keydown="setEmpty($event, 'value1')">
  35546. * value1: "{{ model.value1 }}"
  35547. * </div>
  35548. *
  35549. * <div>
  35550. * <p id="inputDescription2">With $rollbackViewValue():</p>
  35551. * <input name="value2" aria-describedby="inputDescription2" ng-model="model.value2"
  35552. * ng-keydown="setEmpty($event, 'value2', true)">
  35553. * value2: "{{ model.value2 }}"
  35554. * </div>
  35555. * </form>
  35556. * </div>
  35557. * </file>
  35558. <file name="style.css">
  35559. div {
  35560. display: table-cell;
  35561. }
  35562. div:nth-child(1) {
  35563. padding-right: 30px;
  35564. }
  35565. </file>
  35566. * </example>
  35567. */
  35568. this.$rollbackViewValue = function() {
  35569. $timeout.cancel(pendingDebounce);
  35570. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  35571. ctrl.$render();
  35572. };
  35573. /**
  35574. * @ngdoc method
  35575. * @name ngModel.NgModelController#$validate
  35576. *
  35577. * @description
  35578. * Runs each of the registered validators (first synchronous validators and then
  35579. * asynchronous validators).
  35580. * If the validity changes to invalid, the model will be set to `undefined`,
  35581. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  35582. * If the validity changes to valid, it will set the model to the last available valid
  35583. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  35584. */
  35585. this.$validate = function() {
  35586. // ignore $validate before model is initialized
  35587. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  35588. return;
  35589. }
  35590. var viewValue = ctrl.$$lastCommittedViewValue;
  35591. // Note: we use the $$rawModelValue as $modelValue might have been
  35592. // set to undefined during a view -> model update that found validation
  35593. // errors. We can't parse the view here, since that could change
  35594. // the model although neither viewValue nor the model on the scope changed
  35595. var modelValue = ctrl.$$rawModelValue;
  35596. var prevValid = ctrl.$valid;
  35597. var prevModelValue = ctrl.$modelValue;
  35598. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  35599. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  35600. // If there was no change in validity, don't update the model
  35601. // This prevents changing an invalid modelValue to undefined
  35602. if (!allowInvalid && prevValid !== allValid) {
  35603. // Note: Don't check ctrl.$valid here, as we could have
  35604. // external validators (e.g. calculated on the server),
  35605. // that just call $setValidity and need the model value
  35606. // to calculate their validity.
  35607. ctrl.$modelValue = allValid ? modelValue : undefined;
  35608. if (ctrl.$modelValue !== prevModelValue) {
  35609. ctrl.$$writeModelToScope();
  35610. }
  35611. }
  35612. });
  35613. };
  35614. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  35615. currentValidationRunId++;
  35616. var localValidationRunId = currentValidationRunId;
  35617. // check parser error
  35618. if (!processParseErrors()) {
  35619. validationDone(false);
  35620. return;
  35621. }
  35622. if (!processSyncValidators()) {
  35623. validationDone(false);
  35624. return;
  35625. }
  35626. processAsyncValidators();
  35627. function processParseErrors() {
  35628. var errorKey = ctrl.$$parserName || 'parse';
  35629. if (isUndefined(parserValid)) {
  35630. setValidity(errorKey, null);
  35631. } else {
  35632. if (!parserValid) {
  35633. forEach(ctrl.$validators, function(v, name) {
  35634. setValidity(name, null);
  35635. });
  35636. forEach(ctrl.$asyncValidators, function(v, name) {
  35637. setValidity(name, null);
  35638. });
  35639. }
  35640. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  35641. setValidity(errorKey, parserValid);
  35642. return parserValid;
  35643. }
  35644. return true;
  35645. }
  35646. function processSyncValidators() {
  35647. var syncValidatorsValid = true;
  35648. forEach(ctrl.$validators, function(validator, name) {
  35649. var result = validator(modelValue, viewValue);
  35650. syncValidatorsValid = syncValidatorsValid && result;
  35651. setValidity(name, result);
  35652. });
  35653. if (!syncValidatorsValid) {
  35654. forEach(ctrl.$asyncValidators, function(v, name) {
  35655. setValidity(name, null);
  35656. });
  35657. return false;
  35658. }
  35659. return true;
  35660. }
  35661. function processAsyncValidators() {
  35662. var validatorPromises = [];
  35663. var allValid = true;
  35664. forEach(ctrl.$asyncValidators, function(validator, name) {
  35665. var promise = validator(modelValue, viewValue);
  35666. if (!isPromiseLike(promise)) {
  35667. throw ngModelMinErr('nopromise',
  35668. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  35669. }
  35670. setValidity(name, undefined);
  35671. validatorPromises.push(promise.then(function() {
  35672. setValidity(name, true);
  35673. }, function() {
  35674. allValid = false;
  35675. setValidity(name, false);
  35676. }));
  35677. });
  35678. if (!validatorPromises.length) {
  35679. validationDone(true);
  35680. } else {
  35681. $q.all(validatorPromises).then(function() {
  35682. validationDone(allValid);
  35683. }, noop);
  35684. }
  35685. }
  35686. function setValidity(name, isValid) {
  35687. if (localValidationRunId === currentValidationRunId) {
  35688. ctrl.$setValidity(name, isValid);
  35689. }
  35690. }
  35691. function validationDone(allValid) {
  35692. if (localValidationRunId === currentValidationRunId) {
  35693. doneCallback(allValid);
  35694. }
  35695. }
  35696. };
  35697. /**
  35698. * @ngdoc method
  35699. * @name ngModel.NgModelController#$commitViewValue
  35700. *
  35701. * @description
  35702. * Commit a pending update to the `$modelValue`.
  35703. *
  35704. * Updates may be pending by a debounced event or because the input is waiting for a some future
  35705. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  35706. * usually handles calling this in response to input events.
  35707. */
  35708. this.$commitViewValue = function() {
  35709. var viewValue = ctrl.$viewValue;
  35710. $timeout.cancel(pendingDebounce);
  35711. // If the view value has not changed then we should just exit, except in the case where there is
  35712. // a native validator on the element. In this case the validation state may have changed even though
  35713. // the viewValue has stayed empty.
  35714. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  35715. return;
  35716. }
  35717. ctrl.$$updateEmptyClasses(viewValue);
  35718. ctrl.$$lastCommittedViewValue = viewValue;
  35719. // change to dirty
  35720. if (ctrl.$pristine) {
  35721. this.$setDirty();
  35722. }
  35723. this.$$parseAndValidate();
  35724. };
  35725. this.$$parseAndValidate = function() {
  35726. var viewValue = ctrl.$$lastCommittedViewValue;
  35727. var modelValue = viewValue;
  35728. parserValid = isUndefined(modelValue) ? undefined : true;
  35729. if (parserValid) {
  35730. for (var i = 0; i < ctrl.$parsers.length; i++) {
  35731. modelValue = ctrl.$parsers[i](modelValue);
  35732. if (isUndefined(modelValue)) {
  35733. parserValid = false;
  35734. break;
  35735. }
  35736. }
  35737. }
  35738. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  35739. // ctrl.$modelValue has not been touched yet...
  35740. ctrl.$modelValue = ngModelGet($scope);
  35741. }
  35742. var prevModelValue = ctrl.$modelValue;
  35743. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  35744. ctrl.$$rawModelValue = modelValue;
  35745. if (allowInvalid) {
  35746. ctrl.$modelValue = modelValue;
  35747. writeToModelIfNeeded();
  35748. }
  35749. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  35750. // This can happen if e.g. $setViewValue is called from inside a parser
  35751. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  35752. if (!allowInvalid) {
  35753. // Note: Don't check ctrl.$valid here, as we could have
  35754. // external validators (e.g. calculated on the server),
  35755. // that just call $setValidity and need the model value
  35756. // to calculate their validity.
  35757. ctrl.$modelValue = allValid ? modelValue : undefined;
  35758. writeToModelIfNeeded();
  35759. }
  35760. });
  35761. function writeToModelIfNeeded() {
  35762. if (ctrl.$modelValue !== prevModelValue) {
  35763. ctrl.$$writeModelToScope();
  35764. }
  35765. }
  35766. };
  35767. this.$$writeModelToScope = function() {
  35768. ngModelSet($scope, ctrl.$modelValue);
  35769. forEach(ctrl.$viewChangeListeners, function(listener) {
  35770. try {
  35771. listener();
  35772. } catch (e) {
  35773. $exceptionHandler(e);
  35774. }
  35775. });
  35776. };
  35777. /**
  35778. * @ngdoc method
  35779. * @name ngModel.NgModelController#$setViewValue
  35780. *
  35781. * @description
  35782. * Update the view value.
  35783. *
  35784. * This method should be called when a control wants to change the view value; typically,
  35785. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  35786. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  35787. * calls it when an option is selected.
  35788. *
  35789. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  35790. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  35791. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  35792. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  35793. * in the `$viewChangeListeners` list, are called.
  35794. *
  35795. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  35796. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  35797. * `updateOn` events is triggered on the DOM element.
  35798. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  35799. * directive is used with a custom debounce for this particular event.
  35800. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  35801. * is specified, once the timer runs out.
  35802. *
  35803. * When used with standard inputs, the view value will always be a string (which is in some cases
  35804. * parsed into another type, such as a `Date` object for `input[date]`.)
  35805. * However, custom controls might also pass objects to this method. In this case, we should make
  35806. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  35807. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  35808. * the property of the object then ngModel will not realize that the object has changed and
  35809. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  35810. * not change properties of the copy once it has been passed to `$setViewValue`.
  35811. * Otherwise you may cause the model value on the scope to change incorrectly.
  35812. *
  35813. * <div class="alert alert-info">
  35814. * In any case, the value passed to the method should always reflect the current value
  35815. * of the control. For example, if you are calling `$setViewValue` for an input element,
  35816. * you should pass the input DOM value. Otherwise, the control and the scope model become
  35817. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  35818. * the control's DOM value in any way. If we want to change the control's DOM value
  35819. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  35820. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  35821. * to update the DOM, and finally call `$validate` on it.
  35822. * </div>
  35823. *
  35824. * @param {*} value value from the view.
  35825. * @param {string} trigger Event that triggered the update.
  35826. */
  35827. this.$setViewValue = function(value, trigger) {
  35828. ctrl.$viewValue = value;
  35829. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  35830. ctrl.$$debounceViewValueCommit(trigger);
  35831. }
  35832. };
  35833. this.$$debounceViewValueCommit = function(trigger) {
  35834. var debounceDelay = 0,
  35835. options = ctrl.$options,
  35836. debounce;
  35837. if (options && isDefined(options.debounce)) {
  35838. debounce = options.debounce;
  35839. if (isNumber(debounce)) {
  35840. debounceDelay = debounce;
  35841. } else if (isNumber(debounce[trigger])) {
  35842. debounceDelay = debounce[trigger];
  35843. } else if (isNumber(debounce['default'])) {
  35844. debounceDelay = debounce['default'];
  35845. }
  35846. }
  35847. $timeout.cancel(pendingDebounce);
  35848. if (debounceDelay) {
  35849. pendingDebounce = $timeout(function() {
  35850. ctrl.$commitViewValue();
  35851. }, debounceDelay);
  35852. } else if ($rootScope.$$phase) {
  35853. ctrl.$commitViewValue();
  35854. } else {
  35855. $scope.$apply(function() {
  35856. ctrl.$commitViewValue();
  35857. });
  35858. }
  35859. };
  35860. // model -> value
  35861. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  35862. // 1. scope value is 'a'
  35863. // 2. user enters 'b'
  35864. // 3. ng-change kicks in and reverts scope value to 'a'
  35865. // -> scope value did not change since the last digest as
  35866. // ng-change executes in apply phase
  35867. // 4. view should be changed back to 'a'
  35868. $scope.$watch(function ngModelWatch() {
  35869. var modelValue = ngModelGet($scope);
  35870. // if scope model value and ngModel value are out of sync
  35871. // TODO(perf): why not move this to the action fn?
  35872. if (modelValue !== ctrl.$modelValue &&
  35873. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  35874. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  35875. ) {
  35876. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  35877. parserValid = undefined;
  35878. var formatters = ctrl.$formatters,
  35879. idx = formatters.length;
  35880. var viewValue = modelValue;
  35881. while (idx--) {
  35882. viewValue = formatters[idx](viewValue);
  35883. }
  35884. if (ctrl.$viewValue !== viewValue) {
  35885. ctrl.$$updateEmptyClasses(viewValue);
  35886. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  35887. ctrl.$render();
  35888. ctrl.$$runValidators(modelValue, viewValue, noop);
  35889. }
  35890. }
  35891. return modelValue;
  35892. });
  35893. }];
  35894. /**
  35895. * @ngdoc directive
  35896. * @name ngModel
  35897. *
  35898. * @element input
  35899. * @priority 1
  35900. *
  35901. * @description
  35902. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  35903. * property on the scope using {@link ngModel.NgModelController NgModelController},
  35904. * which is created and exposed by this directive.
  35905. *
  35906. * `ngModel` is responsible for:
  35907. *
  35908. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  35909. * require.
  35910. * - Providing validation behavior (i.e. required, number, email, url).
  35911. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  35912. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`,
  35913. * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations.
  35914. * - Registering the control with its parent {@link ng.directive:form form}.
  35915. *
  35916. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  35917. * current scope. If the property doesn't already exist on this scope, it will be created
  35918. * implicitly and added to the scope.
  35919. *
  35920. * For best practices on using `ngModel`, see:
  35921. *
  35922. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  35923. *
  35924. * For basic examples, how to use `ngModel`, see:
  35925. *
  35926. * - {@link ng.directive:input input}
  35927. * - {@link input[text] text}
  35928. * - {@link input[checkbox] checkbox}
  35929. * - {@link input[radio] radio}
  35930. * - {@link input[number] number}
  35931. * - {@link input[email] email}
  35932. * - {@link input[url] url}
  35933. * - {@link input[date] date}
  35934. * - {@link input[datetime-local] datetime-local}
  35935. * - {@link input[time] time}
  35936. * - {@link input[month] month}
  35937. * - {@link input[week] week}
  35938. * - {@link ng.directive:select select}
  35939. * - {@link ng.directive:textarea textarea}
  35940. *
  35941. * # Complex Models (objects or collections)
  35942. *
  35943. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  35944. * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the
  35945. * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered.
  35946. *
  35947. * The model must be assigned an entirely new object or collection before a re-rendering will occur.
  35948. *
  35949. * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression
  35950. * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or
  35951. * if the select is given the `multiple` attribute.
  35952. *
  35953. * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the
  35954. * first level of the object (or only changing the properties of an item in the collection if it's an array) will still
  35955. * not trigger a re-rendering of the model.
  35956. *
  35957. * # CSS classes
  35958. * The following CSS classes are added and removed on the associated input/select/textarea element
  35959. * depending on the validity of the model.
  35960. *
  35961. * - `ng-valid`: the model is valid
  35962. * - `ng-invalid`: the model is invalid
  35963. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  35964. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  35965. * - `ng-pristine`: the control hasn't been interacted with yet
  35966. * - `ng-dirty`: the control has been interacted with
  35967. * - `ng-touched`: the control has been blurred
  35968. * - `ng-untouched`: the control hasn't been blurred
  35969. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  35970. * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined
  35971. * by the {@link ngModel.NgModelController#$isEmpty} method
  35972. * - `ng-not-empty`: the view contains a non-empty value
  35973. *
  35974. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  35975. *
  35976. * ## Animation Hooks
  35977. *
  35978. * Animations within models are triggered when any of the associated CSS classes are added and removed
  35979. * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`,
  35980. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  35981. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  35982. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  35983. *
  35984. * The following example shows a simple way to utilize CSS transitions to style an input element
  35985. * that has been rendered as invalid after it has been validated:
  35986. *
  35987. * <pre>
  35988. * //be sure to include ngAnimate as a module to hook into more
  35989. * //advanced animations
  35990. * .my-input {
  35991. * transition:0.5s linear all;
  35992. * background: white;
  35993. * }
  35994. * .my-input.ng-invalid {
  35995. * background: red;
  35996. * color:white;
  35997. * }
  35998. * </pre>
  35999. *
  36000. * @example
  36001. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  36002. <file name="index.html">
  36003. <script>
  36004. angular.module('inputExample', [])
  36005. .controller('ExampleController', ['$scope', function($scope) {
  36006. $scope.val = '1';
  36007. }]);
  36008. </script>
  36009. <style>
  36010. .my-input {
  36011. transition:all linear 0.5s;
  36012. background: transparent;
  36013. }
  36014. .my-input.ng-invalid {
  36015. color:white;
  36016. background: red;
  36017. }
  36018. </style>
  36019. <p id="inputDescription">
  36020. Update input to see transitions when valid/invalid.
  36021. Integer is a valid value.
  36022. </p>
  36023. <form name="testForm" ng-controller="ExampleController">
  36024. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  36025. aria-describedby="inputDescription" />
  36026. </form>
  36027. </file>
  36028. * </example>
  36029. *
  36030. * ## Binding to a getter/setter
  36031. *
  36032. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  36033. * function that returns a representation of the model when called with zero arguments, and sets
  36034. * the internal state of a model when called with an argument. It's sometimes useful to use this
  36035. * for models that have an internal representation that's different from what the model exposes
  36036. * to the view.
  36037. *
  36038. * <div class="alert alert-success">
  36039. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  36040. * frequently than other parts of your code.
  36041. * </div>
  36042. *
  36043. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  36044. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  36045. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  36046. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  36047. *
  36048. * The following example shows how to use `ngModel` with a getter/setter:
  36049. *
  36050. * @example
  36051. * <example name="ngModel-getter-setter" module="getterSetterExample">
  36052. <file name="index.html">
  36053. <div ng-controller="ExampleController">
  36054. <form name="userForm">
  36055. <label>Name:
  36056. <input type="text" name="userName"
  36057. ng-model="user.name"
  36058. ng-model-options="{ getterSetter: true }" />
  36059. </label>
  36060. </form>
  36061. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  36062. </div>
  36063. </file>
  36064. <file name="app.js">
  36065. angular.module('getterSetterExample', [])
  36066. .controller('ExampleController', ['$scope', function($scope) {
  36067. var _name = 'Brian';
  36068. $scope.user = {
  36069. name: function(newName) {
  36070. // Note that newName can be undefined for two reasons:
  36071. // 1. Because it is called as a getter and thus called with no arguments
  36072. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  36073. // input is invalid
  36074. return arguments.length ? (_name = newName) : _name;
  36075. }
  36076. };
  36077. }]);
  36078. </file>
  36079. * </example>
  36080. */
  36081. var ngModelDirective = ['$rootScope', function($rootScope) {
  36082. return {
  36083. restrict: 'A',
  36084. require: ['ngModel', '^?form', '^?ngModelOptions'],
  36085. controller: NgModelController,
  36086. // Prelink needs to run before any input directive
  36087. // so that we can set the NgModelOptions in NgModelController
  36088. // before anyone else uses it.
  36089. priority: 1,
  36090. compile: function ngModelCompile(element) {
  36091. // Setup initial state of the control
  36092. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  36093. return {
  36094. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  36095. var modelCtrl = ctrls[0],
  36096. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  36097. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  36098. // notify others, especially parent forms
  36099. formCtrl.$addControl(modelCtrl);
  36100. attr.$observe('name', function(newValue) {
  36101. if (modelCtrl.$name !== newValue) {
  36102. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  36103. }
  36104. });
  36105. scope.$on('$destroy', function() {
  36106. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  36107. });
  36108. },
  36109. post: function ngModelPostLink(scope, element, attr, ctrls) {
  36110. var modelCtrl = ctrls[0];
  36111. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  36112. element.on(modelCtrl.$options.updateOn, function(ev) {
  36113. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  36114. });
  36115. }
  36116. element.on('blur', function() {
  36117. if (modelCtrl.$touched) return;
  36118. if ($rootScope.$$phase) {
  36119. scope.$evalAsync(modelCtrl.$setTouched);
  36120. } else {
  36121. scope.$apply(modelCtrl.$setTouched);
  36122. }
  36123. });
  36124. }
  36125. };
  36126. }
  36127. };
  36128. }];
  36129. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  36130. /**
  36131. * @ngdoc directive
  36132. * @name ngModelOptions
  36133. *
  36134. * @description
  36135. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  36136. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  36137. * takes place when a timer expires; this timer will be reset after another change takes place.
  36138. *
  36139. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  36140. * be different from the value in the actual model. This means that if you update the model you
  36141. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  36142. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  36143. *
  36144. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  36145. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  36146. * important because `form` controllers are published to the related scope under the name in their
  36147. * `name` attribute.
  36148. *
  36149. * Any pending changes will take place immediately when an enclosing form is submitted via the
  36150. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  36151. * to have access to the updated model.
  36152. *
  36153. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  36154. *
  36155. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  36156. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  36157. * events using an space delimited list. There is a special event called `default` that
  36158. * matches the default events belonging of the control.
  36159. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  36160. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  36161. * custom value for each event. For example:
  36162. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  36163. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  36164. * not validate correctly instead of the default behavior of setting the model to undefined.
  36165. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  36166. `ngModel` as getters/setters.
  36167. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  36168. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  36169. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  36170. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  36171. * If not specified, the timezone of the browser will be used.
  36172. *
  36173. * @example
  36174. The following example shows how to override immediate updates. Changes on the inputs within the
  36175. form will update the model only when the control loses focus (blur event). If `escape` key is
  36176. pressed while the input field is focused, the value is reset to the value in the current model.
  36177. <example name="ngModelOptions-directive-blur" module="optionsExample">
  36178. <file name="index.html">
  36179. <div ng-controller="ExampleController">
  36180. <form name="userForm">
  36181. <label>Name:
  36182. <input type="text" name="userName"
  36183. ng-model="user.name"
  36184. ng-model-options="{ updateOn: 'blur' }"
  36185. ng-keyup="cancel($event)" />
  36186. </label><br />
  36187. <label>Other data:
  36188. <input type="text" ng-model="user.data" />
  36189. </label><br />
  36190. </form>
  36191. <pre>user.name = <span ng-bind="user.name"></span></pre>
  36192. <pre>user.data = <span ng-bind="user.data"></span></pre>
  36193. </div>
  36194. </file>
  36195. <file name="app.js">
  36196. angular.module('optionsExample', [])
  36197. .controller('ExampleController', ['$scope', function($scope) {
  36198. $scope.user = { name: 'John', data: '' };
  36199. $scope.cancel = function(e) {
  36200. if (e.keyCode == 27) {
  36201. $scope.userForm.userName.$rollbackViewValue();
  36202. }
  36203. };
  36204. }]);
  36205. </file>
  36206. <file name="protractor.js" type="protractor">
  36207. var model = element(by.binding('user.name'));
  36208. var input = element(by.model('user.name'));
  36209. var other = element(by.model('user.data'));
  36210. it('should allow custom events', function() {
  36211. input.sendKeys(' Doe');
  36212. input.click();
  36213. expect(model.getText()).toEqual('John');
  36214. other.click();
  36215. expect(model.getText()).toEqual('John Doe');
  36216. });
  36217. it('should $rollbackViewValue when model changes', function() {
  36218. input.sendKeys(' Doe');
  36219. expect(input.getAttribute('value')).toEqual('John Doe');
  36220. input.sendKeys(protractor.Key.ESCAPE);
  36221. expect(input.getAttribute('value')).toEqual('John');
  36222. other.click();
  36223. expect(model.getText()).toEqual('John');
  36224. });
  36225. </file>
  36226. </example>
  36227. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  36228. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  36229. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  36230. <file name="index.html">
  36231. <div ng-controller="ExampleController">
  36232. <form name="userForm">
  36233. <label>Name:
  36234. <input type="text" name="userName"
  36235. ng-model="user.name"
  36236. ng-model-options="{ debounce: 1000 }" />
  36237. </label>
  36238. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  36239. <br />
  36240. </form>
  36241. <pre>user.name = <span ng-bind="user.name"></span></pre>
  36242. </div>
  36243. </file>
  36244. <file name="app.js">
  36245. angular.module('optionsExample', [])
  36246. .controller('ExampleController', ['$scope', function($scope) {
  36247. $scope.user = { name: 'Igor' };
  36248. }]);
  36249. </file>
  36250. </example>
  36251. This one shows how to bind to getter/setters:
  36252. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  36253. <file name="index.html">
  36254. <div ng-controller="ExampleController">
  36255. <form name="userForm">
  36256. <label>Name:
  36257. <input type="text" name="userName"
  36258. ng-model="user.name"
  36259. ng-model-options="{ getterSetter: true }" />
  36260. </label>
  36261. </form>
  36262. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  36263. </div>
  36264. </file>
  36265. <file name="app.js">
  36266. angular.module('getterSetterExample', [])
  36267. .controller('ExampleController', ['$scope', function($scope) {
  36268. var _name = 'Brian';
  36269. $scope.user = {
  36270. name: function(newName) {
  36271. // Note that newName can be undefined for two reasons:
  36272. // 1. Because it is called as a getter and thus called with no arguments
  36273. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  36274. // input is invalid
  36275. return arguments.length ? (_name = newName) : _name;
  36276. }
  36277. };
  36278. }]);
  36279. </file>
  36280. </example>
  36281. */
  36282. var ngModelOptionsDirective = function() {
  36283. return {
  36284. restrict: 'A',
  36285. controller: ['$scope', '$attrs', function($scope, $attrs) {
  36286. var that = this;
  36287. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  36288. // Allow adding/overriding bound events
  36289. if (isDefined(this.$options.updateOn)) {
  36290. this.$options.updateOnDefault = false;
  36291. // extract "default" pseudo-event from list of events that can trigger a model update
  36292. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  36293. that.$options.updateOnDefault = true;
  36294. return ' ';
  36295. }));
  36296. } else {
  36297. this.$options.updateOnDefault = true;
  36298. }
  36299. }]
  36300. };
  36301. };
  36302. // helper methods
  36303. function addSetValidityMethod(context) {
  36304. var ctrl = context.ctrl,
  36305. $element = context.$element,
  36306. classCache = {},
  36307. set = context.set,
  36308. unset = context.unset,
  36309. $animate = context.$animate;
  36310. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  36311. ctrl.$setValidity = setValidity;
  36312. function setValidity(validationErrorKey, state, controller) {
  36313. if (isUndefined(state)) {
  36314. createAndSet('$pending', validationErrorKey, controller);
  36315. } else {
  36316. unsetAndCleanup('$pending', validationErrorKey, controller);
  36317. }
  36318. if (!isBoolean(state)) {
  36319. unset(ctrl.$error, validationErrorKey, controller);
  36320. unset(ctrl.$$success, validationErrorKey, controller);
  36321. } else {
  36322. if (state) {
  36323. unset(ctrl.$error, validationErrorKey, controller);
  36324. set(ctrl.$$success, validationErrorKey, controller);
  36325. } else {
  36326. set(ctrl.$error, validationErrorKey, controller);
  36327. unset(ctrl.$$success, validationErrorKey, controller);
  36328. }
  36329. }
  36330. if (ctrl.$pending) {
  36331. cachedToggleClass(PENDING_CLASS, true);
  36332. ctrl.$valid = ctrl.$invalid = undefined;
  36333. toggleValidationCss('', null);
  36334. } else {
  36335. cachedToggleClass(PENDING_CLASS, false);
  36336. ctrl.$valid = isObjectEmpty(ctrl.$error);
  36337. ctrl.$invalid = !ctrl.$valid;
  36338. toggleValidationCss('', ctrl.$valid);
  36339. }
  36340. // re-read the state as the set/unset methods could have
  36341. // combined state in ctrl.$error[validationError] (used for forms),
  36342. // where setting/unsetting only increments/decrements the value,
  36343. // and does not replace it.
  36344. var combinedState;
  36345. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  36346. combinedState = undefined;
  36347. } else if (ctrl.$error[validationErrorKey]) {
  36348. combinedState = false;
  36349. } else if (ctrl.$$success[validationErrorKey]) {
  36350. combinedState = true;
  36351. } else {
  36352. combinedState = null;
  36353. }
  36354. toggleValidationCss(validationErrorKey, combinedState);
  36355. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  36356. }
  36357. function createAndSet(name, value, controller) {
  36358. if (!ctrl[name]) {
  36359. ctrl[name] = {};
  36360. }
  36361. set(ctrl[name], value, controller);
  36362. }
  36363. function unsetAndCleanup(name, value, controller) {
  36364. if (ctrl[name]) {
  36365. unset(ctrl[name], value, controller);
  36366. }
  36367. if (isObjectEmpty(ctrl[name])) {
  36368. ctrl[name] = undefined;
  36369. }
  36370. }
  36371. function cachedToggleClass(className, switchValue) {
  36372. if (switchValue && !classCache[className]) {
  36373. $animate.addClass($element, className);
  36374. classCache[className] = true;
  36375. } else if (!switchValue && classCache[className]) {
  36376. $animate.removeClass($element, className);
  36377. classCache[className] = false;
  36378. }
  36379. }
  36380. function toggleValidationCss(validationErrorKey, isValid) {
  36381. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  36382. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  36383. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  36384. }
  36385. }
  36386. function isObjectEmpty(obj) {
  36387. if (obj) {
  36388. for (var prop in obj) {
  36389. if (obj.hasOwnProperty(prop)) {
  36390. return false;
  36391. }
  36392. }
  36393. }
  36394. return true;
  36395. }
  36396. /**
  36397. * @ngdoc directive
  36398. * @name ngNonBindable
  36399. * @restrict AC
  36400. * @priority 1000
  36401. *
  36402. * @description
  36403. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  36404. * DOM element. This is useful if the element contains what appears to be Angular directives and
  36405. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  36406. * displays snippets of code, for instance.
  36407. *
  36408. * @element ANY
  36409. *
  36410. * @example
  36411. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  36412. * but the one wrapped in `ngNonBindable` is left alone.
  36413. *
  36414. * @example
  36415. <example>
  36416. <file name="index.html">
  36417. <div>Normal: {{1 + 2}}</div>
  36418. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  36419. </file>
  36420. <file name="protractor.js" type="protractor">
  36421. it('should check ng-non-bindable', function() {
  36422. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  36423. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  36424. });
  36425. </file>
  36426. </example>
  36427. */
  36428. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  36429. /* global jqLiteRemove */
  36430. var ngOptionsMinErr = minErr('ngOptions');
  36431. /**
  36432. * @ngdoc directive
  36433. * @name ngOptions
  36434. * @restrict A
  36435. *
  36436. * @description
  36437. *
  36438. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  36439. * elements for the `<select>` element using the array or object obtained by evaluating the
  36440. * `ngOptions` comprehension expression.
  36441. *
  36442. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  36443. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  36444. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  36445. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  36446. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  36447. * to a non-string value. This is because an option element can only be bound to string values at
  36448. * present.
  36449. *
  36450. * When an item in the `<select>` menu is selected, the array element or object property
  36451. * represented by the selected option will be bound to the model identified by the `ngModel`
  36452. * directive.
  36453. *
  36454. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  36455. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  36456. * option. See example below for demonstration.
  36457. *
  36458. * ## Complex Models (objects or collections)
  36459. *
  36460. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  36461. * binding the select to a model that is an object or a collection.
  36462. *
  36463. * One issue occurs if you want to preselect an option. For example, if you set
  36464. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  36465. * because the objects are not identical. So by default, you should always reference the item in your collection
  36466. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  36467. *
  36468. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  36469. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  36470. * collection items have an id property, you would `track by item.id`.
  36471. *
  36472. * A different issue with objects or collections is that ngModel won't detect if an object property or
  36473. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  36474. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  36475. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  36476. * has not changed identity, but only a property on the object or an item in the collection changes.
  36477. *
  36478. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  36479. * if the model is an array). This means that changing a property deeper than the first level inside the
  36480. * object/collection will not trigger a re-rendering.
  36481. *
  36482. * ## `select` **`as`**
  36483. *
  36484. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  36485. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  36486. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  36487. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  36488. *
  36489. *
  36490. * ### `select` **`as`** and **`track by`**
  36491. *
  36492. * <div class="alert alert-warning">
  36493. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  36494. * </div>
  36495. *
  36496. * Given this array of items on the $scope:
  36497. *
  36498. * ```js
  36499. * $scope.items = [{
  36500. * id: 1,
  36501. * label: 'aLabel',
  36502. * subItem: { name: 'aSubItem' }
  36503. * }, {
  36504. * id: 2,
  36505. * label: 'bLabel',
  36506. * subItem: { name: 'bSubItem' }
  36507. * }];
  36508. * ```
  36509. *
  36510. * This will work:
  36511. *
  36512. * ```html
  36513. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  36514. * ```
  36515. * ```js
  36516. * $scope.selected = $scope.items[0];
  36517. * ```
  36518. *
  36519. * but this will not work:
  36520. *
  36521. * ```html
  36522. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  36523. * ```
  36524. * ```js
  36525. * $scope.selected = $scope.items[0].subItem;
  36526. * ```
  36527. *
  36528. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  36529. * `items` array. Because the selected option has been set programmatically in the controller, the
  36530. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  36531. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  36532. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  36533. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  36534. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  36535. *
  36536. *
  36537. * @param {string} ngModel Assignable angular expression to data-bind to.
  36538. * @param {string=} name Property name of the form under which the control is published.
  36539. * @param {string=} required The control is considered valid only if value is entered.
  36540. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  36541. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  36542. * `required` when you want to data-bind to the `required` attribute.
  36543. * @param {comprehension_expression=} ngOptions in one of the following forms:
  36544. *
  36545. * * for array data sources:
  36546. * * `label` **`for`** `value` **`in`** `array`
  36547. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  36548. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  36549. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  36550. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  36551. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  36552. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  36553. * (for including a filter with `track by`)
  36554. * * for object data sources:
  36555. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  36556. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  36557. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  36558. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  36559. * * `select` **`as`** `label` **`group by`** `group`
  36560. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  36561. * * `select` **`as`** `label` **`disable when`** `disable`
  36562. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  36563. *
  36564. * Where:
  36565. *
  36566. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  36567. * * `value`: local variable which will refer to each item in the `array` or each property value
  36568. * of `object` during iteration.
  36569. * * `key`: local variable which will refer to a property name in `object` during iteration.
  36570. * * `label`: The result of this expression will be the label for `<option>` element. The
  36571. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  36572. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  36573. * element. If not specified, `select` expression will default to `value`.
  36574. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  36575. * DOM element.
  36576. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  36577. * element. Return `true` to disable.
  36578. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  36579. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  36580. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  36581. * even when the options are recreated (e.g. reloaded from the server).
  36582. *
  36583. * @example
  36584. <example module="selectExample">
  36585. <file name="index.html">
  36586. <script>
  36587. angular.module('selectExample', [])
  36588. .controller('ExampleController', ['$scope', function($scope) {
  36589. $scope.colors = [
  36590. {name:'black', shade:'dark'},
  36591. {name:'white', shade:'light', notAnOption: true},
  36592. {name:'red', shade:'dark'},
  36593. {name:'blue', shade:'dark', notAnOption: true},
  36594. {name:'yellow', shade:'light', notAnOption: false}
  36595. ];
  36596. $scope.myColor = $scope.colors[2]; // red
  36597. }]);
  36598. </script>
  36599. <div ng-controller="ExampleController">
  36600. <ul>
  36601. <li ng-repeat="color in colors">
  36602. <label>Name: <input ng-model="color.name"></label>
  36603. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  36604. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  36605. </li>
  36606. <li>
  36607. <button ng-click="colors.push({})">add</button>
  36608. </li>
  36609. </ul>
  36610. <hr/>
  36611. <label>Color (null not allowed):
  36612. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  36613. </label><br/>
  36614. <label>Color (null allowed):
  36615. <span class="nullable">
  36616. <select ng-model="myColor" ng-options="color.name for color in colors">
  36617. <option value="">-- choose color --</option>
  36618. </select>
  36619. </span></label><br/>
  36620. <label>Color grouped by shade:
  36621. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  36622. </select>
  36623. </label><br/>
  36624. <label>Color grouped by shade, with some disabled:
  36625. <select ng-model="myColor"
  36626. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  36627. </select>
  36628. </label><br/>
  36629. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  36630. <br/>
  36631. <hr/>
  36632. Currently selected: {{ {selected_color:myColor} }}
  36633. <div style="border:solid 1px black; height:20px"
  36634. ng-style="{'background-color':myColor.name}">
  36635. </div>
  36636. </div>
  36637. </file>
  36638. <file name="protractor.js" type="protractor">
  36639. it('should check ng-options', function() {
  36640. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  36641. element.all(by.model('myColor')).first().click();
  36642. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  36643. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  36644. element(by.css('.nullable select[ng-model="myColor"]')).click();
  36645. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  36646. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  36647. });
  36648. </file>
  36649. </example>
  36650. */
  36651. // jshint maxlen: false
  36652. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  36653. 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]+?))?$/;
  36654. // 1: value expression (valueFn)
  36655. // 2: label expression (displayFn)
  36656. // 3: group by expression (groupByFn)
  36657. // 4: disable when expression (disableWhenFn)
  36658. // 5: array item variable name
  36659. // 6: object item key variable name
  36660. // 7: object item value variable name
  36661. // 8: collection expression
  36662. // 9: track by expression
  36663. // jshint maxlen: 100
  36664. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  36665. function parseOptionsExpression(optionsExp, selectElement, scope) {
  36666. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  36667. if (!(match)) {
  36668. throw ngOptionsMinErr('iexp',
  36669. "Expected expression in form of " +
  36670. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  36671. " but got '{0}'. Element: {1}",
  36672. optionsExp, startingTag(selectElement));
  36673. }
  36674. // Extract the parts from the ngOptions expression
  36675. // The variable name for the value of the item in the collection
  36676. var valueName = match[5] || match[7];
  36677. // The variable name for the key of the item in the collection
  36678. var keyName = match[6];
  36679. // An expression that generates the viewValue for an option if there is a label expression
  36680. var selectAs = / as /.test(match[0]) && match[1];
  36681. // An expression that is used to track the id of each object in the options collection
  36682. var trackBy = match[9];
  36683. // An expression that generates the viewValue for an option if there is no label expression
  36684. var valueFn = $parse(match[2] ? match[1] : valueName);
  36685. var selectAsFn = selectAs && $parse(selectAs);
  36686. var viewValueFn = selectAsFn || valueFn;
  36687. var trackByFn = trackBy && $parse(trackBy);
  36688. // Get the value by which we are going to track the option
  36689. // if we have a trackFn then use that (passing scope and locals)
  36690. // otherwise just hash the given viewValue
  36691. var getTrackByValueFn = trackBy ?
  36692. function(value, locals) { return trackByFn(scope, locals); } :
  36693. function getHashOfValue(value) { return hashKey(value); };
  36694. var getTrackByValue = function(value, key) {
  36695. return getTrackByValueFn(value, getLocals(value, key));
  36696. };
  36697. var displayFn = $parse(match[2] || match[1]);
  36698. var groupByFn = $parse(match[3] || '');
  36699. var disableWhenFn = $parse(match[4] || '');
  36700. var valuesFn = $parse(match[8]);
  36701. var locals = {};
  36702. var getLocals = keyName ? function(value, key) {
  36703. locals[keyName] = key;
  36704. locals[valueName] = value;
  36705. return locals;
  36706. } : function(value) {
  36707. locals[valueName] = value;
  36708. return locals;
  36709. };
  36710. function Option(selectValue, viewValue, label, group, disabled) {
  36711. this.selectValue = selectValue;
  36712. this.viewValue = viewValue;
  36713. this.label = label;
  36714. this.group = group;
  36715. this.disabled = disabled;
  36716. }
  36717. function getOptionValuesKeys(optionValues) {
  36718. var optionValuesKeys;
  36719. if (!keyName && isArrayLike(optionValues)) {
  36720. optionValuesKeys = optionValues;
  36721. } else {
  36722. // if object, extract keys, in enumeration order, unsorted
  36723. optionValuesKeys = [];
  36724. for (var itemKey in optionValues) {
  36725. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  36726. optionValuesKeys.push(itemKey);
  36727. }
  36728. }
  36729. }
  36730. return optionValuesKeys;
  36731. }
  36732. return {
  36733. trackBy: trackBy,
  36734. getTrackByValue: getTrackByValue,
  36735. getWatchables: $parse(valuesFn, function(optionValues) {
  36736. // Create a collection of things that we would like to watch (watchedArray)
  36737. // so that they can all be watched using a single $watchCollection
  36738. // that only runs the handler once if anything changes
  36739. var watchedArray = [];
  36740. optionValues = optionValues || [];
  36741. var optionValuesKeys = getOptionValuesKeys(optionValues);
  36742. var optionValuesLength = optionValuesKeys.length;
  36743. for (var index = 0; index < optionValuesLength; index++) {
  36744. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  36745. var value = optionValues[key];
  36746. var locals = getLocals(value, key);
  36747. var selectValue = getTrackByValueFn(value, locals);
  36748. watchedArray.push(selectValue);
  36749. // Only need to watch the displayFn if there is a specific label expression
  36750. if (match[2] || match[1]) {
  36751. var label = displayFn(scope, locals);
  36752. watchedArray.push(label);
  36753. }
  36754. // Only need to watch the disableWhenFn if there is a specific disable expression
  36755. if (match[4]) {
  36756. var disableWhen = disableWhenFn(scope, locals);
  36757. watchedArray.push(disableWhen);
  36758. }
  36759. }
  36760. return watchedArray;
  36761. }),
  36762. getOptions: function() {
  36763. var optionItems = [];
  36764. var selectValueMap = {};
  36765. // The option values were already computed in the `getWatchables` fn,
  36766. // which must have been called to trigger `getOptions`
  36767. var optionValues = valuesFn(scope) || [];
  36768. var optionValuesKeys = getOptionValuesKeys(optionValues);
  36769. var optionValuesLength = optionValuesKeys.length;
  36770. for (var index = 0; index < optionValuesLength; index++) {
  36771. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  36772. var value = optionValues[key];
  36773. var locals = getLocals(value, key);
  36774. var viewValue = viewValueFn(scope, locals);
  36775. var selectValue = getTrackByValueFn(viewValue, locals);
  36776. var label = displayFn(scope, locals);
  36777. var group = groupByFn(scope, locals);
  36778. var disabled = disableWhenFn(scope, locals);
  36779. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  36780. optionItems.push(optionItem);
  36781. selectValueMap[selectValue] = optionItem;
  36782. }
  36783. return {
  36784. items: optionItems,
  36785. selectValueMap: selectValueMap,
  36786. getOptionFromViewValue: function(value) {
  36787. return selectValueMap[getTrackByValue(value)];
  36788. },
  36789. getViewValueFromOption: function(option) {
  36790. // If the viewValue could be an object that may be mutated by the application,
  36791. // we need to make a copy and not return the reference to the value on the option.
  36792. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  36793. }
  36794. };
  36795. }
  36796. };
  36797. }
  36798. // we can't just jqLite('<option>') since jqLite is not smart enough
  36799. // to create it in <select> and IE barfs otherwise.
  36800. var optionTemplate = document.createElement('option'),
  36801. optGroupTemplate = document.createElement('optgroup');
  36802. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  36803. var selectCtrl = ctrls[0];
  36804. var ngModelCtrl = ctrls[1];
  36805. var multiple = attr.multiple;
  36806. // The emptyOption allows the application developer to provide their own custom "empty"
  36807. // option when the viewValue does not match any of the option values.
  36808. var emptyOption;
  36809. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  36810. if (children[i].value === '') {
  36811. emptyOption = children.eq(i);
  36812. break;
  36813. }
  36814. }
  36815. var providedEmptyOption = !!emptyOption;
  36816. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  36817. unknownOption.val('?');
  36818. var options;
  36819. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  36820. var renderEmptyOption = function() {
  36821. if (!providedEmptyOption) {
  36822. selectElement.prepend(emptyOption);
  36823. }
  36824. selectElement.val('');
  36825. emptyOption.prop('selected', true); // needed for IE
  36826. emptyOption.attr('selected', true);
  36827. };
  36828. var removeEmptyOption = function() {
  36829. if (!providedEmptyOption) {
  36830. emptyOption.remove();
  36831. }
  36832. };
  36833. var renderUnknownOption = function() {
  36834. selectElement.prepend(unknownOption);
  36835. selectElement.val('?');
  36836. unknownOption.prop('selected', true); // needed for IE
  36837. unknownOption.attr('selected', true);
  36838. };
  36839. var removeUnknownOption = function() {
  36840. unknownOption.remove();
  36841. };
  36842. // Update the controller methods for multiple selectable options
  36843. if (!multiple) {
  36844. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  36845. var option = options.getOptionFromViewValue(value);
  36846. if (option && !option.disabled) {
  36847. // Don't update the option when it is already selected.
  36848. // For example, the browser will select the first option by default. In that case,
  36849. // most properties are set automatically - except the `selected` attribute, which we
  36850. // set always
  36851. if (selectElement[0].value !== option.selectValue) {
  36852. removeUnknownOption();
  36853. removeEmptyOption();
  36854. selectElement[0].value = option.selectValue;
  36855. option.element.selected = true;
  36856. }
  36857. option.element.setAttribute('selected', 'selected');
  36858. } else {
  36859. if (value === null || providedEmptyOption) {
  36860. removeUnknownOption();
  36861. renderEmptyOption();
  36862. } else {
  36863. removeEmptyOption();
  36864. renderUnknownOption();
  36865. }
  36866. }
  36867. };
  36868. selectCtrl.readValue = function readNgOptionsValue() {
  36869. var selectedOption = options.selectValueMap[selectElement.val()];
  36870. if (selectedOption && !selectedOption.disabled) {
  36871. removeEmptyOption();
  36872. removeUnknownOption();
  36873. return options.getViewValueFromOption(selectedOption);
  36874. }
  36875. return null;
  36876. };
  36877. // If we are using `track by` then we must watch the tracked value on the model
  36878. // since ngModel only watches for object identity change
  36879. if (ngOptions.trackBy) {
  36880. scope.$watch(
  36881. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  36882. function() { ngModelCtrl.$render(); }
  36883. );
  36884. }
  36885. } else {
  36886. ngModelCtrl.$isEmpty = function(value) {
  36887. return !value || value.length === 0;
  36888. };
  36889. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  36890. options.items.forEach(function(option) {
  36891. option.element.selected = false;
  36892. });
  36893. if (value) {
  36894. value.forEach(function(item) {
  36895. var option = options.getOptionFromViewValue(item);
  36896. if (option && !option.disabled) option.element.selected = true;
  36897. });
  36898. }
  36899. };
  36900. selectCtrl.readValue = function readNgOptionsMultiple() {
  36901. var selectedValues = selectElement.val() || [],
  36902. selections = [];
  36903. forEach(selectedValues, function(value) {
  36904. var option = options.selectValueMap[value];
  36905. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  36906. });
  36907. return selections;
  36908. };
  36909. // If we are using `track by` then we must watch these tracked values on the model
  36910. // since ngModel only watches for object identity change
  36911. if (ngOptions.trackBy) {
  36912. scope.$watchCollection(function() {
  36913. if (isArray(ngModelCtrl.$viewValue)) {
  36914. return ngModelCtrl.$viewValue.map(function(value) {
  36915. return ngOptions.getTrackByValue(value);
  36916. });
  36917. }
  36918. }, function() {
  36919. ngModelCtrl.$render();
  36920. });
  36921. }
  36922. }
  36923. if (providedEmptyOption) {
  36924. // we need to remove it before calling selectElement.empty() because otherwise IE will
  36925. // remove the label from the element. wtf?
  36926. emptyOption.remove();
  36927. // compile the element since there might be bindings in it
  36928. $compile(emptyOption)(scope);
  36929. // remove the class, which is added automatically because we recompile the element and it
  36930. // becomes the compilation root
  36931. emptyOption.removeClass('ng-scope');
  36932. } else {
  36933. emptyOption = jqLite(optionTemplate.cloneNode(false));
  36934. }
  36935. // We need to do this here to ensure that the options object is defined
  36936. // when we first hit it in writeNgOptionsValue
  36937. updateOptions();
  36938. // We will re-render the option elements if the option values or labels change
  36939. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  36940. // ------------------------------------------------------------------ //
  36941. function updateOptionElement(option, element) {
  36942. option.element = element;
  36943. element.disabled = option.disabled;
  36944. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  36945. // selects in certain circumstances when multiple selects are next to each other and display
  36946. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  36947. // See https://github.com/angular/angular.js/issues/11314 for more info.
  36948. // This is unfortunately untestable with unit / e2e tests
  36949. if (option.label !== element.label) {
  36950. element.label = option.label;
  36951. element.textContent = option.label;
  36952. }
  36953. if (option.value !== element.value) element.value = option.selectValue;
  36954. }
  36955. function addOrReuseElement(parent, current, type, templateElement) {
  36956. var element;
  36957. // Check whether we can reuse the next element
  36958. if (current && lowercase(current.nodeName) === type) {
  36959. // The next element is the right type so reuse it
  36960. element = current;
  36961. } else {
  36962. // The next element is not the right type so create a new one
  36963. element = templateElement.cloneNode(false);
  36964. if (!current) {
  36965. // There are no more elements so just append it to the select
  36966. parent.appendChild(element);
  36967. } else {
  36968. // The next element is not a group so insert the new one
  36969. parent.insertBefore(element, current);
  36970. }
  36971. }
  36972. return element;
  36973. }
  36974. function removeExcessElements(current) {
  36975. var next;
  36976. while (current) {
  36977. next = current.nextSibling;
  36978. jqLiteRemove(current);
  36979. current = next;
  36980. }
  36981. }
  36982. function skipEmptyAndUnknownOptions(current) {
  36983. var emptyOption_ = emptyOption && emptyOption[0];
  36984. var unknownOption_ = unknownOption && unknownOption[0];
  36985. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  36986. // because the compiled empty option might have been replaced by a comment because
  36987. // it had an "element" transclusion directive on it (such as ngIf)
  36988. if (emptyOption_ || unknownOption_) {
  36989. while (current &&
  36990. (current === emptyOption_ ||
  36991. current === unknownOption_ ||
  36992. current.nodeType === NODE_TYPE_COMMENT ||
  36993. (nodeName_(current) === 'option' && current.value === ''))) {
  36994. current = current.nextSibling;
  36995. }
  36996. }
  36997. return current;
  36998. }
  36999. function updateOptions() {
  37000. var previousValue = options && selectCtrl.readValue();
  37001. options = ngOptions.getOptions();
  37002. var groupMap = {};
  37003. var currentElement = selectElement[0].firstChild;
  37004. // Ensure that the empty option is always there if it was explicitly provided
  37005. if (providedEmptyOption) {
  37006. selectElement.prepend(emptyOption);
  37007. }
  37008. currentElement = skipEmptyAndUnknownOptions(currentElement);
  37009. options.items.forEach(function updateOption(option) {
  37010. var group;
  37011. var groupElement;
  37012. var optionElement;
  37013. if (isDefined(option.group)) {
  37014. // This option is to live in a group
  37015. // See if we have already created this group
  37016. group = groupMap[option.group];
  37017. if (!group) {
  37018. // We have not already created this group
  37019. groupElement = addOrReuseElement(selectElement[0],
  37020. currentElement,
  37021. 'optgroup',
  37022. optGroupTemplate);
  37023. // Move to the next element
  37024. currentElement = groupElement.nextSibling;
  37025. // Update the label on the group element
  37026. groupElement.label = option.group;
  37027. // Store it for use later
  37028. group = groupMap[option.group] = {
  37029. groupElement: groupElement,
  37030. currentOptionElement: groupElement.firstChild
  37031. };
  37032. }
  37033. // So now we have a group for this option we add the option to the group
  37034. optionElement = addOrReuseElement(group.groupElement,
  37035. group.currentOptionElement,
  37036. 'option',
  37037. optionTemplate);
  37038. updateOptionElement(option, optionElement);
  37039. // Move to the next element
  37040. group.currentOptionElement = optionElement.nextSibling;
  37041. } else {
  37042. // This option is not in a group
  37043. optionElement = addOrReuseElement(selectElement[0],
  37044. currentElement,
  37045. 'option',
  37046. optionTemplate);
  37047. updateOptionElement(option, optionElement);
  37048. // Move to the next element
  37049. currentElement = optionElement.nextSibling;
  37050. }
  37051. });
  37052. // Now remove all excess options and group
  37053. Object.keys(groupMap).forEach(function(key) {
  37054. removeExcessElements(groupMap[key].currentOptionElement);
  37055. });
  37056. removeExcessElements(currentElement);
  37057. ngModelCtrl.$render();
  37058. // Check to see if the value has changed due to the update to the options
  37059. if (!ngModelCtrl.$isEmpty(previousValue)) {
  37060. var nextValue = selectCtrl.readValue();
  37061. var isNotPrimitive = ngOptions.trackBy || multiple;
  37062. if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  37063. ngModelCtrl.$setViewValue(nextValue);
  37064. ngModelCtrl.$render();
  37065. }
  37066. }
  37067. }
  37068. }
  37069. return {
  37070. restrict: 'A',
  37071. terminal: true,
  37072. require: ['select', 'ngModel'],
  37073. link: {
  37074. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  37075. // Deactivate the SelectController.register method to prevent
  37076. // option directives from accidentally registering themselves
  37077. // (and unwanted $destroy handlers etc.)
  37078. ctrls[0].registerOption = noop;
  37079. },
  37080. post: ngOptionsPostLink
  37081. }
  37082. };
  37083. }];
  37084. /**
  37085. * @ngdoc directive
  37086. * @name ngPluralize
  37087. * @restrict EA
  37088. *
  37089. * @description
  37090. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  37091. * These rules are bundled with angular.js, but can be overridden
  37092. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  37093. * by specifying the mappings between
  37094. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  37095. * and the strings to be displayed.
  37096. *
  37097. * # Plural categories and explicit number rules
  37098. * There are two
  37099. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  37100. * in Angular's default en-US locale: "one" and "other".
  37101. *
  37102. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  37103. * any number that is not 1), an explicit number rule can only match one number. For example, the
  37104. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  37105. * and explicit number rules throughout the rest of this documentation.
  37106. *
  37107. * # Configuring ngPluralize
  37108. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  37109. * You can also provide an optional attribute, `offset`.
  37110. *
  37111. * The value of the `count` attribute can be either a string or an {@link guide/expression
  37112. * Angular expression}; these are evaluated on the current scope for its bound value.
  37113. *
  37114. * The `when` attribute specifies the mappings between plural categories and the actual
  37115. * string to be displayed. The value of the attribute should be a JSON object.
  37116. *
  37117. * The following example shows how to configure ngPluralize:
  37118. *
  37119. * ```html
  37120. * <ng-pluralize count="personCount"
  37121. when="{'0': 'Nobody is viewing.',
  37122. * 'one': '1 person is viewing.',
  37123. * 'other': '{} people are viewing.'}">
  37124. * </ng-pluralize>
  37125. *```
  37126. *
  37127. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  37128. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  37129. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  37130. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  37131. * show "a dozen people are viewing".
  37132. *
  37133. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  37134. * into pluralized strings. In the previous example, Angular will replace `{}` with
  37135. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  37136. * for <span ng-non-bindable>{{numberExpression}}</span>.
  37137. *
  37138. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  37139. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  37140. *
  37141. * # Configuring ngPluralize with offset
  37142. * The `offset` attribute allows further customization of pluralized text, which can result in
  37143. * a better user experience. For example, instead of the message "4 people are viewing this document",
  37144. * you might display "John, Kate and 2 others are viewing this document".
  37145. * The offset attribute allows you to offset a number by any desired value.
  37146. * Let's take a look at an example:
  37147. *
  37148. * ```html
  37149. * <ng-pluralize count="personCount" offset=2
  37150. * when="{'0': 'Nobody is viewing.',
  37151. * '1': '{{person1}} is viewing.',
  37152. * '2': '{{person1}} and {{person2}} are viewing.',
  37153. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  37154. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  37155. * </ng-pluralize>
  37156. * ```
  37157. *
  37158. * Notice that we are still using two plural categories(one, other), but we added
  37159. * three explicit number rules 0, 1 and 2.
  37160. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  37161. * When three people view the document, no explicit number rule is found, so
  37162. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  37163. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  37164. * is shown.
  37165. *
  37166. * Note that when you specify offsets, you must provide explicit number rules for
  37167. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  37168. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  37169. * plural categories "one" and "other".
  37170. *
  37171. * @param {string|expression} count The variable to be bound to.
  37172. * @param {string} when The mapping between plural category to its corresponding strings.
  37173. * @param {number=} offset Offset to deduct from the total number.
  37174. *
  37175. * @example
  37176. <example module="pluralizeExample">
  37177. <file name="index.html">
  37178. <script>
  37179. angular.module('pluralizeExample', [])
  37180. .controller('ExampleController', ['$scope', function($scope) {
  37181. $scope.person1 = 'Igor';
  37182. $scope.person2 = 'Misko';
  37183. $scope.personCount = 1;
  37184. }]);
  37185. </script>
  37186. <div ng-controller="ExampleController">
  37187. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  37188. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  37189. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  37190. <!--- Example with simple pluralization rules for en locale --->
  37191. Without Offset:
  37192. <ng-pluralize count="personCount"
  37193. when="{'0': 'Nobody is viewing.',
  37194. 'one': '1 person is viewing.',
  37195. 'other': '{} people are viewing.'}">
  37196. </ng-pluralize><br>
  37197. <!--- Example with offset --->
  37198. With Offset(2):
  37199. <ng-pluralize count="personCount" offset=2
  37200. when="{'0': 'Nobody is viewing.',
  37201. '1': '{{person1}} is viewing.',
  37202. '2': '{{person1}} and {{person2}} are viewing.',
  37203. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  37204. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  37205. </ng-pluralize>
  37206. </div>
  37207. </file>
  37208. <file name="protractor.js" type="protractor">
  37209. it('should show correct pluralized string', function() {
  37210. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  37211. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  37212. var countInput = element(by.model('personCount'));
  37213. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  37214. expect(withOffset.getText()).toEqual('Igor is viewing.');
  37215. countInput.clear();
  37216. countInput.sendKeys('0');
  37217. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  37218. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  37219. countInput.clear();
  37220. countInput.sendKeys('2');
  37221. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  37222. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  37223. countInput.clear();
  37224. countInput.sendKeys('3');
  37225. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  37226. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  37227. countInput.clear();
  37228. countInput.sendKeys('4');
  37229. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  37230. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  37231. });
  37232. it('should show data-bound names', function() {
  37233. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  37234. var personCount = element(by.model('personCount'));
  37235. var person1 = element(by.model('person1'));
  37236. var person2 = element(by.model('person2'));
  37237. personCount.clear();
  37238. personCount.sendKeys('4');
  37239. person1.clear();
  37240. person1.sendKeys('Di');
  37241. person2.clear();
  37242. person2.sendKeys('Vojta');
  37243. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  37244. });
  37245. </file>
  37246. </example>
  37247. */
  37248. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  37249. var BRACE = /{}/g,
  37250. IS_WHEN = /^when(Minus)?(.+)$/;
  37251. return {
  37252. link: function(scope, element, attr) {
  37253. var numberExp = attr.count,
  37254. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  37255. offset = attr.offset || 0,
  37256. whens = scope.$eval(whenExp) || {},
  37257. whensExpFns = {},
  37258. startSymbol = $interpolate.startSymbol(),
  37259. endSymbol = $interpolate.endSymbol(),
  37260. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  37261. watchRemover = angular.noop,
  37262. lastCount;
  37263. forEach(attr, function(expression, attributeName) {
  37264. var tmpMatch = IS_WHEN.exec(attributeName);
  37265. if (tmpMatch) {
  37266. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  37267. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  37268. }
  37269. });
  37270. forEach(whens, function(expression, key) {
  37271. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  37272. });
  37273. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  37274. var count = parseFloat(newVal);
  37275. var countIsNaN = isNaN(count);
  37276. if (!countIsNaN && !(count in whens)) {
  37277. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  37278. // Otherwise, check it against pluralization rules in $locale service.
  37279. count = $locale.pluralCat(count - offset);
  37280. }
  37281. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  37282. // In JS `NaN !== NaN`, so we have to explicitly check.
  37283. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  37284. watchRemover();
  37285. var whenExpFn = whensExpFns[count];
  37286. if (isUndefined(whenExpFn)) {
  37287. if (newVal != null) {
  37288. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  37289. }
  37290. watchRemover = noop;
  37291. updateElementText();
  37292. } else {
  37293. watchRemover = scope.$watch(whenExpFn, updateElementText);
  37294. }
  37295. lastCount = count;
  37296. }
  37297. });
  37298. function updateElementText(newText) {
  37299. element.text(newText || '');
  37300. }
  37301. }
  37302. };
  37303. }];
  37304. /**
  37305. * @ngdoc directive
  37306. * @name ngRepeat
  37307. * @multiElement
  37308. *
  37309. * @description
  37310. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  37311. * instance gets its own scope, where the given loop variable is set to the current collection item,
  37312. * and `$index` is set to the item index or key.
  37313. *
  37314. * Special properties are exposed on the local scope of each template instance, including:
  37315. *
  37316. * | Variable | Type | Details |
  37317. * |-----------|-----------------|-----------------------------------------------------------------------------|
  37318. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  37319. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  37320. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  37321. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  37322. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  37323. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  37324. *
  37325. * <div class="alert alert-info">
  37326. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  37327. * This may be useful when, for instance, nesting ngRepeats.
  37328. * </div>
  37329. *
  37330. *
  37331. * # Iterating over object properties
  37332. *
  37333. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  37334. * syntax:
  37335. *
  37336. * ```js
  37337. * <div ng-repeat="(key, value) in myObj"> ... </div>
  37338. * ```
  37339. *
  37340. * However, there are a limitations compared to array iteration:
  37341. *
  37342. * - The JavaScript specification does not define the order of keys
  37343. * returned for an object, so Angular relies on the order returned by the browser
  37344. * when running `for key in myObj`. Browsers generally follow the strategy of providing
  37345. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  37346. * and reinstated. See the
  37347. * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  37348. *
  37349. * - `ngRepeat` will silently *ignore* object keys starting with `$`, because
  37350. * it's a prefix used by Angular for public (`$`) and private (`$$`) properties.
  37351. *
  37352. * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with
  37353. * objects, and will throw if used with one.
  37354. *
  37355. * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array
  37356. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  37357. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  37358. * or implement a `$watch` on the object yourself.
  37359. *
  37360. *
  37361. * # Tracking and Duplicates
  37362. *
  37363. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  37364. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  37365. *
  37366. * * When an item is added, a new instance of the template is added to the DOM.
  37367. * * When an item is removed, its template instance is removed from the DOM.
  37368. * * When items are reordered, their respective templates are reordered in the DOM.
  37369. *
  37370. * To minimize creation of DOM elements, `ngRepeat` uses a function
  37371. * to "keep track" of all items in the collection and their corresponding DOM elements.
  37372. * For example, if an item is added to the collection, ngRepeat will know that all other items
  37373. * already have DOM elements, and will not re-render them.
  37374. *
  37375. * The default tracking function (which tracks items by their identity) does not allow
  37376. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  37377. * to maintain a one-to-one mapping between collection items and DOM elements.
  37378. *
  37379. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  37380. * with your own using the `track by` expression.
  37381. *
  37382. * For example, you may track items by the index of each item in the collection, using the
  37383. * special scope property `$index`:
  37384. * ```html
  37385. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  37386. * {{n}}
  37387. * </div>
  37388. * ```
  37389. *
  37390. * You may also use arbitrary expressions in `track by`, including references to custom functions
  37391. * on the scope:
  37392. * ```html
  37393. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  37394. * {{n}}
  37395. * </div>
  37396. * ```
  37397. *
  37398. * <div class="alert alert-success">
  37399. * If you are working with objects that have an identifier property, you should track
  37400. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  37401. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  37402. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  37403. * this significantly improves rendering performance. If you don't have a unique identifier,
  37404. * `track by $index` can also provide a performance boost.
  37405. * </div>
  37406. * ```html
  37407. * <div ng-repeat="model in collection track by model.id">
  37408. * {{model.name}}
  37409. * </div>
  37410. * ```
  37411. *
  37412. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  37413. * `$id` function, which tracks items by their identity:
  37414. * ```html
  37415. * <div ng-repeat="obj in collection track by $id(obj)">
  37416. * {{obj.prop}}
  37417. * </div>
  37418. * ```
  37419. *
  37420. * <div class="alert alert-warning">
  37421. * **Note:** `track by` must always be the last expression:
  37422. * </div>
  37423. * ```
  37424. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  37425. * {{model.name}}
  37426. * </div>
  37427. * ```
  37428. *
  37429. * # Special repeat start and end points
  37430. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  37431. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  37432. * 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)
  37433. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  37434. *
  37435. * The example below makes use of this feature:
  37436. * ```html
  37437. * <header ng-repeat-start="item in items">
  37438. * Header {{ item }}
  37439. * </header>
  37440. * <div class="body">
  37441. * Body {{ item }}
  37442. * </div>
  37443. * <footer ng-repeat-end>
  37444. * Footer {{ item }}
  37445. * </footer>
  37446. * ```
  37447. *
  37448. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  37449. * ```html
  37450. * <header>
  37451. * Header A
  37452. * </header>
  37453. * <div class="body">
  37454. * Body A
  37455. * </div>
  37456. * <footer>
  37457. * Footer A
  37458. * </footer>
  37459. * <header>
  37460. * Header B
  37461. * </header>
  37462. * <div class="body">
  37463. * Body B
  37464. * </div>
  37465. * <footer>
  37466. * Footer B
  37467. * </footer>
  37468. * ```
  37469. *
  37470. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  37471. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  37472. *
  37473. * @animations
  37474. * | Animation | Occurs |
  37475. * |----------------------------------|-------------------------------------|
  37476. * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter |
  37477. * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out |
  37478. * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered |
  37479. *
  37480. * See the example below for defining CSS animations with ngRepeat.
  37481. *
  37482. * @element ANY
  37483. * @scope
  37484. * @priority 1000
  37485. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  37486. * formats are currently supported:
  37487. *
  37488. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  37489. * is a scope expression giving the collection to enumerate.
  37490. *
  37491. * For example: `album in artist.albums`.
  37492. *
  37493. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  37494. * and `expression` is the scope expression giving the collection to enumerate.
  37495. *
  37496. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  37497. *
  37498. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  37499. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  37500. * is specified, ng-repeat associates elements by identity. It is an error to have
  37501. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  37502. * mapped to the same DOM element, which is not possible.)
  37503. *
  37504. * Note that the tracking expression must come last, after any filters, and the alias expression.
  37505. *
  37506. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  37507. * will be associated by item identity in the array.
  37508. *
  37509. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  37510. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  37511. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  37512. * element in the same way in the DOM.
  37513. *
  37514. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  37515. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  37516. * property is same.
  37517. *
  37518. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  37519. * to items in conjunction with a tracking expression.
  37520. *
  37521. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  37522. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  37523. * when a filter is active on the repeater, but the filtered result set is empty.
  37524. *
  37525. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  37526. * the items have been processed through the filter.
  37527. *
  37528. * 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
  37529. * (and not as operator, inside an expression).
  37530. *
  37531. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  37532. *
  37533. * @example
  37534. * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed
  37535. * results by name. New (entering) and removed (leaving) items are animated.
  37536. <example module="ngRepeat" name="ngRepeat" deps="angular-animate.js" animations="true">
  37537. <file name="index.html">
  37538. <div ng-controller="repeatController">
  37539. I have {{friends.length}} friends. They are:
  37540. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  37541. <ul class="example-animate-container">
  37542. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  37543. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  37544. </li>
  37545. <li class="animate-repeat" ng-if="results.length == 0">
  37546. <strong>No results found...</strong>
  37547. </li>
  37548. </ul>
  37549. </div>
  37550. </file>
  37551. <file name="script.js">
  37552. angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) {
  37553. $scope.friends = [
  37554. {name:'John', age:25, gender:'boy'},
  37555. {name:'Jessie', age:30, gender:'girl'},
  37556. {name:'Johanna', age:28, gender:'girl'},
  37557. {name:'Joy', age:15, gender:'girl'},
  37558. {name:'Mary', age:28, gender:'girl'},
  37559. {name:'Peter', age:95, gender:'boy'},
  37560. {name:'Sebastian', age:50, gender:'boy'},
  37561. {name:'Erika', age:27, gender:'girl'},
  37562. {name:'Patrick', age:40, gender:'boy'},
  37563. {name:'Samantha', age:60, gender:'girl'}
  37564. ];
  37565. });
  37566. </file>
  37567. <file name="animations.css">
  37568. .example-animate-container {
  37569. background:white;
  37570. border:1px solid black;
  37571. list-style:none;
  37572. margin:0;
  37573. padding:0 10px;
  37574. }
  37575. .animate-repeat {
  37576. line-height:30px;
  37577. list-style:none;
  37578. box-sizing:border-box;
  37579. }
  37580. .animate-repeat.ng-move,
  37581. .animate-repeat.ng-enter,
  37582. .animate-repeat.ng-leave {
  37583. transition:all linear 0.5s;
  37584. }
  37585. .animate-repeat.ng-leave.ng-leave-active,
  37586. .animate-repeat.ng-move,
  37587. .animate-repeat.ng-enter {
  37588. opacity:0;
  37589. max-height:0;
  37590. }
  37591. .animate-repeat.ng-leave,
  37592. .animate-repeat.ng-move.ng-move-active,
  37593. .animate-repeat.ng-enter.ng-enter-active {
  37594. opacity:1;
  37595. max-height:30px;
  37596. }
  37597. </file>
  37598. <file name="protractor.js" type="protractor">
  37599. var friends = element.all(by.repeater('friend in friends'));
  37600. it('should render initial data set', function() {
  37601. expect(friends.count()).toBe(10);
  37602. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  37603. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  37604. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  37605. expect(element(by.binding('friends.length')).getText())
  37606. .toMatch("I have 10 friends. They are:");
  37607. });
  37608. it('should update repeater when filter predicate changes', function() {
  37609. expect(friends.count()).toBe(10);
  37610. element(by.model('q')).sendKeys('ma');
  37611. expect(friends.count()).toBe(2);
  37612. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  37613. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  37614. });
  37615. </file>
  37616. </example>
  37617. */
  37618. var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) {
  37619. var NG_REMOVED = '$$NG_REMOVED';
  37620. var ngRepeatMinErr = minErr('ngRepeat');
  37621. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  37622. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  37623. scope[valueIdentifier] = value;
  37624. if (keyIdentifier) scope[keyIdentifier] = key;
  37625. scope.$index = index;
  37626. scope.$first = (index === 0);
  37627. scope.$last = (index === (arrayLength - 1));
  37628. scope.$middle = !(scope.$first || scope.$last);
  37629. // jshint bitwise: false
  37630. scope.$odd = !(scope.$even = (index&1) === 0);
  37631. // jshint bitwise: true
  37632. };
  37633. var getBlockStart = function(block) {
  37634. return block.clone[0];
  37635. };
  37636. var getBlockEnd = function(block) {
  37637. return block.clone[block.clone.length - 1];
  37638. };
  37639. return {
  37640. restrict: 'A',
  37641. multiElement: true,
  37642. transclude: 'element',
  37643. priority: 1000,
  37644. terminal: true,
  37645. $$tlb: true,
  37646. compile: function ngRepeatCompile($element, $attr) {
  37647. var expression = $attr.ngRepeat;
  37648. var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression);
  37649. 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*$/);
  37650. if (!match) {
  37651. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  37652. expression);
  37653. }
  37654. var lhs = match[1];
  37655. var rhs = match[2];
  37656. var aliasAs = match[3];
  37657. var trackByExp = match[4];
  37658. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  37659. if (!match) {
  37660. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  37661. lhs);
  37662. }
  37663. var valueIdentifier = match[3] || match[1];
  37664. var keyIdentifier = match[2];
  37665. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  37666. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  37667. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  37668. aliasAs);
  37669. }
  37670. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  37671. var hashFnLocals = {$id: hashKey};
  37672. if (trackByExp) {
  37673. trackByExpGetter = $parse(trackByExp);
  37674. } else {
  37675. trackByIdArrayFn = function(key, value) {
  37676. return hashKey(value);
  37677. };
  37678. trackByIdObjFn = function(key) {
  37679. return key;
  37680. };
  37681. }
  37682. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  37683. if (trackByExpGetter) {
  37684. trackByIdExpFn = function(key, value, index) {
  37685. // assign key, value, and $index to the locals so that they can be used in hash functions
  37686. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  37687. hashFnLocals[valueIdentifier] = value;
  37688. hashFnLocals.$index = index;
  37689. return trackByExpGetter($scope, hashFnLocals);
  37690. };
  37691. }
  37692. // Store a list of elements from previous run. This is a hash where key is the item from the
  37693. // iterator, and the value is objects with following properties.
  37694. // - scope: bound scope
  37695. // - element: previous element.
  37696. // - index: position
  37697. //
  37698. // We are using no-proto object so that we don't need to guard against inherited props via
  37699. // hasOwnProperty.
  37700. var lastBlockMap = createMap();
  37701. //watch props
  37702. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  37703. var index, length,
  37704. previousNode = $element[0], // node that cloned nodes should be inserted after
  37705. // initialized to the comment node anchor
  37706. nextNode,
  37707. // Same as lastBlockMap but it has the current state. It will become the
  37708. // lastBlockMap on the next iteration.
  37709. nextBlockMap = createMap(),
  37710. collectionLength,
  37711. key, value, // key/value of iteration
  37712. trackById,
  37713. trackByIdFn,
  37714. collectionKeys,
  37715. block, // last object information {scope, element, id}
  37716. nextBlockOrder,
  37717. elementsToRemove;
  37718. if (aliasAs) {
  37719. $scope[aliasAs] = collection;
  37720. }
  37721. if (isArrayLike(collection)) {
  37722. collectionKeys = collection;
  37723. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  37724. } else {
  37725. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  37726. // if object, extract keys, in enumeration order, unsorted
  37727. collectionKeys = [];
  37728. for (var itemKey in collection) {
  37729. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  37730. collectionKeys.push(itemKey);
  37731. }
  37732. }
  37733. }
  37734. collectionLength = collectionKeys.length;
  37735. nextBlockOrder = new Array(collectionLength);
  37736. // locate existing items
  37737. for (index = 0; index < collectionLength; index++) {
  37738. key = (collection === collectionKeys) ? index : collectionKeys[index];
  37739. value = collection[key];
  37740. trackById = trackByIdFn(key, value, index);
  37741. if (lastBlockMap[trackById]) {
  37742. // found previously seen block
  37743. block = lastBlockMap[trackById];
  37744. delete lastBlockMap[trackById];
  37745. nextBlockMap[trackById] = block;
  37746. nextBlockOrder[index] = block;
  37747. } else if (nextBlockMap[trackById]) {
  37748. // if collision detected. restore lastBlockMap and throw an error
  37749. forEach(nextBlockOrder, function(block) {
  37750. if (block && block.scope) lastBlockMap[block.id] = block;
  37751. });
  37752. throw ngRepeatMinErr('dupes',
  37753. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  37754. expression, trackById, value);
  37755. } else {
  37756. // new never before seen block
  37757. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  37758. nextBlockMap[trackById] = true;
  37759. }
  37760. }
  37761. // remove leftover items
  37762. for (var blockKey in lastBlockMap) {
  37763. block = lastBlockMap[blockKey];
  37764. elementsToRemove = getBlockNodes(block.clone);
  37765. $animate.leave(elementsToRemove);
  37766. if (elementsToRemove[0].parentNode) {
  37767. // if the element was not removed yet because of pending animation, mark it as deleted
  37768. // so that we can ignore it later
  37769. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  37770. elementsToRemove[index][NG_REMOVED] = true;
  37771. }
  37772. }
  37773. block.scope.$destroy();
  37774. }
  37775. // we are not using forEach for perf reasons (trying to avoid #call)
  37776. for (index = 0; index < collectionLength; index++) {
  37777. key = (collection === collectionKeys) ? index : collectionKeys[index];
  37778. value = collection[key];
  37779. block = nextBlockOrder[index];
  37780. if (block.scope) {
  37781. // if we have already seen this object, then we need to reuse the
  37782. // associated scope/element
  37783. nextNode = previousNode;
  37784. // skip nodes that are already pending removal via leave animation
  37785. do {
  37786. nextNode = nextNode.nextSibling;
  37787. } while (nextNode && nextNode[NG_REMOVED]);
  37788. if (getBlockStart(block) != nextNode) {
  37789. // existing item which got moved
  37790. $animate.move(getBlockNodes(block.clone), null, previousNode);
  37791. }
  37792. previousNode = getBlockEnd(block);
  37793. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  37794. } else {
  37795. // new item which we don't know about
  37796. $transclude(function ngRepeatTransclude(clone, scope) {
  37797. block.scope = scope;
  37798. // http://jsperf.com/clone-vs-createcomment
  37799. var endNode = ngRepeatEndComment.cloneNode(false);
  37800. clone[clone.length++] = endNode;
  37801. $animate.enter(clone, null, previousNode);
  37802. previousNode = endNode;
  37803. // Note: We only need the first/last node of the cloned nodes.
  37804. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  37805. // by a directive with templateUrl when its template arrives.
  37806. block.clone = clone;
  37807. nextBlockMap[block.id] = block;
  37808. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  37809. });
  37810. }
  37811. }
  37812. lastBlockMap = nextBlockMap;
  37813. });
  37814. };
  37815. }
  37816. };
  37817. }];
  37818. var NG_HIDE_CLASS = 'ng-hide';
  37819. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  37820. /**
  37821. * @ngdoc directive
  37822. * @name ngShow
  37823. * @multiElement
  37824. *
  37825. * @description
  37826. * The `ngShow` directive shows or hides the given HTML element based on the expression
  37827. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  37828. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  37829. * in AngularJS and sets the display style to none (using an !important flag).
  37830. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  37831. *
  37832. * ```html
  37833. * <!-- when $scope.myValue is truthy (element is visible) -->
  37834. * <div ng-show="myValue"></div>
  37835. *
  37836. * <!-- when $scope.myValue is falsy (element is hidden) -->
  37837. * <div ng-show="myValue" class="ng-hide"></div>
  37838. * ```
  37839. *
  37840. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  37841. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  37842. * from the element causing the element not to appear hidden.
  37843. *
  37844. * ## Why is !important used?
  37845. *
  37846. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  37847. * can be easily overridden by heavier selectors. For example, something as simple
  37848. * as changing the display style on a HTML list item would make hidden elements appear visible.
  37849. * This also becomes a bigger issue when dealing with CSS frameworks.
  37850. *
  37851. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  37852. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  37853. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  37854. *
  37855. * ### Overriding `.ng-hide`
  37856. *
  37857. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  37858. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  37859. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  37860. * with extra animation classes that can be added.
  37861. *
  37862. * ```css
  37863. * .ng-hide:not(.ng-hide-animate) {
  37864. * /&#42; this is just another form of hiding an element &#42;/
  37865. * display: block!important;
  37866. * position: absolute;
  37867. * top: -9999px;
  37868. * left: -9999px;
  37869. * }
  37870. * ```
  37871. *
  37872. * By default you don't need to override in CSS anything and the animations will work around the display style.
  37873. *
  37874. * ## A note about animations with `ngShow`
  37875. *
  37876. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  37877. * is true and false. This system works like the animation system present with ngClass except that
  37878. * you must also include the !important flag to override the display property
  37879. * so that you can perform an animation when the element is hidden during the time of the animation.
  37880. *
  37881. * ```css
  37882. * //
  37883. * //a working example can be found at the bottom of this page
  37884. * //
  37885. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  37886. * /&#42; this is required as of 1.3x to properly
  37887. * apply all styling in a show/hide animation &#42;/
  37888. * transition: 0s linear all;
  37889. * }
  37890. *
  37891. * .my-element.ng-hide-add-active,
  37892. * .my-element.ng-hide-remove-active {
  37893. * /&#42; the transition is defined in the active class &#42;/
  37894. * transition: 1s linear all;
  37895. * }
  37896. *
  37897. * .my-element.ng-hide-add { ... }
  37898. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  37899. * .my-element.ng-hide-remove { ... }
  37900. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  37901. * ```
  37902. *
  37903. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  37904. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  37905. *
  37906. * @animations
  37907. * | Animation | Occurs |
  37908. * |----------------------------------|-------------------------------------|
  37909. * | {@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 |
  37910. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngShow` expression evaluates to a truthy value and just before contents are set to visible |
  37911. *
  37912. * @element ANY
  37913. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  37914. * then the element is shown or hidden respectively.
  37915. *
  37916. * @example
  37917. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  37918. <file name="index.html">
  37919. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  37920. <div>
  37921. Show:
  37922. <div class="check-element animate-show" ng-show="checked">
  37923. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  37924. </div>
  37925. </div>
  37926. <div>
  37927. Hide:
  37928. <div class="check-element animate-show" ng-hide="checked">
  37929. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  37930. </div>
  37931. </div>
  37932. </file>
  37933. <file name="glyphicons.css">
  37934. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  37935. </file>
  37936. <file name="animations.css">
  37937. .animate-show {
  37938. line-height: 20px;
  37939. opacity: 1;
  37940. padding: 10px;
  37941. border: 1px solid black;
  37942. background: white;
  37943. }
  37944. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  37945. transition: all linear 0.5s;
  37946. }
  37947. .animate-show.ng-hide {
  37948. line-height: 0;
  37949. opacity: 0;
  37950. padding: 0 10px;
  37951. }
  37952. .check-element {
  37953. padding: 10px;
  37954. border: 1px solid black;
  37955. background: white;
  37956. }
  37957. </file>
  37958. <file name="protractor.js" type="protractor">
  37959. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  37960. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  37961. it('should check ng-show / ng-hide', function() {
  37962. expect(thumbsUp.isDisplayed()).toBeFalsy();
  37963. expect(thumbsDown.isDisplayed()).toBeTruthy();
  37964. element(by.model('checked')).click();
  37965. expect(thumbsUp.isDisplayed()).toBeTruthy();
  37966. expect(thumbsDown.isDisplayed()).toBeFalsy();
  37967. });
  37968. </file>
  37969. </example>
  37970. */
  37971. var ngShowDirective = ['$animate', function($animate) {
  37972. return {
  37973. restrict: 'A',
  37974. multiElement: true,
  37975. link: function(scope, element, attr) {
  37976. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  37977. // we're adding a temporary, animation-specific class for ng-hide since this way
  37978. // we can control when the element is actually displayed on screen without having
  37979. // to have a global/greedy CSS selector that breaks when other animations are run.
  37980. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  37981. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  37982. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  37983. });
  37984. });
  37985. }
  37986. };
  37987. }];
  37988. /**
  37989. * @ngdoc directive
  37990. * @name ngHide
  37991. * @multiElement
  37992. *
  37993. * @description
  37994. * The `ngHide` directive shows or hides the given HTML element based on the expression
  37995. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  37996. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  37997. * in AngularJS and sets the display style to none (using an !important flag).
  37998. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  37999. *
  38000. * ```html
  38001. * <!-- when $scope.myValue is truthy (element is hidden) -->
  38002. * <div ng-hide="myValue" class="ng-hide"></div>
  38003. *
  38004. * <!-- when $scope.myValue is falsy (element is visible) -->
  38005. * <div ng-hide="myValue"></div>
  38006. * ```
  38007. *
  38008. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  38009. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  38010. * from the element causing the element not to appear hidden.
  38011. *
  38012. * ## Why is !important used?
  38013. *
  38014. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  38015. * can be easily overridden by heavier selectors. For example, something as simple
  38016. * as changing the display style on a HTML list item would make hidden elements appear visible.
  38017. * This also becomes a bigger issue when dealing with CSS frameworks.
  38018. *
  38019. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  38020. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  38021. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  38022. *
  38023. * ### Overriding `.ng-hide`
  38024. *
  38025. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  38026. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  38027. * class in CSS:
  38028. *
  38029. * ```css
  38030. * .ng-hide {
  38031. * /&#42; this is just another form of hiding an element &#42;/
  38032. * display: block!important;
  38033. * position: absolute;
  38034. * top: -9999px;
  38035. * left: -9999px;
  38036. * }
  38037. * ```
  38038. *
  38039. * By default you don't need to override in CSS anything and the animations will work around the display style.
  38040. *
  38041. * ## A note about animations with `ngHide`
  38042. *
  38043. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  38044. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  38045. * CSS class is added and removed for you instead of your own CSS class.
  38046. *
  38047. * ```css
  38048. * //
  38049. * //a working example can be found at the bottom of this page
  38050. * //
  38051. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  38052. * transition: 0.5s linear all;
  38053. * }
  38054. *
  38055. * .my-element.ng-hide-add { ... }
  38056. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  38057. * .my-element.ng-hide-remove { ... }
  38058. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  38059. * ```
  38060. *
  38061. * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display
  38062. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  38063. *
  38064. * @animations
  38065. * | Animation | Occurs |
  38066. * |----------------------------------|-------------------------------------|
  38067. * | {@link $animate#addClass addClass} `.ng-hide` | after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden |
  38068. * | {@link $animate#removeClass removeClass} `.ng-hide` | after the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible |
  38069. *
  38070. *
  38071. * @element ANY
  38072. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  38073. * the element is shown or hidden respectively.
  38074. *
  38075. * @example
  38076. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  38077. <file name="index.html">
  38078. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  38079. <div>
  38080. Show:
  38081. <div class="check-element animate-hide" ng-show="checked">
  38082. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  38083. </div>
  38084. </div>
  38085. <div>
  38086. Hide:
  38087. <div class="check-element animate-hide" ng-hide="checked">
  38088. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  38089. </div>
  38090. </div>
  38091. </file>
  38092. <file name="glyphicons.css">
  38093. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  38094. </file>
  38095. <file name="animations.css">
  38096. .animate-hide {
  38097. transition: all linear 0.5s;
  38098. line-height: 20px;
  38099. opacity: 1;
  38100. padding: 10px;
  38101. border: 1px solid black;
  38102. background: white;
  38103. }
  38104. .animate-hide.ng-hide {
  38105. line-height: 0;
  38106. opacity: 0;
  38107. padding: 0 10px;
  38108. }
  38109. .check-element {
  38110. padding: 10px;
  38111. border: 1px solid black;
  38112. background: white;
  38113. }
  38114. </file>
  38115. <file name="protractor.js" type="protractor">
  38116. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  38117. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  38118. it('should check ng-show / ng-hide', function() {
  38119. expect(thumbsUp.isDisplayed()).toBeFalsy();
  38120. expect(thumbsDown.isDisplayed()).toBeTruthy();
  38121. element(by.model('checked')).click();
  38122. expect(thumbsUp.isDisplayed()).toBeTruthy();
  38123. expect(thumbsDown.isDisplayed()).toBeFalsy();
  38124. });
  38125. </file>
  38126. </example>
  38127. */
  38128. var ngHideDirective = ['$animate', function($animate) {
  38129. return {
  38130. restrict: 'A',
  38131. multiElement: true,
  38132. link: function(scope, element, attr) {
  38133. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  38134. // The comment inside of the ngShowDirective explains why we add and
  38135. // remove a temporary class for the show/hide animation
  38136. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  38137. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  38138. });
  38139. });
  38140. }
  38141. };
  38142. }];
  38143. /**
  38144. * @ngdoc directive
  38145. * @name ngStyle
  38146. * @restrict AC
  38147. *
  38148. * @description
  38149. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  38150. *
  38151. * @element ANY
  38152. * @param {expression} ngStyle
  38153. *
  38154. * {@link guide/expression Expression} which evals to an
  38155. * object whose keys are CSS style names and values are corresponding values for those CSS
  38156. * keys.
  38157. *
  38158. * Since some CSS style names are not valid keys for an object, they must be quoted.
  38159. * See the 'background-color' style in the example below.
  38160. *
  38161. * @example
  38162. <example>
  38163. <file name="index.html">
  38164. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  38165. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  38166. <input type="button" value="clear" ng-click="myStyle={}">
  38167. <br/>
  38168. <span ng-style="myStyle">Sample Text</span>
  38169. <pre>myStyle={{myStyle}}</pre>
  38170. </file>
  38171. <file name="style.css">
  38172. span {
  38173. color: black;
  38174. }
  38175. </file>
  38176. <file name="protractor.js" type="protractor">
  38177. var colorSpan = element(by.css('span'));
  38178. it('should check ng-style', function() {
  38179. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  38180. element(by.css('input[value=\'set color\']')).click();
  38181. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  38182. element(by.css('input[value=clear]')).click();
  38183. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  38184. });
  38185. </file>
  38186. </example>
  38187. */
  38188. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  38189. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  38190. if (oldStyles && (newStyles !== oldStyles)) {
  38191. forEach(oldStyles, function(val, style) { element.css(style, '');});
  38192. }
  38193. if (newStyles) element.css(newStyles);
  38194. }, true);
  38195. });
  38196. /**
  38197. * @ngdoc directive
  38198. * @name ngSwitch
  38199. * @restrict EA
  38200. *
  38201. * @description
  38202. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  38203. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  38204. * as specified in the template.
  38205. *
  38206. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  38207. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  38208. * matches the value obtained from the evaluated expression. In other words, you define a container element
  38209. * (where you place the directive), place an expression on the **`on="..."` attribute**
  38210. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  38211. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  38212. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  38213. * attribute is displayed.
  38214. *
  38215. * <div class="alert alert-info">
  38216. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  38217. * as literal string values to match against.
  38218. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  38219. * value of the expression `$scope.someVal`.
  38220. * </div>
  38221. * @animations
  38222. * | Animation | Occurs |
  38223. * |----------------------------------|-------------------------------------|
  38224. * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container |
  38225. * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM |
  38226. *
  38227. * @usage
  38228. *
  38229. * ```
  38230. * <ANY ng-switch="expression">
  38231. * <ANY ng-switch-when="matchValue1">...</ANY>
  38232. * <ANY ng-switch-when="matchValue2">...</ANY>
  38233. * <ANY ng-switch-default>...</ANY>
  38234. * </ANY>
  38235. * ```
  38236. *
  38237. *
  38238. * @scope
  38239. * @priority 1200
  38240. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  38241. * On child elements add:
  38242. *
  38243. * * `ngSwitchWhen`: the case statement to match against. If match then this
  38244. * case will be displayed. If the same match appears multiple times, all the
  38245. * elements will be displayed.
  38246. * * `ngSwitchDefault`: the default case when no other case match. If there
  38247. * are multiple default cases, all of them will be displayed when no other
  38248. * case match.
  38249. *
  38250. *
  38251. * @example
  38252. <example module="switchExample" deps="angular-animate.js" animations="true">
  38253. <file name="index.html">
  38254. <div ng-controller="ExampleController">
  38255. <select ng-model="selection" ng-options="item for item in items">
  38256. </select>
  38257. <code>selection={{selection}}</code>
  38258. <hr/>
  38259. <div class="animate-switch-container"
  38260. ng-switch on="selection">
  38261. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  38262. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  38263. <div class="animate-switch" ng-switch-default>default</div>
  38264. </div>
  38265. </div>
  38266. </file>
  38267. <file name="script.js">
  38268. angular.module('switchExample', ['ngAnimate'])
  38269. .controller('ExampleController', ['$scope', function($scope) {
  38270. $scope.items = ['settings', 'home', 'other'];
  38271. $scope.selection = $scope.items[0];
  38272. }]);
  38273. </file>
  38274. <file name="animations.css">
  38275. .animate-switch-container {
  38276. position:relative;
  38277. background:white;
  38278. border:1px solid black;
  38279. height:40px;
  38280. overflow:hidden;
  38281. }
  38282. .animate-switch {
  38283. padding:10px;
  38284. }
  38285. .animate-switch.ng-animate {
  38286. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  38287. position:absolute;
  38288. top:0;
  38289. left:0;
  38290. right:0;
  38291. bottom:0;
  38292. }
  38293. .animate-switch.ng-leave.ng-leave-active,
  38294. .animate-switch.ng-enter {
  38295. top:-50px;
  38296. }
  38297. .animate-switch.ng-leave,
  38298. .animate-switch.ng-enter.ng-enter-active {
  38299. top:0;
  38300. }
  38301. </file>
  38302. <file name="protractor.js" type="protractor">
  38303. var switchElem = element(by.css('[ng-switch]'));
  38304. var select = element(by.model('selection'));
  38305. it('should start in settings', function() {
  38306. expect(switchElem.getText()).toMatch(/Settings Div/);
  38307. });
  38308. it('should change to home', function() {
  38309. select.all(by.css('option')).get(1).click();
  38310. expect(switchElem.getText()).toMatch(/Home Span/);
  38311. });
  38312. it('should select default', function() {
  38313. select.all(by.css('option')).get(2).click();
  38314. expect(switchElem.getText()).toMatch(/default/);
  38315. });
  38316. </file>
  38317. </example>
  38318. */
  38319. var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) {
  38320. return {
  38321. require: 'ngSwitch',
  38322. // asks for $scope to fool the BC controller module
  38323. controller: ['$scope', function ngSwitchController() {
  38324. this.cases = {};
  38325. }],
  38326. link: function(scope, element, attr, ngSwitchController) {
  38327. var watchExpr = attr.ngSwitch || attr.on,
  38328. selectedTranscludes = [],
  38329. selectedElements = [],
  38330. previousLeaveAnimations = [],
  38331. selectedScopes = [];
  38332. var spliceFactory = function(array, index) {
  38333. return function() { array.splice(index, 1); };
  38334. };
  38335. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  38336. var i, ii;
  38337. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  38338. $animate.cancel(previousLeaveAnimations[i]);
  38339. }
  38340. previousLeaveAnimations.length = 0;
  38341. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  38342. var selected = getBlockNodes(selectedElements[i].clone);
  38343. selectedScopes[i].$destroy();
  38344. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  38345. promise.then(spliceFactory(previousLeaveAnimations, i));
  38346. }
  38347. selectedElements.length = 0;
  38348. selectedScopes.length = 0;
  38349. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  38350. forEach(selectedTranscludes, function(selectedTransclude) {
  38351. selectedTransclude.transclude(function(caseElement, selectedScope) {
  38352. selectedScopes.push(selectedScope);
  38353. var anchor = selectedTransclude.element;
  38354. caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen');
  38355. var block = { clone: caseElement };
  38356. selectedElements.push(block);
  38357. $animate.enter(caseElement, anchor.parent(), anchor);
  38358. });
  38359. });
  38360. }
  38361. });
  38362. }
  38363. };
  38364. }];
  38365. var ngSwitchWhenDirective = ngDirective({
  38366. transclude: 'element',
  38367. priority: 1200,
  38368. require: '^ngSwitch',
  38369. multiElement: true,
  38370. link: function(scope, element, attrs, ctrl, $transclude) {
  38371. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  38372. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  38373. }
  38374. });
  38375. var ngSwitchDefaultDirective = ngDirective({
  38376. transclude: 'element',
  38377. priority: 1200,
  38378. require: '^ngSwitch',
  38379. multiElement: true,
  38380. link: function(scope, element, attr, ctrl, $transclude) {
  38381. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  38382. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  38383. }
  38384. });
  38385. /**
  38386. * @ngdoc directive
  38387. * @name ngTransclude
  38388. * @restrict EAC
  38389. *
  38390. * @description
  38391. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  38392. *
  38393. * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name
  38394. * as the value of the `ng-transclude` or `ng-transclude-slot` attribute.
  38395. *
  38396. * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing
  38397. * content of this element will be removed before the transcluded content is inserted.
  38398. * If the transcluded content is empty, the existing content is left intact. This lets you provide fallback content in the case
  38399. * that no transcluded content is provided.
  38400. *
  38401. * @element ANY
  38402. *
  38403. * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty
  38404. * or its value is the same as the name of the attribute then the default slot is used.
  38405. *
  38406. * @example
  38407. * ### Basic transclusion
  38408. * This example demonstrates basic transclusion of content into a component directive.
  38409. * <example name="simpleTranscludeExample" module="transcludeExample">
  38410. * <file name="index.html">
  38411. * <script>
  38412. * angular.module('transcludeExample', [])
  38413. * .directive('pane', function(){
  38414. * return {
  38415. * restrict: 'E',
  38416. * transclude: true,
  38417. * scope: { title:'@' },
  38418. * template: '<div style="border: 1px solid black;">' +
  38419. * '<div style="background-color: gray">{{title}}</div>' +
  38420. * '<ng-transclude></ng-transclude>' +
  38421. * '</div>'
  38422. * };
  38423. * })
  38424. * .controller('ExampleController', ['$scope', function($scope) {
  38425. * $scope.title = 'Lorem Ipsum';
  38426. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  38427. * }]);
  38428. * </script>
  38429. * <div ng-controller="ExampleController">
  38430. * <input ng-model="title" aria-label="title"> <br/>
  38431. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  38432. * <pane title="{{title}}">{{text}}</pane>
  38433. * </div>
  38434. * </file>
  38435. * <file name="protractor.js" type="protractor">
  38436. * it('should have transcluded', function() {
  38437. * var titleElement = element(by.model('title'));
  38438. * titleElement.clear();
  38439. * titleElement.sendKeys('TITLE');
  38440. * var textElement = element(by.model('text'));
  38441. * textElement.clear();
  38442. * textElement.sendKeys('TEXT');
  38443. * expect(element(by.binding('title')).getText()).toEqual('TITLE');
  38444. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  38445. * });
  38446. * </file>
  38447. * </example>
  38448. *
  38449. * @example
  38450. * ### Transclude fallback content
  38451. * This example shows how to use `NgTransclude` with fallback content, that
  38452. * is displayed if no transcluded content is provided.
  38453. *
  38454. * <example module="transcludeFallbackContentExample">
  38455. * <file name="index.html">
  38456. * <script>
  38457. * angular.module('transcludeFallbackContentExample', [])
  38458. * .directive('myButton', function(){
  38459. * return {
  38460. * restrict: 'E',
  38461. * transclude: true,
  38462. * scope: true,
  38463. * template: '<button style="cursor: pointer;">' +
  38464. * '<ng-transclude>' +
  38465. * '<b style="color: red;">Button1</b>' +
  38466. * '</ng-transclude>' +
  38467. * '</button>'
  38468. * };
  38469. * });
  38470. * </script>
  38471. * <!-- fallback button content -->
  38472. * <my-button id="fallback"></my-button>
  38473. * <!-- modified button content -->
  38474. * <my-button id="modified">
  38475. * <i style="color: green;">Button2</i>
  38476. * </my-button>
  38477. * </file>
  38478. * <file name="protractor.js" type="protractor">
  38479. * it('should have different transclude element content', function() {
  38480. * expect(element(by.id('fallback')).getText()).toBe('Button1');
  38481. * expect(element(by.id('modified')).getText()).toBe('Button2');
  38482. * });
  38483. * </file>
  38484. * </example>
  38485. *
  38486. * @example
  38487. * ### Multi-slot transclusion
  38488. * This example demonstrates using multi-slot transclusion in a component directive.
  38489. * <example name="multiSlotTranscludeExample" module="multiSlotTranscludeExample">
  38490. * <file name="index.html">
  38491. * <style>
  38492. * .title, .footer {
  38493. * background-color: gray
  38494. * }
  38495. * </style>
  38496. * <div ng-controller="ExampleController">
  38497. * <input ng-model="title" aria-label="title"> <br/>
  38498. * <textarea ng-model="text" aria-label="text"></textarea> <br/>
  38499. * <pane>
  38500. * <pane-title><a ng-href="{{link}}">{{title}}</a></pane-title>
  38501. * <pane-body><p>{{text}}</p></pane-body>
  38502. * </pane>
  38503. * </div>
  38504. * </file>
  38505. * <file name="app.js">
  38506. * angular.module('multiSlotTranscludeExample', [])
  38507. * .directive('pane', function(){
  38508. * return {
  38509. * restrict: 'E',
  38510. * transclude: {
  38511. * 'title': '?paneTitle',
  38512. * 'body': 'paneBody',
  38513. * 'footer': '?paneFooter'
  38514. * },
  38515. * template: '<div style="border: 1px solid black;">' +
  38516. * '<div class="title" ng-transclude="title">Fallback Title</div>' +
  38517. * '<div ng-transclude="body"></div>' +
  38518. * '<div class="footer" ng-transclude="footer">Fallback Footer</div>' +
  38519. * '</div>'
  38520. * };
  38521. * })
  38522. * .controller('ExampleController', ['$scope', function($scope) {
  38523. * $scope.title = 'Lorem Ipsum';
  38524. * $scope.link = "https://google.com";
  38525. * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  38526. * }]);
  38527. * </file>
  38528. * <file name="protractor.js" type="protractor">
  38529. * it('should have transcluded the title and the body', function() {
  38530. * var titleElement = element(by.model('title'));
  38531. * titleElement.clear();
  38532. * titleElement.sendKeys('TITLE');
  38533. * var textElement = element(by.model('text'));
  38534. * textElement.clear();
  38535. * textElement.sendKeys('TEXT');
  38536. * expect(element(by.css('.title')).getText()).toEqual('TITLE');
  38537. * expect(element(by.binding('text')).getText()).toEqual('TEXT');
  38538. * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer');
  38539. * });
  38540. * </file>
  38541. * </example>
  38542. */
  38543. var ngTranscludeMinErr = minErr('ngTransclude');
  38544. var ngTranscludeDirective = ngDirective({
  38545. restrict: 'EAC',
  38546. link: function($scope, $element, $attrs, controller, $transclude) {
  38547. if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) {
  38548. // If the attribute is of the form: `ng-transclude="ng-transclude"`
  38549. // then treat it like the default
  38550. $attrs.ngTransclude = '';
  38551. }
  38552. function ngTranscludeCloneAttachFn(clone) {
  38553. if (clone.length) {
  38554. $element.empty();
  38555. $element.append(clone);
  38556. }
  38557. }
  38558. if (!$transclude) {
  38559. throw ngTranscludeMinErr('orphan',
  38560. 'Illegal use of ngTransclude directive in the template! ' +
  38561. 'No parent directive that requires a transclusion found. ' +
  38562. 'Element: {0}',
  38563. startingTag($element));
  38564. }
  38565. // If there is no slot name defined or the slot name is not optional
  38566. // then transclude the slot
  38567. var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot;
  38568. $transclude(ngTranscludeCloneAttachFn, null, slotName);
  38569. }
  38570. });
  38571. /**
  38572. * @ngdoc directive
  38573. * @name script
  38574. * @restrict E
  38575. *
  38576. * @description
  38577. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  38578. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  38579. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  38580. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  38581. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  38582. *
  38583. * @param {string} type Must be set to `'text/ng-template'`.
  38584. * @param {string} id Cache name of the template.
  38585. *
  38586. * @example
  38587. <example>
  38588. <file name="index.html">
  38589. <script type="text/ng-template" id="/tpl.html">
  38590. Content of the template.
  38591. </script>
  38592. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  38593. <div id="tpl-content" ng-include src="currentTpl"></div>
  38594. </file>
  38595. <file name="protractor.js" type="protractor">
  38596. it('should load template defined inside script tag', function() {
  38597. element(by.css('#tpl-link')).click();
  38598. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  38599. });
  38600. </file>
  38601. </example>
  38602. */
  38603. var scriptDirective = ['$templateCache', function($templateCache) {
  38604. return {
  38605. restrict: 'E',
  38606. terminal: true,
  38607. compile: function(element, attr) {
  38608. if (attr.type == 'text/ng-template') {
  38609. var templateUrl = attr.id,
  38610. text = element[0].text;
  38611. $templateCache.put(templateUrl, text);
  38612. }
  38613. }
  38614. };
  38615. }];
  38616. var noopNgModelController = { $setViewValue: noop, $render: noop };
  38617. function chromeHack(optionElement) {
  38618. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  38619. // Adding an <option selected="selected"> element to a <select required="required"> should
  38620. // automatically select the new element
  38621. if (optionElement[0].hasAttribute('selected')) {
  38622. optionElement[0].selected = true;
  38623. }
  38624. }
  38625. /**
  38626. * @ngdoc type
  38627. * @name select.SelectController
  38628. * @description
  38629. * The controller for the `<select>` directive. This provides support for reading
  38630. * and writing the selected value(s) of the control and also coordinates dynamically
  38631. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  38632. */
  38633. var SelectController =
  38634. ['$element', '$scope', function($element, $scope) {
  38635. var self = this,
  38636. optionsMap = new HashMap();
  38637. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  38638. self.ngModelCtrl = noopNgModelController;
  38639. // The "unknown" option is one that is prepended to the list if the viewValue
  38640. // does not match any of the options. When it is rendered the value of the unknown
  38641. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  38642. //
  38643. // We can't just jqLite('<option>') since jqLite is not smart enough
  38644. // to create it in <select> and IE barfs otherwise.
  38645. self.unknownOption = jqLite(document.createElement('option'));
  38646. self.renderUnknownOption = function(val) {
  38647. var unknownVal = '? ' + hashKey(val) + ' ?';
  38648. self.unknownOption.val(unknownVal);
  38649. $element.prepend(self.unknownOption);
  38650. $element.val(unknownVal);
  38651. };
  38652. $scope.$on('$destroy', function() {
  38653. // disable unknown option so that we don't do work when the whole select is being destroyed
  38654. self.renderUnknownOption = noop;
  38655. });
  38656. self.removeUnknownOption = function() {
  38657. if (self.unknownOption.parent()) self.unknownOption.remove();
  38658. };
  38659. // Read the value of the select control, the implementation of this changes depending
  38660. // upon whether the select can have multiple values and whether ngOptions is at work.
  38661. self.readValue = function readSingleValue() {
  38662. self.removeUnknownOption();
  38663. return $element.val();
  38664. };
  38665. // Write the value to the select control, the implementation of this changes depending
  38666. // upon whether the select can have multiple values and whether ngOptions is at work.
  38667. self.writeValue = function writeSingleValue(value) {
  38668. if (self.hasOption(value)) {
  38669. self.removeUnknownOption();
  38670. $element.val(value);
  38671. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  38672. } else {
  38673. if (value == null && self.emptyOption) {
  38674. self.removeUnknownOption();
  38675. $element.val('');
  38676. } else {
  38677. self.renderUnknownOption(value);
  38678. }
  38679. }
  38680. };
  38681. // Tell the select control that an option, with the given value, has been added
  38682. self.addOption = function(value, element) {
  38683. // Skip comment nodes, as they only pollute the `optionsMap`
  38684. if (element[0].nodeType === NODE_TYPE_COMMENT) return;
  38685. assertNotHasOwnProperty(value, '"option value"');
  38686. if (value === '') {
  38687. self.emptyOption = element;
  38688. }
  38689. var count = optionsMap.get(value) || 0;
  38690. optionsMap.put(value, count + 1);
  38691. self.ngModelCtrl.$render();
  38692. chromeHack(element);
  38693. };
  38694. // Tell the select control that an option, with the given value, has been removed
  38695. self.removeOption = function(value) {
  38696. var count = optionsMap.get(value);
  38697. if (count) {
  38698. if (count === 1) {
  38699. optionsMap.remove(value);
  38700. if (value === '') {
  38701. self.emptyOption = undefined;
  38702. }
  38703. } else {
  38704. optionsMap.put(value, count - 1);
  38705. }
  38706. }
  38707. };
  38708. // Check whether the select control has an option matching the given value
  38709. self.hasOption = function(value) {
  38710. return !!optionsMap.get(value);
  38711. };
  38712. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  38713. if (interpolateValueFn) {
  38714. // The value attribute is interpolated
  38715. var oldVal;
  38716. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  38717. if (isDefined(oldVal)) {
  38718. self.removeOption(oldVal);
  38719. }
  38720. oldVal = newVal;
  38721. self.addOption(newVal, optionElement);
  38722. });
  38723. } else if (interpolateTextFn) {
  38724. // The text content is interpolated
  38725. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  38726. optionAttrs.$set('value', newVal);
  38727. if (oldVal !== newVal) {
  38728. self.removeOption(oldVal);
  38729. }
  38730. self.addOption(newVal, optionElement);
  38731. });
  38732. } else {
  38733. // The value attribute is static
  38734. self.addOption(optionAttrs.value, optionElement);
  38735. }
  38736. optionElement.on('$destroy', function() {
  38737. self.removeOption(optionAttrs.value);
  38738. self.ngModelCtrl.$render();
  38739. });
  38740. };
  38741. }];
  38742. /**
  38743. * @ngdoc directive
  38744. * @name select
  38745. * @restrict E
  38746. *
  38747. * @description
  38748. * HTML `SELECT` element with angular data-binding.
  38749. *
  38750. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  38751. * between the scope and the `<select>` control (including setting default values).
  38752. * It also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  38753. * {@link ngOptions `ngOptions`} directives.
  38754. *
  38755. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  38756. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  38757. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  38758. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  38759. *
  38760. * <div class="alert alert-warning">
  38761. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  38762. * When the model needs to be bound to a non-string value, you must either explicitly convert it
  38763. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  38764. * This is because an option element can only be bound to string values at present.
  38765. * </div>
  38766. *
  38767. * If the viewValue of `ngModel` does not match any of the options, then the control
  38768. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  38769. *
  38770. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  38771. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  38772. * option. See example below for demonstration.
  38773. *
  38774. * <div class="alert alert-info">
  38775. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  38776. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  38777. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  38778. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  38779. * a new scope for each repeated instance.
  38780. * </div>
  38781. *
  38782. *
  38783. * @param {string} ngModel Assignable angular expression to data-bind to.
  38784. * @param {string=} name Property name of the form under which the control is published.
  38785. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  38786. * bound to the model as an array.
  38787. * @param {string=} required Sets `required` validation error key if the value is not entered.
  38788. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  38789. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  38790. * when you want to data-bind to the required attribute.
  38791. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  38792. * interaction with the select element.
  38793. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  38794. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  38795. *
  38796. * @example
  38797. * ### Simple `select` elements with static options
  38798. *
  38799. * <example name="static-select" module="staticSelect">
  38800. * <file name="index.html">
  38801. * <div ng-controller="ExampleController">
  38802. * <form name="myForm">
  38803. * <label for="singleSelect"> Single select: </label><br>
  38804. * <select name="singleSelect" ng-model="data.singleSelect">
  38805. * <option value="option-1">Option 1</option>
  38806. * <option value="option-2">Option 2</option>
  38807. * </select><br>
  38808. *
  38809. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  38810. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  38811. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  38812. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  38813. * <option value="option-2">Option 2</option>
  38814. * </select><br>
  38815. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  38816. * <tt>singleSelect = {{data.singleSelect}}</tt>
  38817. *
  38818. * <hr>
  38819. * <label for="multipleSelect"> Multiple select: </label><br>
  38820. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  38821. * <option value="option-1">Option 1</option>
  38822. * <option value="option-2">Option 2</option>
  38823. * <option value="option-3">Option 3</option>
  38824. * </select><br>
  38825. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  38826. * </form>
  38827. * </div>
  38828. * </file>
  38829. * <file name="app.js">
  38830. * angular.module('staticSelect', [])
  38831. * .controller('ExampleController', ['$scope', function($scope) {
  38832. * $scope.data = {
  38833. * singleSelect: null,
  38834. * multipleSelect: [],
  38835. * option1: 'option-1',
  38836. * };
  38837. *
  38838. * $scope.forceUnknownOption = function() {
  38839. * $scope.data.singleSelect = 'nonsense';
  38840. * };
  38841. * }]);
  38842. * </file>
  38843. *</example>
  38844. *
  38845. * ### Using `ngRepeat` to generate `select` options
  38846. * <example name="ngrepeat-select" module="ngrepeatSelect">
  38847. * <file name="index.html">
  38848. * <div ng-controller="ExampleController">
  38849. * <form name="myForm">
  38850. * <label for="repeatSelect"> Repeat select: </label>
  38851. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  38852. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  38853. * </select>
  38854. * </form>
  38855. * <hr>
  38856. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  38857. * </div>
  38858. * </file>
  38859. * <file name="app.js">
  38860. * angular.module('ngrepeatSelect', [])
  38861. * .controller('ExampleController', ['$scope', function($scope) {
  38862. * $scope.data = {
  38863. * repeatSelect: null,
  38864. * availableOptions: [
  38865. * {id: '1', name: 'Option A'},
  38866. * {id: '2', name: 'Option B'},
  38867. * {id: '3', name: 'Option C'}
  38868. * ],
  38869. * };
  38870. * }]);
  38871. * </file>
  38872. *</example>
  38873. *
  38874. *
  38875. * ### Using `select` with `ngOptions` and setting a default value
  38876. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  38877. *
  38878. * <example name="select-with-default-values" module="defaultValueSelect">
  38879. * <file name="index.html">
  38880. * <div ng-controller="ExampleController">
  38881. * <form name="myForm">
  38882. * <label for="mySelect">Make a choice:</label>
  38883. * <select name="mySelect" id="mySelect"
  38884. * ng-options="option.name for option in data.availableOptions track by option.id"
  38885. * ng-model="data.selectedOption"></select>
  38886. * </form>
  38887. * <hr>
  38888. * <tt>option = {{data.selectedOption}}</tt><br/>
  38889. * </div>
  38890. * </file>
  38891. * <file name="app.js">
  38892. * angular.module('defaultValueSelect', [])
  38893. * .controller('ExampleController', ['$scope', function($scope) {
  38894. * $scope.data = {
  38895. * availableOptions: [
  38896. * {id: '1', name: 'Option A'},
  38897. * {id: '2', name: 'Option B'},
  38898. * {id: '3', name: 'Option C'}
  38899. * ],
  38900. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  38901. * };
  38902. * }]);
  38903. * </file>
  38904. *</example>
  38905. *
  38906. *
  38907. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  38908. *
  38909. * <example name="select-with-non-string-options" module="nonStringSelect">
  38910. * <file name="index.html">
  38911. * <select ng-model="model.id" convert-to-number>
  38912. * <option value="0">Zero</option>
  38913. * <option value="1">One</option>
  38914. * <option value="2">Two</option>
  38915. * </select>
  38916. * {{ model }}
  38917. * </file>
  38918. * <file name="app.js">
  38919. * angular.module('nonStringSelect', [])
  38920. * .run(function($rootScope) {
  38921. * $rootScope.model = { id: 2 };
  38922. * })
  38923. * .directive('convertToNumber', function() {
  38924. * return {
  38925. * require: 'ngModel',
  38926. * link: function(scope, element, attrs, ngModel) {
  38927. * ngModel.$parsers.push(function(val) {
  38928. * return parseInt(val, 10);
  38929. * });
  38930. * ngModel.$formatters.push(function(val) {
  38931. * return '' + val;
  38932. * });
  38933. * }
  38934. * };
  38935. * });
  38936. * </file>
  38937. * <file name="protractor.js" type="protractor">
  38938. * it('should initialize to model', function() {
  38939. * var select = element(by.css('select'));
  38940. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  38941. * });
  38942. * </file>
  38943. * </example>
  38944. *
  38945. */
  38946. var selectDirective = function() {
  38947. return {
  38948. restrict: 'E',
  38949. require: ['select', '?ngModel'],
  38950. controller: SelectController,
  38951. priority: 1,
  38952. link: {
  38953. pre: selectPreLink,
  38954. post: selectPostLink
  38955. }
  38956. };
  38957. function selectPreLink(scope, element, attr, ctrls) {
  38958. // if ngModel is not defined, we don't need to do anything
  38959. var ngModelCtrl = ctrls[1];
  38960. if (!ngModelCtrl) return;
  38961. var selectCtrl = ctrls[0];
  38962. selectCtrl.ngModelCtrl = ngModelCtrl;
  38963. // When the selected item(s) changes we delegate getting the value of the select control
  38964. // to the `readValue` method, which can be changed if the select can have multiple
  38965. // selected values or if the options are being generated by `ngOptions`
  38966. element.on('change', function() {
  38967. scope.$apply(function() {
  38968. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  38969. });
  38970. });
  38971. // If the select allows multiple values then we need to modify how we read and write
  38972. // values from and to the control; also what it means for the value to be empty and
  38973. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  38974. // doesn't trigger rendering if only an item in the array changes.
  38975. if (attr.multiple) {
  38976. // Read value now needs to check each option to see if it is selected
  38977. selectCtrl.readValue = function readMultipleValue() {
  38978. var array = [];
  38979. forEach(element.find('option'), function(option) {
  38980. if (option.selected) {
  38981. array.push(option.value);
  38982. }
  38983. });
  38984. return array;
  38985. };
  38986. // Write value now needs to set the selected property of each matching option
  38987. selectCtrl.writeValue = function writeMultipleValue(value) {
  38988. var items = new HashMap(value);
  38989. forEach(element.find('option'), function(option) {
  38990. option.selected = isDefined(items.get(option.value));
  38991. });
  38992. };
  38993. // we have to do it on each watch since ngModel watches reference, but
  38994. // we need to work of an array, so we need to see if anything was inserted/removed
  38995. var lastView, lastViewRef = NaN;
  38996. scope.$watch(function selectMultipleWatch() {
  38997. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  38998. lastView = shallowCopy(ngModelCtrl.$viewValue);
  38999. ngModelCtrl.$render();
  39000. }
  39001. lastViewRef = ngModelCtrl.$viewValue;
  39002. });
  39003. // If we are a multiple select then value is now a collection
  39004. // so the meaning of $isEmpty changes
  39005. ngModelCtrl.$isEmpty = function(value) {
  39006. return !value || value.length === 0;
  39007. };
  39008. }
  39009. }
  39010. function selectPostLink(scope, element, attrs, ctrls) {
  39011. // if ngModel is not defined, we don't need to do anything
  39012. var ngModelCtrl = ctrls[1];
  39013. if (!ngModelCtrl) return;
  39014. var selectCtrl = ctrls[0];
  39015. // We delegate rendering to the `writeValue` method, which can be changed
  39016. // if the select can have multiple selected values or if the options are being
  39017. // generated by `ngOptions`.
  39018. // This must be done in the postLink fn to prevent $render to be called before
  39019. // all nodes have been linked correctly.
  39020. ngModelCtrl.$render = function() {
  39021. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  39022. };
  39023. }
  39024. };
  39025. // The option directive is purely designed to communicate the existence (or lack of)
  39026. // of dynamically created (and destroyed) option elements to their containing select
  39027. // directive via its controller.
  39028. var optionDirective = ['$interpolate', function($interpolate) {
  39029. return {
  39030. restrict: 'E',
  39031. priority: 100,
  39032. compile: function(element, attr) {
  39033. if (isDefined(attr.value)) {
  39034. // If the value attribute is defined, check if it contains an interpolation
  39035. var interpolateValueFn = $interpolate(attr.value, true);
  39036. } else {
  39037. // If the value attribute is not defined then we fall back to the
  39038. // text content of the option element, which may be interpolated
  39039. var interpolateTextFn = $interpolate(element.text(), true);
  39040. if (!interpolateTextFn) {
  39041. attr.$set('value', element.text());
  39042. }
  39043. }
  39044. return function(scope, element, attr) {
  39045. // This is an optimization over using ^^ since we don't want to have to search
  39046. // all the way to the root of the DOM for every single option element
  39047. var selectCtrlName = '$selectController',
  39048. parent = element.parent(),
  39049. selectCtrl = parent.data(selectCtrlName) ||
  39050. parent.parent().data(selectCtrlName); // in case we are in optgroup
  39051. if (selectCtrl) {
  39052. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  39053. }
  39054. };
  39055. }
  39056. };
  39057. }];
  39058. var styleDirective = valueFn({
  39059. restrict: 'E',
  39060. terminal: false
  39061. });
  39062. /**
  39063. * @ngdoc directive
  39064. * @name ngRequired
  39065. *
  39066. * @description
  39067. *
  39068. * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39069. * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be
  39070. * applied to custom controls.
  39071. *
  39072. * The directive sets the `required` attribute on the element if the Angular expression inside
  39073. * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we
  39074. * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide}
  39075. * for more info.
  39076. *
  39077. * The validator will set the `required` error key to true if the `required` attribute is set and
  39078. * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the
  39079. * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the
  39080. * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing
  39081. * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based.
  39082. *
  39083. * @example
  39084. * <example name="ngRequiredDirective" module="ngRequiredExample">
  39085. * <file name="index.html">
  39086. * <script>
  39087. * angular.module('ngRequiredExample', [])
  39088. * .controller('ExampleController', ['$scope', function($scope) {
  39089. * $scope.required = true;
  39090. * }]);
  39091. * </script>
  39092. * <div ng-controller="ExampleController">
  39093. * <form name="form">
  39094. * <label for="required">Toggle required: </label>
  39095. * <input type="checkbox" ng-model="required" id="required" />
  39096. * <br>
  39097. * <label for="input">This input must be filled if `required` is true: </label>
  39098. * <input type="text" ng-model="model" id="input" name="input" ng-required="required" /><br>
  39099. * <hr>
  39100. * required error set? = <code>{{form.input.$error.required}}</code><br>
  39101. * model = <code>{{model}}</code>
  39102. * </form>
  39103. * </div>
  39104. * </file>
  39105. * <file name="protractor.js" type="protractor">
  39106. var required = element(by.binding('form.input.$error.required'));
  39107. var model = element(by.binding('model'));
  39108. var input = element(by.id('input'));
  39109. it('should set the required error', function() {
  39110. expect(required.getText()).toContain('true');
  39111. input.sendKeys('123');
  39112. expect(required.getText()).not.toContain('true');
  39113. expect(model.getText()).toContain('123');
  39114. });
  39115. * </file>
  39116. * </example>
  39117. */
  39118. var requiredDirective = function() {
  39119. return {
  39120. restrict: 'A',
  39121. require: '?ngModel',
  39122. link: function(scope, elm, attr, ctrl) {
  39123. if (!ctrl) return;
  39124. attr.required = true; // force truthy in case we are on non input element
  39125. ctrl.$validators.required = function(modelValue, viewValue) {
  39126. return !attr.required || !ctrl.$isEmpty(viewValue);
  39127. };
  39128. attr.$observe('required', function() {
  39129. ctrl.$validate();
  39130. });
  39131. }
  39132. };
  39133. };
  39134. /**
  39135. * @ngdoc directive
  39136. * @name ngPattern
  39137. *
  39138. * @description
  39139. *
  39140. * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39141. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39142. *
  39143. * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39144. * does not match a RegExp which is obtained by evaluating the Angular expression given in the
  39145. * `ngPattern` attribute value:
  39146. * * If the expression evaluates to a RegExp object, then this is used directly.
  39147. * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
  39148. * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
  39149. *
  39150. * <div class="alert alert-info">
  39151. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  39152. * start at the index of the last search's match, thus not taking the whole input value into
  39153. * account.
  39154. * </div>
  39155. *
  39156. * <div class="alert alert-info">
  39157. * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
  39158. * differences:
  39159. * <ol>
  39160. * <li>
  39161. * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is
  39162. * not available.
  39163. * </li>
  39164. * <li>
  39165. * The `ngPattern` attribute must be an expression, while the `pattern` value must be
  39166. * interpolated.
  39167. * </li>
  39168. * </ol>
  39169. * </div>
  39170. *
  39171. * @example
  39172. * <example name="ngPatternDirective" module="ngPatternExample">
  39173. * <file name="index.html">
  39174. * <script>
  39175. * angular.module('ngPatternExample', [])
  39176. * .controller('ExampleController', ['$scope', function($scope) {
  39177. * $scope.regex = '\\d+';
  39178. * }]);
  39179. * </script>
  39180. * <div ng-controller="ExampleController">
  39181. * <form name="form">
  39182. * <label for="regex">Set a pattern (regex string): </label>
  39183. * <input type="text" ng-model="regex" id="regex" />
  39184. * <br>
  39185. * <label for="input">This input is restricted by the current pattern: </label>
  39186. * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
  39187. * <hr>
  39188. * input valid? = <code>{{form.input.$valid}}</code><br>
  39189. * model = <code>{{model}}</code>
  39190. * </form>
  39191. * </div>
  39192. * </file>
  39193. * <file name="protractor.js" type="protractor">
  39194. var model = element(by.binding('model'));
  39195. var input = element(by.id('input'));
  39196. it('should validate the input with the default pattern', function() {
  39197. input.sendKeys('aaa');
  39198. expect(model.getText()).not.toContain('aaa');
  39199. input.clear().then(function() {
  39200. input.sendKeys('123');
  39201. expect(model.getText()).toContain('123');
  39202. });
  39203. });
  39204. * </file>
  39205. * </example>
  39206. */
  39207. var patternDirective = function() {
  39208. return {
  39209. restrict: 'A',
  39210. require: '?ngModel',
  39211. link: function(scope, elm, attr, ctrl) {
  39212. if (!ctrl) return;
  39213. var regexp, patternExp = attr.ngPattern || attr.pattern;
  39214. attr.$observe('pattern', function(regex) {
  39215. if (isString(regex) && regex.length > 0) {
  39216. regex = new RegExp('^' + regex + '$');
  39217. }
  39218. if (regex && !regex.test) {
  39219. throw minErr('ngPattern')('noregexp',
  39220. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  39221. regex, startingTag(elm));
  39222. }
  39223. regexp = regex || undefined;
  39224. ctrl.$validate();
  39225. });
  39226. ctrl.$validators.pattern = function(modelValue, viewValue) {
  39227. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  39228. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  39229. };
  39230. }
  39231. };
  39232. };
  39233. /**
  39234. * @ngdoc directive
  39235. * @name ngMaxlength
  39236. *
  39237. * @description
  39238. *
  39239. * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39240. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39241. *
  39242. * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39243. * is longer than the integer obtained by evaluating the Angular expression given in the
  39244. * `ngMaxlength` attribute value.
  39245. *
  39246. * <div class="alert alert-info">
  39247. * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
  39248. * differences:
  39249. * <ol>
  39250. * <li>
  39251. * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint
  39252. * validation is not available.
  39253. * </li>
  39254. * <li>
  39255. * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be
  39256. * interpolated.
  39257. * </li>
  39258. * </ol>
  39259. * </div>
  39260. *
  39261. * @example
  39262. * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
  39263. * <file name="index.html">
  39264. * <script>
  39265. * angular.module('ngMaxlengthExample', [])
  39266. * .controller('ExampleController', ['$scope', function($scope) {
  39267. * $scope.maxlength = 5;
  39268. * }]);
  39269. * </script>
  39270. * <div ng-controller="ExampleController">
  39271. * <form name="form">
  39272. * <label for="maxlength">Set a maxlength: </label>
  39273. * <input type="number" ng-model="maxlength" id="maxlength" />
  39274. * <br>
  39275. * <label for="input">This input is restricted by the current maxlength: </label>
  39276. * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
  39277. * <hr>
  39278. * input valid? = <code>{{form.input.$valid}}</code><br>
  39279. * model = <code>{{model}}</code>
  39280. * </form>
  39281. * </div>
  39282. * </file>
  39283. * <file name="protractor.js" type="protractor">
  39284. var model = element(by.binding('model'));
  39285. var input = element(by.id('input'));
  39286. it('should validate the input with the default maxlength', function() {
  39287. input.sendKeys('abcdef');
  39288. expect(model.getText()).not.toContain('abcdef');
  39289. input.clear().then(function() {
  39290. input.sendKeys('abcde');
  39291. expect(model.getText()).toContain('abcde');
  39292. });
  39293. });
  39294. * </file>
  39295. * </example>
  39296. */
  39297. var maxlengthDirective = function() {
  39298. return {
  39299. restrict: 'A',
  39300. require: '?ngModel',
  39301. link: function(scope, elm, attr, ctrl) {
  39302. if (!ctrl) return;
  39303. var maxlength = -1;
  39304. attr.$observe('maxlength', function(value) {
  39305. var intVal = toInt(value);
  39306. maxlength = isNaN(intVal) ? -1 : intVal;
  39307. ctrl.$validate();
  39308. });
  39309. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  39310. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  39311. };
  39312. }
  39313. };
  39314. };
  39315. /**
  39316. * @ngdoc directive
  39317. * @name ngMinlength
  39318. *
  39319. * @description
  39320. *
  39321. * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
  39322. * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls.
  39323. *
  39324. * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
  39325. * is shorter than the integer obtained by evaluating the Angular expression given in the
  39326. * `ngMinlength` attribute value.
  39327. *
  39328. * <div class="alert alert-info">
  39329. * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
  39330. * differences:
  39331. * <ol>
  39332. * <li>
  39333. * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint
  39334. * validation is not available.
  39335. * </li>
  39336. * <li>
  39337. * The `ngMinlength` value must be an expression, while the `minlength` value must be
  39338. * interpolated.
  39339. * </li>
  39340. * </ol>
  39341. * </div>
  39342. *
  39343. * @example
  39344. * <example name="ngMinlengthDirective" module="ngMinlengthExample">
  39345. * <file name="index.html">
  39346. * <script>
  39347. * angular.module('ngMinlengthExample', [])
  39348. * .controller('ExampleController', ['$scope', function($scope) {
  39349. * $scope.minlength = 3;
  39350. * }]);
  39351. * </script>
  39352. * <div ng-controller="ExampleController">
  39353. * <form name="form">
  39354. * <label for="minlength">Set a minlength: </label>
  39355. * <input type="number" ng-model="minlength" id="minlength" />
  39356. * <br>
  39357. * <label for="input">This input is restricted by the current minlength: </label>
  39358. * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
  39359. * <hr>
  39360. * input valid? = <code>{{form.input.$valid}}</code><br>
  39361. * model = <code>{{model}}</code>
  39362. * </form>
  39363. * </div>
  39364. * </file>
  39365. * <file name="protractor.js" type="protractor">
  39366. var model = element(by.binding('model'));
  39367. var input = element(by.id('input'));
  39368. it('should validate the input with the default minlength', function() {
  39369. input.sendKeys('ab');
  39370. expect(model.getText()).not.toContain('ab');
  39371. input.sendKeys('abc');
  39372. expect(model.getText()).toContain('abc');
  39373. });
  39374. * </file>
  39375. * </example>
  39376. */
  39377. var minlengthDirective = function() {
  39378. return {
  39379. restrict: 'A',
  39380. require: '?ngModel',
  39381. link: function(scope, elm, attr, ctrl) {
  39382. if (!ctrl) return;
  39383. var minlength = 0;
  39384. attr.$observe('minlength', function(value) {
  39385. minlength = toInt(value) || 0;
  39386. ctrl.$validate();
  39387. });
  39388. ctrl.$validators.minlength = function(modelValue, viewValue) {
  39389. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  39390. };
  39391. }
  39392. };
  39393. };
  39394. if (window.angular.bootstrap) {
  39395. //AngularJS is already loaded, so we can return here...
  39396. if (window.console) {
  39397. console.log('WARNING: Tried to load angular more than once.');
  39398. }
  39399. return;
  39400. }
  39401. //try to bind to jquery now so that one can write jqLite(document).ready()
  39402. //but we will rebind on bootstrap again.
  39403. bindJQuery();
  39404. publishExternalAPI(angular);
  39405. angular.module("ngLocale", [], ["$provide", function($provide) {
  39406. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  39407. function getDecimals(n) {
  39408. n = n + '';
  39409. var i = n.indexOf('.');
  39410. return (i == -1) ? 0 : n.length - i - 1;
  39411. }
  39412. function getVF(n, opt_precision) {
  39413. var v = opt_precision;
  39414. if (undefined === v) {
  39415. v = Math.min(getDecimals(n), 3);
  39416. }
  39417. var base = Math.pow(10, v);
  39418. var f = ((n * base) | 0) % base;
  39419. return {v: v, f: f};
  39420. }
  39421. $provide.value("$locale", {
  39422. "DATETIME_FORMATS": {
  39423. "AMPMS": [
  39424. "AM",
  39425. "PM"
  39426. ],
  39427. "DAY": [
  39428. "Sunday",
  39429. "Monday",
  39430. "Tuesday",
  39431. "Wednesday",
  39432. "Thursday",
  39433. "Friday",
  39434. "Saturday"
  39435. ],
  39436. "ERANAMES": [
  39437. "Before Christ",
  39438. "Anno Domini"
  39439. ],
  39440. "ERAS": [
  39441. "BC",
  39442. "AD"
  39443. ],
  39444. "FIRSTDAYOFWEEK": 6,
  39445. "MONTH": [
  39446. "January",
  39447. "February",
  39448. "March",
  39449. "April",
  39450. "May",
  39451. "June",
  39452. "July",
  39453. "August",
  39454. "September",
  39455. "October",
  39456. "November",
  39457. "December"
  39458. ],
  39459. "SHORTDAY": [
  39460. "Sun",
  39461. "Mon",
  39462. "Tue",
  39463. "Wed",
  39464. "Thu",
  39465. "Fri",
  39466. "Sat"
  39467. ],
  39468. "SHORTMONTH": [
  39469. "Jan",
  39470. "Feb",
  39471. "Mar",
  39472. "Apr",
  39473. "May",
  39474. "Jun",
  39475. "Jul",
  39476. "Aug",
  39477. "Sep",
  39478. "Oct",
  39479. "Nov",
  39480. "Dec"
  39481. ],
  39482. "STANDALONEMONTH": [
  39483. "January",
  39484. "February",
  39485. "March",
  39486. "April",
  39487. "May",
  39488. "June",
  39489. "July",
  39490. "August",
  39491. "September",
  39492. "October",
  39493. "November",
  39494. "December"
  39495. ],
  39496. "WEEKENDRANGE": [
  39497. 5,
  39498. 6
  39499. ],
  39500. "fullDate": "EEEE, MMMM d, y",
  39501. "longDate": "MMMM d, y",
  39502. "medium": "MMM d, y h:mm:ss a",
  39503. "mediumDate": "MMM d, y",
  39504. "mediumTime": "h:mm:ss a",
  39505. "short": "M/d/yy h:mm a",
  39506. "shortDate": "M/d/yy",
  39507. "shortTime": "h:mm a"
  39508. },
  39509. "NUMBER_FORMATS": {
  39510. "CURRENCY_SYM": "$",
  39511. "DECIMAL_SEP": ".",
  39512. "GROUP_SEP": ",",
  39513. "PATTERNS": [
  39514. {
  39515. "gSize": 3,
  39516. "lgSize": 3,
  39517. "maxFrac": 3,
  39518. "minFrac": 0,
  39519. "minInt": 1,
  39520. "negPre": "-",
  39521. "negSuf": "",
  39522. "posPre": "",
  39523. "posSuf": ""
  39524. },
  39525. {
  39526. "gSize": 3,
  39527. "lgSize": 3,
  39528. "maxFrac": 2,
  39529. "minFrac": 2,
  39530. "minInt": 1,
  39531. "negPre": "-\u00a4",
  39532. "negSuf": "",
  39533. "posPre": "\u00a4",
  39534. "posSuf": ""
  39535. }
  39536. ]
  39537. },
  39538. "id": "en-us",
  39539. "localeID": "en_US",
  39540. "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;}
  39541. });
  39542. }]);
  39543. jqLite(document).ready(function() {
  39544. angularInit(document, bootstrap);
  39545. });
  39546. })(window, document);
  39547. !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>');
  39548. /*!
  39549. * ionic.bundle.js is a concatenation of:
  39550. * ionic.js, angular.js, angular-animate.js,
  39551. * angular-sanitize.js, angular-ui-router.js,
  39552. * and ionic-angular.js
  39553. */
  39554. /**
  39555. * @license AngularJS v1.5.3
  39556. * (c) 2010-2016 Google, Inc. http://angularjs.org
  39557. * License: MIT
  39558. */
  39559. (function(window, angular, undefined) {'use strict';
  39560. /* jshint ignore:start */
  39561. var noop = angular.noop;
  39562. var copy = angular.copy;
  39563. var extend = angular.extend;
  39564. var jqLite = angular.element;
  39565. var forEach = angular.forEach;
  39566. var isArray = angular.isArray;
  39567. var isString = angular.isString;
  39568. var isObject = angular.isObject;
  39569. var isUndefined = angular.isUndefined;
  39570. var isDefined = angular.isDefined;
  39571. var isFunction = angular.isFunction;
  39572. var isElement = angular.isElement;
  39573. var ELEMENT_NODE = 1;
  39574. var COMMENT_NODE = 8;
  39575. var ADD_CLASS_SUFFIX = '-add';
  39576. var REMOVE_CLASS_SUFFIX = '-remove';
  39577. var EVENT_CLASS_PREFIX = 'ng-';
  39578. var ACTIVE_CLASS_SUFFIX = '-active';
  39579. var PREPARE_CLASS_SUFFIX = '-prepare';
  39580. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  39581. var NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';
  39582. // Detect proper transitionend/animationend event names.
  39583. var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
  39584. // If unprefixed events are not supported but webkit-prefixed are, use the latter.
  39585. // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
  39586. // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
  39587. // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
  39588. // Register both events in case `window.onanimationend` is not supported because of that,
  39589. // do the same for `transitionend` as Safari is likely to exhibit similar behavior.
  39590. // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
  39591. // therefore there is no reason to test anymore for other vendor prefixes:
  39592. // http://caniuse.com/#search=transition
  39593. if (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {
  39594. CSS_PREFIX = '-webkit-';
  39595. TRANSITION_PROP = 'WebkitTransition';
  39596. TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
  39597. } else {
  39598. TRANSITION_PROP = 'transition';
  39599. TRANSITIONEND_EVENT = 'transitionend';
  39600. }
  39601. if (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {
  39602. CSS_PREFIX = '-webkit-';
  39603. ANIMATION_PROP = 'WebkitAnimation';
  39604. ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
  39605. } else {
  39606. ANIMATION_PROP = 'animation';
  39607. ANIMATIONEND_EVENT = 'animationend';
  39608. }
  39609. var DURATION_KEY = 'Duration';
  39610. var PROPERTY_KEY = 'Property';
  39611. var DELAY_KEY = 'Delay';
  39612. var TIMING_KEY = 'TimingFunction';
  39613. var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
  39614. var ANIMATION_PLAYSTATE_KEY = 'PlayState';
  39615. var SAFE_FAST_FORWARD_DURATION_VALUE = 9999;
  39616. var ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;
  39617. var ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;
  39618. var TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;
  39619. var TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;
  39620. var isPromiseLike = function(p) {
  39621. return p && p.then ? true : false;
  39622. };
  39623. var ngMinErr = angular.$$minErr('ng');
  39624. function assertArg(arg, name, reason) {
  39625. if (!arg) {
  39626. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  39627. }
  39628. return arg;
  39629. }
  39630. function mergeClasses(a,b) {
  39631. if (!a && !b) return '';
  39632. if (!a) return b;
  39633. if (!b) return a;
  39634. if (isArray(a)) a = a.join(' ');
  39635. if (isArray(b)) b = b.join(' ');
  39636. return a + ' ' + b;
  39637. }
  39638. function packageStyles(options) {
  39639. var styles = {};
  39640. if (options && (options.to || options.from)) {
  39641. styles.to = options.to;
  39642. styles.from = options.from;
  39643. }
  39644. return styles;
  39645. }
  39646. function pendClasses(classes, fix, isPrefix) {
  39647. var className = '';
  39648. classes = isArray(classes)
  39649. ? classes
  39650. : classes && isString(classes) && classes.length
  39651. ? classes.split(/\s+/)
  39652. : [];
  39653. forEach(classes, function(klass, i) {
  39654. if (klass && klass.length > 0) {
  39655. className += (i > 0) ? ' ' : '';
  39656. className += isPrefix ? fix + klass
  39657. : klass + fix;
  39658. }
  39659. });
  39660. return className;
  39661. }
  39662. function removeFromArray(arr, val) {
  39663. var index = arr.indexOf(val);
  39664. if (val >= 0) {
  39665. arr.splice(index, 1);
  39666. }
  39667. }
  39668. function stripCommentsFromElement(element) {
  39669. if (element instanceof jqLite) {
  39670. switch (element.length) {
  39671. case 0:
  39672. return [];
  39673. break;
  39674. case 1:
  39675. // there is no point of stripping anything if the element
  39676. // is the only element within the jqLite wrapper.
  39677. // (it's important that we retain the element instance.)
  39678. if (element[0].nodeType === ELEMENT_NODE) {
  39679. return element;
  39680. }
  39681. break;
  39682. default:
  39683. return jqLite(extractElementNode(element));
  39684. break;
  39685. }
  39686. }
  39687. if (element.nodeType === ELEMENT_NODE) {
  39688. return jqLite(element);
  39689. }
  39690. }
  39691. function extractElementNode(element) {
  39692. if (!element[0]) return element;
  39693. for (var i = 0; i < element.length; i++) {
  39694. var elm = element[i];
  39695. if (elm.nodeType == ELEMENT_NODE) {
  39696. return elm;
  39697. }
  39698. }
  39699. }
  39700. function $$addClass($$jqLite, element, className) {
  39701. forEach(element, function(elm) {
  39702. $$jqLite.addClass(elm, className);
  39703. });
  39704. }
  39705. function $$removeClass($$jqLite, element, className) {
  39706. forEach(element, function(elm) {
  39707. $$jqLite.removeClass(elm, className);
  39708. });
  39709. }
  39710. function applyAnimationClassesFactory($$jqLite) {
  39711. return function(element, options) {
  39712. if (options.addClass) {
  39713. $$addClass($$jqLite, element, options.addClass);
  39714. options.addClass = null;
  39715. }
  39716. if (options.removeClass) {
  39717. $$removeClass($$jqLite, element, options.removeClass);
  39718. options.removeClass = null;
  39719. }
  39720. }
  39721. }
  39722. function prepareAnimationOptions(options) {
  39723. options = options || {};
  39724. if (!options.$$prepared) {
  39725. var domOperation = options.domOperation || noop;
  39726. options.domOperation = function() {
  39727. options.$$domOperationFired = true;
  39728. domOperation();
  39729. domOperation = noop;
  39730. };
  39731. options.$$prepared = true;
  39732. }
  39733. return options;
  39734. }
  39735. function applyAnimationStyles(element, options) {
  39736. applyAnimationFromStyles(element, options);
  39737. applyAnimationToStyles(element, options);
  39738. }
  39739. function applyAnimationFromStyles(element, options) {
  39740. if (options.from) {
  39741. element.css(options.from);
  39742. options.from = null;
  39743. }
  39744. }
  39745. function applyAnimationToStyles(element, options) {
  39746. if (options.to) {
  39747. element.css(options.to);
  39748. options.to = null;
  39749. }
  39750. }
  39751. function mergeAnimationDetails(element, oldAnimation, newAnimation) {
  39752. var target = oldAnimation.options || {};
  39753. var newOptions = newAnimation.options || {};
  39754. var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');
  39755. var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');
  39756. var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);
  39757. if (newOptions.preparationClasses) {
  39758. target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);
  39759. delete newOptions.preparationClasses;
  39760. }
  39761. // noop is basically when there is no callback; otherwise something has been set
  39762. var realDomOperation = target.domOperation !== noop ? target.domOperation : null;
  39763. extend(target, newOptions);
  39764. // 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.
  39765. if (realDomOperation) {
  39766. target.domOperation = realDomOperation;
  39767. }
  39768. if (classes.addClass) {
  39769. target.addClass = classes.addClass;
  39770. } else {
  39771. target.addClass = null;
  39772. }
  39773. if (classes.removeClass) {
  39774. target.removeClass = classes.removeClass;
  39775. } else {
  39776. target.removeClass = null;
  39777. }
  39778. oldAnimation.addClass = target.addClass;
  39779. oldAnimation.removeClass = target.removeClass;
  39780. return target;
  39781. }
  39782. function resolveElementClasses(existing, toAdd, toRemove) {
  39783. var ADD_CLASS = 1;
  39784. var REMOVE_CLASS = -1;
  39785. var flags = {};
  39786. existing = splitClassesToLookup(existing);
  39787. toAdd = splitClassesToLookup(toAdd);
  39788. forEach(toAdd, function(value, key) {
  39789. flags[key] = ADD_CLASS;
  39790. });
  39791. toRemove = splitClassesToLookup(toRemove);
  39792. forEach(toRemove, function(value, key) {
  39793. flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;
  39794. });
  39795. var classes = {
  39796. addClass: '',
  39797. removeClass: ''
  39798. };
  39799. forEach(flags, function(val, klass) {
  39800. var prop, allow;
  39801. if (val === ADD_CLASS) {
  39802. prop = 'addClass';
  39803. allow = !existing[klass];
  39804. } else if (val === REMOVE_CLASS) {
  39805. prop = 'removeClass';
  39806. allow = existing[klass];
  39807. }
  39808. if (allow) {
  39809. if (classes[prop].length) {
  39810. classes[prop] += ' ';
  39811. }
  39812. classes[prop] += klass;
  39813. }
  39814. });
  39815. function splitClassesToLookup(classes) {
  39816. if (isString(classes)) {
  39817. classes = classes.split(' ');
  39818. }
  39819. var obj = {};
  39820. forEach(classes, function(klass) {
  39821. // sometimes the split leaves empty string values
  39822. // incase extra spaces were applied to the options
  39823. if (klass.length) {
  39824. obj[klass] = true;
  39825. }
  39826. });
  39827. return obj;
  39828. }
  39829. return classes;
  39830. }
  39831. function getDomNode(element) {
  39832. return (element instanceof angular.element) ? element[0] : element;
  39833. }
  39834. function applyGeneratedPreparationClasses(element, event, options) {
  39835. var classes = '';
  39836. if (event) {
  39837. classes = pendClasses(event, EVENT_CLASS_PREFIX, true);
  39838. }
  39839. if (options.addClass) {
  39840. classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));
  39841. }
  39842. if (options.removeClass) {
  39843. classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));
  39844. }
  39845. if (classes.length) {
  39846. options.preparationClasses = classes;
  39847. element.addClass(classes);
  39848. }
  39849. }
  39850. function clearGeneratedClasses(element, options) {
  39851. if (options.preparationClasses) {
  39852. element.removeClass(options.preparationClasses);
  39853. options.preparationClasses = null;
  39854. }
  39855. if (options.activeClasses) {
  39856. element.removeClass(options.activeClasses);
  39857. options.activeClasses = null;
  39858. }
  39859. }
  39860. function blockTransitions(node, duration) {
  39861. // we use a negative delay value since it performs blocking
  39862. // yet it doesn't kill any existing transitions running on the
  39863. // same element which makes this safe for class-based animations
  39864. var value = duration ? '-' + duration + 's' : '';
  39865. applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);
  39866. return [TRANSITION_DELAY_PROP, value];
  39867. }
  39868. function blockKeyframeAnimations(node, applyBlock) {
  39869. var value = applyBlock ? 'paused' : '';
  39870. var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;
  39871. applyInlineStyle(node, [key, value]);
  39872. return [key, value];
  39873. }
  39874. function applyInlineStyle(node, styleTuple) {
  39875. var prop = styleTuple[0];
  39876. var value = styleTuple[1];
  39877. node.style[prop] = value;
  39878. }
  39879. function concatWithSpace(a,b) {
  39880. if (!a) return b;
  39881. if (!b) return a;
  39882. return a + ' ' + b;
  39883. }
  39884. var $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {
  39885. var queue, cancelFn;
  39886. function scheduler(tasks) {
  39887. // we make a copy since RAFScheduler mutates the state
  39888. // of the passed in array variable and this would be difficult
  39889. // to track down on the outside code
  39890. queue = queue.concat(tasks);
  39891. nextTick();
  39892. }
  39893. queue = scheduler.queue = [];
  39894. /* waitUntilQuiet does two things:
  39895. * 1. It will run the FINAL `fn` value only when an uncanceled RAF has passed through
  39896. * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.
  39897. *
  39898. * The motivation here is that animation code can request more time from the scheduler
  39899. * before the next wave runs. This allows for certain DOM properties such as classes to
  39900. * be resolved in time for the next animation to run.
  39901. */
  39902. scheduler.waitUntilQuiet = function(fn) {
  39903. if (cancelFn) cancelFn();
  39904. cancelFn = $$rAF(function() {
  39905. cancelFn = null;
  39906. fn();
  39907. nextTick();
  39908. });
  39909. };
  39910. return scheduler;
  39911. function nextTick() {
  39912. if (!queue.length) return;
  39913. var items = queue.shift();
  39914. for (var i = 0; i < items.length; i++) {
  39915. items[i]();
  39916. }
  39917. if (!cancelFn) {
  39918. $$rAF(function() {
  39919. if (!cancelFn) nextTick();
  39920. });
  39921. }
  39922. }
  39923. }];
  39924. /**
  39925. * @ngdoc directive
  39926. * @name ngAnimateChildren
  39927. * @restrict AE
  39928. * @element ANY
  39929. *
  39930. * @description
  39931. *
  39932. * ngAnimateChildren allows you to specify that children of this element should animate even if any
  39933. * of the children's parents are currently animating. By default, when an element has an active `enter`, `leave`, or `move`
  39934. * (structural) animation, child elements that also have an active structural animation are not animated.
  39935. *
  39936. * Note that even if `ngAnimteChildren` is set, no child animations will run when the parent element is removed from the DOM (`leave` animation).
  39937. *
  39938. *
  39939. * @param {string} ngAnimateChildren If the value is empty, `true` or `on`,
  39940. * then child animations are allowed. If the value is `false`, child animations are not allowed.
  39941. *
  39942. * @example
  39943. * <example module="ngAnimateChildren" name="ngAnimateChildren" deps="angular-animate.js" animations="true">
  39944. <file name="index.html">
  39945. <div ng-controller="mainController as main">
  39946. <label>Show container? <input type="checkbox" ng-model="main.enterElement" /></label>
  39947. <label>Animate children? <input type="checkbox" ng-model="main.animateChildren" /></label>
  39948. <hr>
  39949. <div ng-animate-children="{{main.animateChildren}}">
  39950. <div ng-if="main.enterElement" class="container">
  39951. List of items:
  39952. <div ng-repeat="item in [0, 1, 2, 3]" class="item">Item {{item}}</div>
  39953. </div>
  39954. </div>
  39955. </div>
  39956. </file>
  39957. <file name="animations.css">
  39958. .container.ng-enter,
  39959. .container.ng-leave {
  39960. transition: all ease 1.5s;
  39961. }
  39962. .container.ng-enter,
  39963. .container.ng-leave-active {
  39964. opacity: 0;
  39965. }
  39966. .container.ng-leave,
  39967. .container.ng-enter-active {
  39968. opacity: 1;
  39969. }
  39970. .item {
  39971. background: firebrick;
  39972. color: #FFF;
  39973. margin-bottom: 10px;
  39974. }
  39975. .item.ng-enter,
  39976. .item.ng-leave {
  39977. transition: transform 1.5s ease;
  39978. }
  39979. .item.ng-enter {
  39980. transform: translateX(50px);
  39981. }
  39982. .item.ng-enter-active {
  39983. transform: translateX(0);
  39984. }
  39985. </file>
  39986. <file name="script.js">
  39987. angular.module('ngAnimateChildren', ['ngAnimate'])
  39988. .controller('mainController', function() {
  39989. this.animateChildren = false;
  39990. this.enterElement = false;
  39991. });
  39992. </file>
  39993. </example>
  39994. */
  39995. var $$AnimateChildrenDirective = ['$interpolate', function($interpolate) {
  39996. return {
  39997. link: function(scope, element, attrs) {
  39998. var val = attrs.ngAnimateChildren;
  39999. if (angular.isString(val) && val.length === 0) { //empty attribute
  40000. element.data(NG_ANIMATE_CHILDREN_DATA, true);
  40001. } else {
  40002. // Interpolate and set the value, so that it is available to
  40003. // animations that run right after compilation
  40004. setData($interpolate(val)(scope));
  40005. attrs.$observe('ngAnimateChildren', setData);
  40006. }
  40007. function setData(value) {
  40008. value = value === 'on' || value === 'true';
  40009. element.data(NG_ANIMATE_CHILDREN_DATA, value);
  40010. }
  40011. }
  40012. };
  40013. }];
  40014. var ANIMATE_TIMER_KEY = '$$animateCss';
  40015. /**
  40016. * @ngdoc service
  40017. * @name $animateCss
  40018. * @kind object
  40019. *
  40020. * @description
  40021. * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes
  40022. * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT
  40023. * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or
  40024. * directives to create more complex animations that can be purely driven using CSS code.
  40025. *
  40026. * Note that only browsers that support CSS transitions and/or keyframe animations are capable of
  40027. * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).
  40028. *
  40029. * ## Usage
  40030. * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that
  40031. * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,
  40032. * any automatic control over cancelling animations and/or preventing animations from being run on
  40033. * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to
  40034. * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger
  40035. * the CSS animation.
  40036. *
  40037. * The example below shows how we can create a folding animation on an element using `ng-if`:
  40038. *
  40039. * ```html
  40040. * <!-- notice the `fold-animation` CSS class -->
  40041. * <div ng-if="onOff" class="fold-animation">
  40042. * This element will go BOOM
  40043. * </div>
  40044. * <button ng-click="onOff=true">Fold In</button>
  40045. * ```
  40046. *
  40047. * Now we create the **JavaScript animation** that will trigger the CSS transition:
  40048. *
  40049. * ```js
  40050. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  40051. * return {
  40052. * enter: function(element, doneFn) {
  40053. * var height = element[0].offsetHeight;
  40054. * return $animateCss(element, {
  40055. * from: { height:'0px' },
  40056. * to: { height:height + 'px' },
  40057. * duration: 1 // one second
  40058. * });
  40059. * }
  40060. * }
  40061. * }]);
  40062. * ```
  40063. *
  40064. * ## More Advanced Uses
  40065. *
  40066. * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks
  40067. * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.
  40068. *
  40069. * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,
  40070. * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with
  40071. * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order
  40072. * to provide a working animation that will run in CSS.
  40073. *
  40074. * The example below showcases a more advanced version of the `.fold-animation` from the example above:
  40075. *
  40076. * ```js
  40077. * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {
  40078. * return {
  40079. * enter: function(element, doneFn) {
  40080. * var height = element[0].offsetHeight;
  40081. * return $animateCss(element, {
  40082. * addClass: 'red large-text pulse-twice',
  40083. * easing: 'ease-out',
  40084. * from: { height:'0px' },
  40085. * to: { height:height + 'px' },
  40086. * duration: 1 // one second
  40087. * });
  40088. * }
  40089. * }
  40090. * }]);
  40091. * ```
  40092. *
  40093. * Since we're adding/removing CSS classes then the CSS transition will also pick those up:
  40094. *
  40095. * ```css
  40096. * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,
  40097. * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/
  40098. * .red { background:red; }
  40099. * .large-text { font-size:20px; }
  40100. *
  40101. * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/
  40102. * .pulse-twice {
  40103. * animation: 0.5s pulse linear 2;
  40104. * -webkit-animation: 0.5s pulse linear 2;
  40105. * }
  40106. *
  40107. * @keyframes pulse {
  40108. * from { transform: scale(0.5); }
  40109. * to { transform: scale(1.5); }
  40110. * }
  40111. *
  40112. * @-webkit-keyframes pulse {
  40113. * from { -webkit-transform: scale(0.5); }
  40114. * to { -webkit-transform: scale(1.5); }
  40115. * }
  40116. * ```
  40117. *
  40118. * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.
  40119. *
  40120. * ## How the Options are handled
  40121. *
  40122. * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation
  40123. * 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
  40124. * styles using the `from` and `to` properties.
  40125. *
  40126. * ```js
  40127. * var animator = $animateCss(element, {
  40128. * from: { background:'red' },
  40129. * to: { background:'blue' }
  40130. * });
  40131. * animator.start();
  40132. * ```
  40133. *
  40134. * ```css
  40135. * .rotating-animation {
  40136. * animation:0.5s rotate linear;
  40137. * -webkit-animation:0.5s rotate linear;
  40138. * }
  40139. *
  40140. * @keyframes rotate {
  40141. * from { transform: rotate(0deg); }
  40142. * to { transform: rotate(360deg); }
  40143. * }
  40144. *
  40145. * @-webkit-keyframes rotate {
  40146. * from { -webkit-transform: rotate(0deg); }
  40147. * to { -webkit-transform: rotate(360deg); }
  40148. * }
  40149. * ```
  40150. *
  40151. * 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
  40152. * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition
  40153. * 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
  40154. * 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
  40155. * and spread across the transition and keyframe animation.
  40156. *
  40157. * ## What is returned
  40158. *
  40159. * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually
  40160. * 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
  40161. * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:
  40162. *
  40163. * ```js
  40164. * var animator = $animateCss(element, { ... });
  40165. * ```
  40166. *
  40167. * Now what do the contents of our `animator` variable look like:
  40168. *
  40169. * ```js
  40170. * {
  40171. * // starts the animation
  40172. * start: Function,
  40173. *
  40174. * // ends (aborts) the animation
  40175. * end: Function
  40176. * }
  40177. * ```
  40178. *
  40179. * 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.
  40180. * 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
  40181. * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties
  40182. * and that changing them will not reconfigure the parameters of the animation.
  40183. *
  40184. * ### runner.done() vs runner.then()
  40185. * 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
  40186. * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.
  40187. * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`
  40188. * unless you really need a digest to kick off afterwards.
  40189. *
  40190. * 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
  40191. * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).
  40192. * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.
  40193. *
  40194. * @param {DOMElement} element the element that will be animated
  40195. * @param {object} options the animation-related options that will be applied during the animation
  40196. *
  40197. * * `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
  40198. * 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.)
  40199. * * `structural` - Indicates that the `ng-` prefix will be added to the event class. Setting to `false` or omitting will turn `ng-EVENT` and
  40200. * `ng-EVENT-active` in `EVENT` and `EVENT-active`. Unused if `event` is omitted.
  40201. * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).
  40202. * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).
  40203. * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).
  40204. * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.
  40205. * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.
  40206. * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.
  40207. * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.
  40208. * * `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`
  40209. * is provided then the animation will be skipped entirely.
  40210. * * `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
  40211. * 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
  40212. * 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
  40213. * CSS delay value.
  40214. * * `stagger` - A numeric time value representing the delay between successively animated elements
  40215. * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})
  40216. * * `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
  40217. * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)
  40218. * * `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.)
  40219. * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once
  40220. * the animation is closed. This is useful for when the styles are used purely for the sake of
  40221. * the animation and do not have a lasting visual effect on the element (e.g. a collapse and open animation).
  40222. * By default this value is set to `false`.
  40223. *
  40224. * @return {object} an object with start and end methods and details about the animation.
  40225. *
  40226. * * `start` - The method to start the animation. This will return a `Promise` when called.
  40227. * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.
  40228. */
  40229. var ONE_SECOND = 1000;
  40230. var BASE_TEN = 10;
  40231. var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
  40232. var CLOSING_TIME_BUFFER = 1.5;
  40233. var DETECT_CSS_PROPERTIES = {
  40234. transitionDuration: TRANSITION_DURATION_PROP,
  40235. transitionDelay: TRANSITION_DELAY_PROP,
  40236. transitionProperty: TRANSITION_PROP + PROPERTY_KEY,
  40237. animationDuration: ANIMATION_DURATION_PROP,
  40238. animationDelay: ANIMATION_DELAY_PROP,
  40239. animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY
  40240. };
  40241. var DETECT_STAGGER_CSS_PROPERTIES = {
  40242. transitionDuration: TRANSITION_DURATION_PROP,
  40243. transitionDelay: TRANSITION_DELAY_PROP,
  40244. animationDuration: ANIMATION_DURATION_PROP,
  40245. animationDelay: ANIMATION_DELAY_PROP
  40246. };
  40247. function getCssKeyframeDurationStyle(duration) {
  40248. return [ANIMATION_DURATION_PROP, duration + 's'];
  40249. }
  40250. function getCssDelayStyle(delay, isKeyframeAnimation) {
  40251. var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;
  40252. return [prop, delay + 's'];
  40253. }
  40254. function computeCssStyles($window, element, properties) {
  40255. var styles = Object.create(null);
  40256. var detectedStyles = $window.getComputedStyle(element) || {};
  40257. forEach(properties, function(formalStyleName, actualStyleName) {
  40258. var val = detectedStyles[formalStyleName];
  40259. if (val) {
  40260. var c = val.charAt(0);
  40261. // only numerical-based values have a negative sign or digit as the first value
  40262. if (c === '-' || c === '+' || c >= 0) {
  40263. val = parseMaxTime(val);
  40264. }
  40265. // by setting this to null in the event that the delay is not set or is set directly as 0
  40266. // then we can still allow for negative values to be used later on and not mistake this
  40267. // value for being greater than any other negative value.
  40268. if (val === 0) {
  40269. val = null;
  40270. }
  40271. styles[actualStyleName] = val;
  40272. }
  40273. });
  40274. return styles;
  40275. }
  40276. function parseMaxTime(str) {
  40277. var maxValue = 0;
  40278. var values = str.split(/\s*,\s*/);
  40279. forEach(values, function(value) {
  40280. // it's always safe to consider only second values and omit `ms` values since
  40281. // getComputedStyle will always handle the conversion for us
  40282. if (value.charAt(value.length - 1) == 's') {
  40283. value = value.substring(0, value.length - 1);
  40284. }
  40285. value = parseFloat(value) || 0;
  40286. maxValue = maxValue ? Math.max(value, maxValue) : value;
  40287. });
  40288. return maxValue;
  40289. }
  40290. function truthyTimingValue(val) {
  40291. return val === 0 || val != null;
  40292. }
  40293. function getCssTransitionDurationStyle(duration, applyOnlyDuration) {
  40294. var style = TRANSITION_PROP;
  40295. var value = duration + 's';
  40296. if (applyOnlyDuration) {
  40297. style += DURATION_KEY;
  40298. } else {
  40299. value += ' linear all';
  40300. }
  40301. return [style, value];
  40302. }
  40303. function createLocalCacheLookup() {
  40304. var cache = Object.create(null);
  40305. return {
  40306. flush: function() {
  40307. cache = Object.create(null);
  40308. },
  40309. count: function(key) {
  40310. var entry = cache[key];
  40311. return entry ? entry.total : 0;
  40312. },
  40313. get: function(key) {
  40314. var entry = cache[key];
  40315. return entry && entry.value;
  40316. },
  40317. put: function(key, value) {
  40318. if (!cache[key]) {
  40319. cache[key] = { total: 1, value: value };
  40320. } else {
  40321. cache[key].total++;
  40322. }
  40323. }
  40324. };
  40325. }
  40326. // we do not reassign an already present style value since
  40327. // if we detect the style property value again we may be
  40328. // detecting styles that were added via the `from` styles.
  40329. // We make use of `isDefined` here since an empty string
  40330. // or null value (which is what getPropertyValue will return
  40331. // for a non-existing style) will still be marked as a valid
  40332. // value for the style (a falsy value implies that the style
  40333. // is to be removed at the end of the animation). If we had a simple
  40334. // "OR" statement then it would not be enough to catch that.
  40335. function registerRestorableStyles(backup, node, properties) {
  40336. forEach(properties, function(prop) {
  40337. backup[prop] = isDefined(backup[prop])
  40338. ? backup[prop]
  40339. : node.style.getPropertyValue(prop);
  40340. });
  40341. }
  40342. var $AnimateCssProvider = ['$animateProvider', function($animateProvider) {
  40343. var gcsLookup = createLocalCacheLookup();
  40344. var gcsStaggerLookup = createLocalCacheLookup();
  40345. this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',
  40346. '$$forceReflow', '$sniffer', '$$rAFScheduler', '$$animateQueue',
  40347. function($window, $$jqLite, $$AnimateRunner, $timeout,
  40348. $$forceReflow, $sniffer, $$rAFScheduler, $$animateQueue) {
  40349. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  40350. var parentCounter = 0;
  40351. function gcsHashFn(node, extraClasses) {
  40352. var KEY = "$$ngAnimateParentKey";
  40353. var parentNode = node.parentNode;
  40354. var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);
  40355. return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;
  40356. }
  40357. function computeCachedCssStyles(node, className, cacheKey, properties) {
  40358. var timings = gcsLookup.get(cacheKey);
  40359. if (!timings) {
  40360. timings = computeCssStyles($window, node, properties);
  40361. if (timings.animationIterationCount === 'infinite') {
  40362. timings.animationIterationCount = 1;
  40363. }
  40364. }
  40365. // we keep putting this in multiple times even though the value and the cacheKey are the same
  40366. // because we're keeping an internal tally of how many duplicate animations are detected.
  40367. gcsLookup.put(cacheKey, timings);
  40368. return timings;
  40369. }
  40370. function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {
  40371. var stagger;
  40372. // if we have one or more existing matches of matching elements
  40373. // containing the same parent + CSS styles (which is how cacheKey works)
  40374. // then staggering is possible
  40375. if (gcsLookup.count(cacheKey) > 0) {
  40376. stagger = gcsStaggerLookup.get(cacheKey);
  40377. if (!stagger) {
  40378. var staggerClassName = pendClasses(className, '-stagger');
  40379. $$jqLite.addClass(node, staggerClassName);
  40380. stagger = computeCssStyles($window, node, properties);
  40381. // force the conversion of a null value to zero incase not set
  40382. stagger.animationDuration = Math.max(stagger.animationDuration, 0);
  40383. stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);
  40384. $$jqLite.removeClass(node, staggerClassName);
  40385. gcsStaggerLookup.put(cacheKey, stagger);
  40386. }
  40387. }
  40388. return stagger || {};
  40389. }
  40390. var cancelLastRAFRequest;
  40391. var rafWaitQueue = [];
  40392. function waitUntilQuiet(callback) {
  40393. rafWaitQueue.push(callback);
  40394. $$rAFScheduler.waitUntilQuiet(function() {
  40395. gcsLookup.flush();
  40396. gcsStaggerLookup.flush();
  40397. // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.
  40398. // PLEASE EXAMINE THE `$$forceReflow` service to understand why.
  40399. var pageWidth = $$forceReflow();
  40400. // we use a for loop to ensure that if the queue is changed
  40401. // during this looping then it will consider new requests
  40402. for (var i = 0; i < rafWaitQueue.length; i++) {
  40403. rafWaitQueue[i](pageWidth);
  40404. }
  40405. rafWaitQueue.length = 0;
  40406. });
  40407. }
  40408. function computeTimings(node, className, cacheKey) {
  40409. var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);
  40410. var aD = timings.animationDelay;
  40411. var tD = timings.transitionDelay;
  40412. timings.maxDelay = aD && tD
  40413. ? Math.max(aD, tD)
  40414. : (aD || tD);
  40415. timings.maxDuration = Math.max(
  40416. timings.animationDuration * timings.animationIterationCount,
  40417. timings.transitionDuration);
  40418. return timings;
  40419. }
  40420. return function init(element, initialOptions) {
  40421. // all of the animation functions should create
  40422. // a copy of the options data, however, if a
  40423. // parent service has already created a copy then
  40424. // we should stick to using that
  40425. var options = initialOptions || {};
  40426. if (!options.$$prepared) {
  40427. options = prepareAnimationOptions(copy(options));
  40428. }
  40429. var restoreStyles = {};
  40430. var node = getDomNode(element);
  40431. if (!node
  40432. || !node.parentNode
  40433. || !$$animateQueue.enabled()) {
  40434. return closeAndReturnNoopAnimator();
  40435. }
  40436. var temporaryStyles = [];
  40437. var classes = element.attr('class');
  40438. var styles = packageStyles(options);
  40439. var animationClosed;
  40440. var animationPaused;
  40441. var animationCompleted;
  40442. var runner;
  40443. var runnerHost;
  40444. var maxDelay;
  40445. var maxDelayTime;
  40446. var maxDuration;
  40447. var maxDurationTime;
  40448. var startTime;
  40449. var events = [];
  40450. if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {
  40451. return closeAndReturnNoopAnimator();
  40452. }
  40453. var method = options.event && isArray(options.event)
  40454. ? options.event.join(' ')
  40455. : options.event;
  40456. var isStructural = method && options.structural;
  40457. var structuralClassName = '';
  40458. var addRemoveClassName = '';
  40459. if (isStructural) {
  40460. structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);
  40461. } else if (method) {
  40462. structuralClassName = method;
  40463. }
  40464. if (options.addClass) {
  40465. addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);
  40466. }
  40467. if (options.removeClass) {
  40468. if (addRemoveClassName.length) {
  40469. addRemoveClassName += ' ';
  40470. }
  40471. addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);
  40472. }
  40473. // there may be a situation where a structural animation is combined together
  40474. // with CSS classes that need to resolve before the animation is computed.
  40475. // However this means that there is no explicit CSS code to block the animation
  40476. // from happening (by setting 0s none in the class name). If this is the case
  40477. // we need to apply the classes before the first rAF so we know to continue if
  40478. // there actually is a detected transition or keyframe animation
  40479. if (options.applyClassesEarly && addRemoveClassName.length) {
  40480. applyAnimationClasses(element, options);
  40481. }
  40482. var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();
  40483. var fullClassName = classes + ' ' + preparationClasses;
  40484. var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);
  40485. var hasToStyles = styles.to && Object.keys(styles.to).length > 0;
  40486. var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;
  40487. // there is no way we can trigger an animation if no styles and
  40488. // no classes are being applied which would then trigger a transition,
  40489. // unless there a is raw keyframe value that is applied to the element.
  40490. if (!containsKeyframeAnimation
  40491. && !hasToStyles
  40492. && !preparationClasses) {
  40493. return closeAndReturnNoopAnimator();
  40494. }
  40495. var cacheKey, stagger;
  40496. if (options.stagger > 0) {
  40497. var staggerVal = parseFloat(options.stagger);
  40498. stagger = {
  40499. transitionDelay: staggerVal,
  40500. animationDelay: staggerVal,
  40501. transitionDuration: 0,
  40502. animationDuration: 0
  40503. };
  40504. } else {
  40505. cacheKey = gcsHashFn(node, fullClassName);
  40506. stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);
  40507. }
  40508. if (!options.$$skipPreparationClasses) {
  40509. $$jqLite.addClass(element, preparationClasses);
  40510. }
  40511. var applyOnlyDuration;
  40512. if (options.transitionStyle) {
  40513. var transitionStyle = [TRANSITION_PROP, options.transitionStyle];
  40514. applyInlineStyle(node, transitionStyle);
  40515. temporaryStyles.push(transitionStyle);
  40516. }
  40517. if (options.duration >= 0) {
  40518. applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;
  40519. var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);
  40520. // we set the duration so that it will be picked up by getComputedStyle later
  40521. applyInlineStyle(node, durationStyle);
  40522. temporaryStyles.push(durationStyle);
  40523. }
  40524. if (options.keyframeStyle) {
  40525. var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];
  40526. applyInlineStyle(node, keyframeStyle);
  40527. temporaryStyles.push(keyframeStyle);
  40528. }
  40529. var itemIndex = stagger
  40530. ? options.staggerIndex >= 0
  40531. ? options.staggerIndex
  40532. : gcsLookup.count(cacheKey)
  40533. : 0;
  40534. var isFirst = itemIndex === 0;
  40535. // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY
  40536. // without causing any combination of transitions to kick in. By adding a negative delay value
  40537. // it forces the setup class' transition to end immediately. We later then remove the negative
  40538. // transition delay to allow for the transition to naturally do it's thing. The beauty here is
  40539. // that if there is no transition defined then nothing will happen and this will also allow
  40540. // other transitions to be stacked on top of each other without any chopping them out.
  40541. if (isFirst && !options.skipBlocking) {
  40542. blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);
  40543. }
  40544. var timings = computeTimings(node, fullClassName, cacheKey);
  40545. var relativeDelay = timings.maxDelay;
  40546. maxDelay = Math.max(relativeDelay, 0);
  40547. maxDuration = timings.maxDuration;
  40548. var flags = {};
  40549. flags.hasTransitions = timings.transitionDuration > 0;
  40550. flags.hasAnimations = timings.animationDuration > 0;
  40551. flags.hasTransitionAll = flags.hasTransitions && timings.transitionProperty == 'all';
  40552. flags.applyTransitionDuration = hasToStyles && (
  40553. (flags.hasTransitions && !flags.hasTransitionAll)
  40554. || (flags.hasAnimations && !flags.hasTransitions));
  40555. flags.applyAnimationDuration = options.duration && flags.hasAnimations;
  40556. flags.applyTransitionDelay = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);
  40557. flags.applyAnimationDelay = truthyTimingValue(options.delay) && flags.hasAnimations;
  40558. flags.recalculateTimingStyles = addRemoveClassName.length > 0;
  40559. if (flags.applyTransitionDuration || flags.applyAnimationDuration) {
  40560. maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;
  40561. if (flags.applyTransitionDuration) {
  40562. flags.hasTransitions = true;
  40563. timings.transitionDuration = maxDuration;
  40564. applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;
  40565. temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));
  40566. }
  40567. if (flags.applyAnimationDuration) {
  40568. flags.hasAnimations = true;
  40569. timings.animationDuration = maxDuration;
  40570. temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));
  40571. }
  40572. }
  40573. if (maxDuration === 0 && !flags.recalculateTimingStyles) {
  40574. return closeAndReturnNoopAnimator();
  40575. }
  40576. if (options.delay != null) {
  40577. var delayStyle;
  40578. if (typeof options.delay !== "boolean") {
  40579. delayStyle = parseFloat(options.delay);
  40580. // number in options.delay means we have to recalculate the delay for the closing timeout
  40581. maxDelay = Math.max(delayStyle, 0);
  40582. }
  40583. if (flags.applyTransitionDelay) {
  40584. temporaryStyles.push(getCssDelayStyle(delayStyle));
  40585. }
  40586. if (flags.applyAnimationDelay) {
  40587. temporaryStyles.push(getCssDelayStyle(delayStyle, true));
  40588. }
  40589. }
  40590. // we need to recalculate the delay value since we used a pre-emptive negative
  40591. // delay value and the delay value is required for the final event checking. This
  40592. // property will ensure that this will happen after the RAF phase has passed.
  40593. if (options.duration == null && timings.transitionDuration > 0) {
  40594. flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;
  40595. }
  40596. maxDelayTime = maxDelay * ONE_SECOND;
  40597. maxDurationTime = maxDuration * ONE_SECOND;
  40598. if (!options.skipBlocking) {
  40599. flags.blockTransition = timings.transitionDuration > 0;
  40600. flags.blockKeyframeAnimation = timings.animationDuration > 0 &&
  40601. stagger.animationDelay > 0 &&
  40602. stagger.animationDuration === 0;
  40603. }
  40604. if (options.from) {
  40605. if (options.cleanupStyles) {
  40606. registerRestorableStyles(restoreStyles, node, Object.keys(options.from));
  40607. }
  40608. applyAnimationFromStyles(element, options);
  40609. }
  40610. if (flags.blockTransition || flags.blockKeyframeAnimation) {
  40611. applyBlocking(maxDuration);
  40612. } else if (!options.skipBlocking) {
  40613. blockTransitions(node, false);
  40614. }
  40615. // TODO(matsko): for 1.5 change this code to have an animator object for better debugging
  40616. return {
  40617. $$willAnimate: true,
  40618. end: endFn,
  40619. start: function() {
  40620. if (animationClosed) return;
  40621. runnerHost = {
  40622. end: endFn,
  40623. cancel: cancelFn,
  40624. resume: null, //this will be set during the start() phase
  40625. pause: null
  40626. };
  40627. runner = new $$AnimateRunner(runnerHost);
  40628. waitUntilQuiet(start);
  40629. // we don't have access to pause/resume the animation
  40630. // since it hasn't run yet. AnimateRunner will therefore
  40631. // set noop functions for resume and pause and they will
  40632. // later be overridden once the animation is triggered
  40633. return runner;
  40634. }
  40635. };
  40636. function endFn() {
  40637. close();
  40638. }
  40639. function cancelFn() {
  40640. close(true);
  40641. }
  40642. function close(rejected) { // jshint ignore:line
  40643. // if the promise has been called already then we shouldn't close
  40644. // the animation again
  40645. if (animationClosed || (animationCompleted && animationPaused)) return;
  40646. animationClosed = true;
  40647. animationPaused = false;
  40648. if (!options.$$skipPreparationClasses) {
  40649. $$jqLite.removeClass(element, preparationClasses);
  40650. }
  40651. $$jqLite.removeClass(element, activeClasses);
  40652. blockKeyframeAnimations(node, false);
  40653. blockTransitions(node, false);
  40654. forEach(temporaryStyles, function(entry) {
  40655. // There is only one way to remove inline style properties entirely from elements.
  40656. // By using `removeProperty` this works, but we need to convert camel-cased CSS
  40657. // styles down to hyphenated values.
  40658. node.style[entry[0]] = '';
  40659. });
  40660. applyAnimationClasses(element, options);
  40661. applyAnimationStyles(element, options);
  40662. if (Object.keys(restoreStyles).length) {
  40663. forEach(restoreStyles, function(value, prop) {
  40664. value ? node.style.setProperty(prop, value)
  40665. : node.style.removeProperty(prop);
  40666. });
  40667. }
  40668. // the reason why we have this option is to allow a synchronous closing callback
  40669. // that is fired as SOON as the animation ends (when the CSS is removed) or if
  40670. // the animation never takes off at all. A good example is a leave animation since
  40671. // the element must be removed just after the animation is over or else the element
  40672. // will appear on screen for one animation frame causing an overbearing flicker.
  40673. if (options.onDone) {
  40674. options.onDone();
  40675. }
  40676. if (events && events.length) {
  40677. // Remove the transitionend / animationend listener(s)
  40678. element.off(events.join(' '), onAnimationProgress);
  40679. }
  40680. //Cancel the fallback closing timeout and remove the timer data
  40681. var animationTimerData = element.data(ANIMATE_TIMER_KEY);
  40682. if (animationTimerData) {
  40683. $timeout.cancel(animationTimerData[0].timer);
  40684. element.removeData(ANIMATE_TIMER_KEY);
  40685. }
  40686. // if the preparation function fails then the promise is not setup
  40687. if (runner) {
  40688. runner.complete(!rejected);
  40689. }
  40690. }
  40691. function applyBlocking(duration) {
  40692. if (flags.blockTransition) {
  40693. blockTransitions(node, duration);
  40694. }
  40695. if (flags.blockKeyframeAnimation) {
  40696. blockKeyframeAnimations(node, !!duration);
  40697. }
  40698. }
  40699. function closeAndReturnNoopAnimator() {
  40700. runner = new $$AnimateRunner({
  40701. end: endFn,
  40702. cancel: cancelFn
  40703. });
  40704. // should flush the cache animation
  40705. waitUntilQuiet(noop);
  40706. close();
  40707. return {
  40708. $$willAnimate: false,
  40709. start: function() {
  40710. return runner;
  40711. },
  40712. end: endFn
  40713. };
  40714. }
  40715. function onAnimationProgress(event) {
  40716. event.stopPropagation();
  40717. var ev = event.originalEvent || event;
  40718. // we now always use `Date.now()` due to the recent changes with
  40719. // event.timeStamp in Firefox, Webkit and Chrome (see #13494 for more info)
  40720. var timeStamp = ev.$manualTimeStamp || Date.now();
  40721. /* Firefox (or possibly just Gecko) likes to not round values up
  40722. * when a ms measurement is used for the animation */
  40723. var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
  40724. /* $manualTimeStamp is a mocked timeStamp value which is set
  40725. * within browserTrigger(). This is only here so that tests can
  40726. * mock animations properly. Real events fallback to event.timeStamp,
  40727. * or, if they don't, then a timeStamp is automatically created for them.
  40728. * We're checking to see if the timeStamp surpasses the expected delay,
  40729. * but we're using elapsedTime instead of the timeStamp on the 2nd
  40730. * pre-condition since animationPauseds sometimes close off early */
  40731. if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
  40732. // we set this flag to ensure that if the transition is paused then, when resumed,
  40733. // the animation will automatically close itself since transitions cannot be paused.
  40734. animationCompleted = true;
  40735. close();
  40736. }
  40737. }
  40738. function start() {
  40739. if (animationClosed) return;
  40740. if (!node.parentNode) {
  40741. close();
  40742. return;
  40743. }
  40744. // even though we only pause keyframe animations here the pause flag
  40745. // will still happen when transitions are used. Only the transition will
  40746. // not be paused since that is not possible. If the animation ends when
  40747. // paused then it will not complete until unpaused or cancelled.
  40748. var playPause = function(playAnimation) {
  40749. if (!animationCompleted) {
  40750. animationPaused = !playAnimation;
  40751. if (timings.animationDuration) {
  40752. var value = blockKeyframeAnimations(node, animationPaused);
  40753. animationPaused
  40754. ? temporaryStyles.push(value)
  40755. : removeFromArray(temporaryStyles, value);
  40756. }
  40757. } else if (animationPaused && playAnimation) {
  40758. animationPaused = false;
  40759. close();
  40760. }
  40761. };
  40762. // checking the stagger duration prevents an accidentally cascade of the CSS delay style
  40763. // being inherited from the parent. If the transition duration is zero then we can safely
  40764. // rely that the delay value is an intentional stagger delay style.
  40765. var maxStagger = itemIndex > 0
  40766. && ((timings.transitionDuration && stagger.transitionDuration === 0) ||
  40767. (timings.animationDuration && stagger.animationDuration === 0))
  40768. && Math.max(stagger.animationDelay, stagger.transitionDelay);
  40769. if (maxStagger) {
  40770. $timeout(triggerAnimationStart,
  40771. Math.floor(maxStagger * itemIndex * ONE_SECOND),
  40772. false);
  40773. } else {
  40774. triggerAnimationStart();
  40775. }
  40776. // this will decorate the existing promise runner with pause/resume methods
  40777. runnerHost.resume = function() {
  40778. playPause(true);
  40779. };
  40780. runnerHost.pause = function() {
  40781. playPause(false);
  40782. };
  40783. function triggerAnimationStart() {
  40784. // just incase a stagger animation kicks in when the animation
  40785. // itself was cancelled entirely
  40786. if (animationClosed) return;
  40787. applyBlocking(false);
  40788. forEach(temporaryStyles, function(entry) {
  40789. var key = entry[0];
  40790. var value = entry[1];
  40791. node.style[key] = value;
  40792. });
  40793. applyAnimationClasses(element, options);
  40794. $$jqLite.addClass(element, activeClasses);
  40795. if (flags.recalculateTimingStyles) {
  40796. fullClassName = node.className + ' ' + preparationClasses;
  40797. cacheKey = gcsHashFn(node, fullClassName);
  40798. timings = computeTimings(node, fullClassName, cacheKey);
  40799. relativeDelay = timings.maxDelay;
  40800. maxDelay = Math.max(relativeDelay, 0);
  40801. maxDuration = timings.maxDuration;
  40802. if (maxDuration === 0) {
  40803. close();
  40804. return;
  40805. }
  40806. flags.hasTransitions = timings.transitionDuration > 0;
  40807. flags.hasAnimations = timings.animationDuration > 0;
  40808. }
  40809. if (flags.applyAnimationDelay) {
  40810. relativeDelay = typeof options.delay !== "boolean" && truthyTimingValue(options.delay)
  40811. ? parseFloat(options.delay)
  40812. : relativeDelay;
  40813. maxDelay = Math.max(relativeDelay, 0);
  40814. timings.animationDelay = relativeDelay;
  40815. delayStyle = getCssDelayStyle(relativeDelay, true);
  40816. temporaryStyles.push(delayStyle);
  40817. node.style[delayStyle[0]] = delayStyle[1];
  40818. }
  40819. maxDelayTime = maxDelay * ONE_SECOND;
  40820. maxDurationTime = maxDuration * ONE_SECOND;
  40821. if (options.easing) {
  40822. var easeProp, easeVal = options.easing;
  40823. if (flags.hasTransitions) {
  40824. easeProp = TRANSITION_PROP + TIMING_KEY;
  40825. temporaryStyles.push([easeProp, easeVal]);
  40826. node.style[easeProp] = easeVal;
  40827. }
  40828. if (flags.hasAnimations) {
  40829. easeProp = ANIMATION_PROP + TIMING_KEY;
  40830. temporaryStyles.push([easeProp, easeVal]);
  40831. node.style[easeProp] = easeVal;
  40832. }
  40833. }
  40834. if (timings.transitionDuration) {
  40835. events.push(TRANSITIONEND_EVENT);
  40836. }
  40837. if (timings.animationDuration) {
  40838. events.push(ANIMATIONEND_EVENT);
  40839. }
  40840. startTime = Date.now();
  40841. var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;
  40842. var endTime = startTime + timerTime;
  40843. var animationsData = element.data(ANIMATE_TIMER_KEY) || [];
  40844. var setupFallbackTimer = true;
  40845. if (animationsData.length) {
  40846. var currentTimerData = animationsData[0];
  40847. setupFallbackTimer = endTime > currentTimerData.expectedEndTime;
  40848. if (setupFallbackTimer) {
  40849. $timeout.cancel(currentTimerData.timer);
  40850. } else {
  40851. animationsData.push(close);
  40852. }
  40853. }
  40854. if (setupFallbackTimer) {
  40855. var timer = $timeout(onAnimationExpired, timerTime, false);
  40856. animationsData[0] = {
  40857. timer: timer,
  40858. expectedEndTime: endTime
  40859. };
  40860. animationsData.push(close);
  40861. element.data(ANIMATE_TIMER_KEY, animationsData);
  40862. }
  40863. if (events.length) {
  40864. element.on(events.join(' '), onAnimationProgress);
  40865. }
  40866. if (options.to) {
  40867. if (options.cleanupStyles) {
  40868. registerRestorableStyles(restoreStyles, node, Object.keys(options.to));
  40869. }
  40870. applyAnimationToStyles(element, options);
  40871. }
  40872. }
  40873. function onAnimationExpired() {
  40874. var animationsData = element.data(ANIMATE_TIMER_KEY);
  40875. // this will be false in the event that the element was
  40876. // removed from the DOM (via a leave animation or something
  40877. // similar)
  40878. if (animationsData) {
  40879. for (var i = 1; i < animationsData.length; i++) {
  40880. animationsData[i]();
  40881. }
  40882. element.removeData(ANIMATE_TIMER_KEY);
  40883. }
  40884. }
  40885. }
  40886. };
  40887. }];
  40888. }];
  40889. var $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {
  40890. $$animationProvider.drivers.push('$$animateCssDriver');
  40891. var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';
  40892. var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';
  40893. var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';
  40894. var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';
  40895. function isDocumentFragment(node) {
  40896. return node.parentNode && node.parentNode.nodeType === 11;
  40897. }
  40898. this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',
  40899. function($animateCss, $rootScope, $$AnimateRunner, $rootElement, $sniffer, $$jqLite, $document) {
  40900. // only browsers that support these properties can render animations
  40901. if (!$sniffer.animations && !$sniffer.transitions) return noop;
  40902. var bodyNode = $document[0].body;
  40903. var rootNode = getDomNode($rootElement);
  40904. var rootBodyElement = jqLite(
  40905. // this is to avoid using something that exists outside of the body
  40906. // we also special case the doc fragment case because our unit test code
  40907. // appends the $rootElement to the body after the app has been bootstrapped
  40908. isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode
  40909. );
  40910. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  40911. return function initDriverFn(animationDetails) {
  40912. return animationDetails.from && animationDetails.to
  40913. ? prepareFromToAnchorAnimation(animationDetails.from,
  40914. animationDetails.to,
  40915. animationDetails.classes,
  40916. animationDetails.anchors)
  40917. : prepareRegularAnimation(animationDetails);
  40918. };
  40919. function filterCssClasses(classes) {
  40920. //remove all the `ng-` stuff
  40921. return classes.replace(/\bng-\S+\b/g, '');
  40922. }
  40923. function getUniqueValues(a, b) {
  40924. if (isString(a)) a = a.split(' ');
  40925. if (isString(b)) b = b.split(' ');
  40926. return a.filter(function(val) {
  40927. return b.indexOf(val) === -1;
  40928. }).join(' ');
  40929. }
  40930. function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {
  40931. var clone = jqLite(getDomNode(outAnchor).cloneNode(true));
  40932. var startingClasses = filterCssClasses(getClassVal(clone));
  40933. outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  40934. inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);
  40935. clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);
  40936. rootBodyElement.append(clone);
  40937. var animatorIn, animatorOut = prepareOutAnimation();
  40938. // the user may not end up using the `out` animation and
  40939. // only making use of the `in` animation or vice-versa.
  40940. // In either case we should allow this and not assume the
  40941. // animation is over unless both animations are not used.
  40942. if (!animatorOut) {
  40943. animatorIn = prepareInAnimation();
  40944. if (!animatorIn) {
  40945. return end();
  40946. }
  40947. }
  40948. var startingAnimator = animatorOut || animatorIn;
  40949. return {
  40950. start: function() {
  40951. var runner;
  40952. var currentAnimation = startingAnimator.start();
  40953. currentAnimation.done(function() {
  40954. currentAnimation = null;
  40955. if (!animatorIn) {
  40956. animatorIn = prepareInAnimation();
  40957. if (animatorIn) {
  40958. currentAnimation = animatorIn.start();
  40959. currentAnimation.done(function() {
  40960. currentAnimation = null;
  40961. end();
  40962. runner.complete();
  40963. });
  40964. return currentAnimation;
  40965. }
  40966. }
  40967. // in the event that there is no `in` animation
  40968. end();
  40969. runner.complete();
  40970. });
  40971. runner = new $$AnimateRunner({
  40972. end: endFn,
  40973. cancel: endFn
  40974. });
  40975. return runner;
  40976. function endFn() {
  40977. if (currentAnimation) {
  40978. currentAnimation.end();
  40979. }
  40980. }
  40981. }
  40982. };
  40983. function calculateAnchorStyles(anchor) {
  40984. var styles = {};
  40985. var coords = getDomNode(anchor).getBoundingClientRect();
  40986. // we iterate directly since safari messes up and doesn't return
  40987. // all the keys for the coords object when iterated
  40988. forEach(['width','height','top','left'], function(key) {
  40989. var value = coords[key];
  40990. switch (key) {
  40991. case 'top':
  40992. value += bodyNode.scrollTop;
  40993. break;
  40994. case 'left':
  40995. value += bodyNode.scrollLeft;
  40996. break;
  40997. }
  40998. styles[key] = Math.floor(value) + 'px';
  40999. });
  41000. return styles;
  41001. }
  41002. function prepareOutAnimation() {
  41003. var animator = $animateCss(clone, {
  41004. addClass: NG_OUT_ANCHOR_CLASS_NAME,
  41005. delay: true,
  41006. from: calculateAnchorStyles(outAnchor)
  41007. });
  41008. // read the comment within `prepareRegularAnimation` to understand
  41009. // why this check is necessary
  41010. return animator.$$willAnimate ? animator : null;
  41011. }
  41012. function getClassVal(element) {
  41013. return element.attr('class') || '';
  41014. }
  41015. function prepareInAnimation() {
  41016. var endingClasses = filterCssClasses(getClassVal(inAnchor));
  41017. var toAdd = getUniqueValues(endingClasses, startingClasses);
  41018. var toRemove = getUniqueValues(startingClasses, endingClasses);
  41019. var animator = $animateCss(clone, {
  41020. to: calculateAnchorStyles(inAnchor),
  41021. addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,
  41022. removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,
  41023. delay: true
  41024. });
  41025. // read the comment within `prepareRegularAnimation` to understand
  41026. // why this check is necessary
  41027. return animator.$$willAnimate ? animator : null;
  41028. }
  41029. function end() {
  41030. clone.remove();
  41031. outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  41032. inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);
  41033. }
  41034. }
  41035. function prepareFromToAnchorAnimation(from, to, classes, anchors) {
  41036. var fromAnimation = prepareRegularAnimation(from, noop);
  41037. var toAnimation = prepareRegularAnimation(to, noop);
  41038. var anchorAnimations = [];
  41039. forEach(anchors, function(anchor) {
  41040. var outElement = anchor['out'];
  41041. var inElement = anchor['in'];
  41042. var animator = prepareAnchoredAnimation(classes, outElement, inElement);
  41043. if (animator) {
  41044. anchorAnimations.push(animator);
  41045. }
  41046. });
  41047. // no point in doing anything when there are no elements to animate
  41048. if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;
  41049. return {
  41050. start: function() {
  41051. var animationRunners = [];
  41052. if (fromAnimation) {
  41053. animationRunners.push(fromAnimation.start());
  41054. }
  41055. if (toAnimation) {
  41056. animationRunners.push(toAnimation.start());
  41057. }
  41058. forEach(anchorAnimations, function(animation) {
  41059. animationRunners.push(animation.start());
  41060. });
  41061. var runner = new $$AnimateRunner({
  41062. end: endFn,
  41063. cancel: endFn // CSS-driven animations cannot be cancelled, only ended
  41064. });
  41065. $$AnimateRunner.all(animationRunners, function(status) {
  41066. runner.complete(status);
  41067. });
  41068. return runner;
  41069. function endFn() {
  41070. forEach(animationRunners, function(runner) {
  41071. runner.end();
  41072. });
  41073. }
  41074. }
  41075. };
  41076. }
  41077. function prepareRegularAnimation(animationDetails) {
  41078. var element = animationDetails.element;
  41079. var options = animationDetails.options || {};
  41080. if (animationDetails.structural) {
  41081. options.event = animationDetails.event;
  41082. options.structural = true;
  41083. options.applyClassesEarly = true;
  41084. // we special case the leave animation since we want to ensure that
  41085. // the element is removed as soon as the animation is over. Otherwise
  41086. // a flicker might appear or the element may not be removed at all
  41087. if (animationDetails.event === 'leave') {
  41088. options.onDone = options.domOperation;
  41089. }
  41090. }
  41091. // We assign the preparationClasses as the actual animation event since
  41092. // the internals of $animateCss will just suffix the event token values
  41093. // with `-active` to trigger the animation.
  41094. if (options.preparationClasses) {
  41095. options.event = concatWithSpace(options.event, options.preparationClasses);
  41096. }
  41097. var animator = $animateCss(element, options);
  41098. // the driver lookup code inside of $$animation attempts to spawn a
  41099. // driver one by one until a driver returns a.$$willAnimate animator object.
  41100. // $animateCss will always return an object, however, it will pass in
  41101. // a flag as a hint as to whether an animation was detected or not
  41102. return animator.$$willAnimate ? animator : null;
  41103. }
  41104. }];
  41105. }];
  41106. // TODO(matsko): use caching here to speed things up for detection
  41107. // TODO(matsko): add documentation
  41108. // by the time...
  41109. var $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {
  41110. this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',
  41111. function($injector, $$AnimateRunner, $$jqLite) {
  41112. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41113. // $animateJs(element, 'enter');
  41114. return function(element, event, classes, options) {
  41115. var animationClosed = false;
  41116. // the `classes` argument is optional and if it is not used
  41117. // then the classes will be resolved from the element's className
  41118. // property as well as options.addClass/options.removeClass.
  41119. if (arguments.length === 3 && isObject(classes)) {
  41120. options = classes;
  41121. classes = null;
  41122. }
  41123. options = prepareAnimationOptions(options);
  41124. if (!classes) {
  41125. classes = element.attr('class') || '';
  41126. if (options.addClass) {
  41127. classes += ' ' + options.addClass;
  41128. }
  41129. if (options.removeClass) {
  41130. classes += ' ' + options.removeClass;
  41131. }
  41132. }
  41133. var classesToAdd = options.addClass;
  41134. var classesToRemove = options.removeClass;
  41135. // the lookupAnimations function returns a series of animation objects that are
  41136. // matched up with one or more of the CSS classes. These animation objects are
  41137. // defined via the module.animation factory function. If nothing is detected then
  41138. // we don't return anything which then makes $animation query the next driver.
  41139. var animations = lookupAnimations(classes);
  41140. var before, after;
  41141. if (animations.length) {
  41142. var afterFn, beforeFn;
  41143. if (event == 'leave') {
  41144. beforeFn = 'leave';
  41145. afterFn = 'afterLeave'; // TODO(matsko): get rid of this
  41146. } else {
  41147. beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);
  41148. afterFn = event;
  41149. }
  41150. if (event !== 'enter' && event !== 'move') {
  41151. before = packageAnimations(element, event, options, animations, beforeFn);
  41152. }
  41153. after = packageAnimations(element, event, options, animations, afterFn);
  41154. }
  41155. // no matching animations
  41156. if (!before && !after) return;
  41157. function applyOptions() {
  41158. options.domOperation();
  41159. applyAnimationClasses(element, options);
  41160. }
  41161. function close() {
  41162. animationClosed = true;
  41163. applyOptions();
  41164. applyAnimationStyles(element, options);
  41165. }
  41166. var runner;
  41167. return {
  41168. $$willAnimate: true,
  41169. end: function() {
  41170. if (runner) {
  41171. runner.end();
  41172. } else {
  41173. close();
  41174. runner = new $$AnimateRunner();
  41175. runner.complete(true);
  41176. }
  41177. return runner;
  41178. },
  41179. start: function() {
  41180. if (runner) {
  41181. return runner;
  41182. }
  41183. runner = new $$AnimateRunner();
  41184. var closeActiveAnimations;
  41185. var chain = [];
  41186. if (before) {
  41187. chain.push(function(fn) {
  41188. closeActiveAnimations = before(fn);
  41189. });
  41190. }
  41191. if (chain.length) {
  41192. chain.push(function(fn) {
  41193. applyOptions();
  41194. fn(true);
  41195. });
  41196. } else {
  41197. applyOptions();
  41198. }
  41199. if (after) {
  41200. chain.push(function(fn) {
  41201. closeActiveAnimations = after(fn);
  41202. });
  41203. }
  41204. runner.setHost({
  41205. end: function() {
  41206. endAnimations();
  41207. },
  41208. cancel: function() {
  41209. endAnimations(true);
  41210. }
  41211. });
  41212. $$AnimateRunner.chain(chain, onComplete);
  41213. return runner;
  41214. function onComplete(success) {
  41215. close(success);
  41216. runner.complete(success);
  41217. }
  41218. function endAnimations(cancelled) {
  41219. if (!animationClosed) {
  41220. (closeActiveAnimations || noop)(cancelled);
  41221. onComplete(cancelled);
  41222. }
  41223. }
  41224. }
  41225. };
  41226. function executeAnimationFn(fn, element, event, options, onDone) {
  41227. var args;
  41228. switch (event) {
  41229. case 'animate':
  41230. args = [element, options.from, options.to, onDone];
  41231. break;
  41232. case 'setClass':
  41233. args = [element, classesToAdd, classesToRemove, onDone];
  41234. break;
  41235. case 'addClass':
  41236. args = [element, classesToAdd, onDone];
  41237. break;
  41238. case 'removeClass':
  41239. args = [element, classesToRemove, onDone];
  41240. break;
  41241. default:
  41242. args = [element, onDone];
  41243. break;
  41244. }
  41245. args.push(options);
  41246. var value = fn.apply(fn, args);
  41247. if (value) {
  41248. if (isFunction(value.start)) {
  41249. value = value.start();
  41250. }
  41251. if (value instanceof $$AnimateRunner) {
  41252. value.done(onDone);
  41253. } else if (isFunction(value)) {
  41254. // optional onEnd / onCancel callback
  41255. return value;
  41256. }
  41257. }
  41258. return noop;
  41259. }
  41260. function groupEventedAnimations(element, event, options, animations, fnName) {
  41261. var operations = [];
  41262. forEach(animations, function(ani) {
  41263. var animation = ani[fnName];
  41264. if (!animation) return;
  41265. // note that all of these animations will run in parallel
  41266. operations.push(function() {
  41267. var runner;
  41268. var endProgressCb;
  41269. var resolved = false;
  41270. var onAnimationComplete = function(rejected) {
  41271. if (!resolved) {
  41272. resolved = true;
  41273. (endProgressCb || noop)(rejected);
  41274. runner.complete(!rejected);
  41275. }
  41276. };
  41277. runner = new $$AnimateRunner({
  41278. end: function() {
  41279. onAnimationComplete();
  41280. },
  41281. cancel: function() {
  41282. onAnimationComplete(true);
  41283. }
  41284. });
  41285. endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {
  41286. var cancelled = result === false;
  41287. onAnimationComplete(cancelled);
  41288. });
  41289. return runner;
  41290. });
  41291. });
  41292. return operations;
  41293. }
  41294. function packageAnimations(element, event, options, animations, fnName) {
  41295. var operations = groupEventedAnimations(element, event, options, animations, fnName);
  41296. if (operations.length === 0) {
  41297. var a,b;
  41298. if (fnName === 'beforeSetClass') {
  41299. a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');
  41300. b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');
  41301. } else if (fnName === 'setClass') {
  41302. a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');
  41303. b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');
  41304. }
  41305. if (a) {
  41306. operations = operations.concat(a);
  41307. }
  41308. if (b) {
  41309. operations = operations.concat(b);
  41310. }
  41311. }
  41312. if (operations.length === 0) return;
  41313. // TODO(matsko): add documentation
  41314. return function startAnimation(callback) {
  41315. var runners = [];
  41316. if (operations.length) {
  41317. forEach(operations, function(animateFn) {
  41318. runners.push(animateFn());
  41319. });
  41320. }
  41321. runners.length ? $$AnimateRunner.all(runners, callback) : callback();
  41322. return function endFn(reject) {
  41323. forEach(runners, function(runner) {
  41324. reject ? runner.cancel() : runner.end();
  41325. });
  41326. };
  41327. };
  41328. }
  41329. };
  41330. function lookupAnimations(classes) {
  41331. classes = isArray(classes) ? classes : classes.split(' ');
  41332. var matches = [], flagMap = {};
  41333. for (var i=0; i < classes.length; i++) {
  41334. var klass = classes[i],
  41335. animationFactory = $animateProvider.$$registeredAnimations[klass];
  41336. if (animationFactory && !flagMap[klass]) {
  41337. matches.push($injector.get(animationFactory));
  41338. flagMap[klass] = true;
  41339. }
  41340. }
  41341. return matches;
  41342. }
  41343. }];
  41344. }];
  41345. var $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {
  41346. $$animationProvider.drivers.push('$$animateJsDriver');
  41347. this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {
  41348. return function initDriverFn(animationDetails) {
  41349. if (animationDetails.from && animationDetails.to) {
  41350. var fromAnimation = prepareAnimation(animationDetails.from);
  41351. var toAnimation = prepareAnimation(animationDetails.to);
  41352. if (!fromAnimation && !toAnimation) return;
  41353. return {
  41354. start: function() {
  41355. var animationRunners = [];
  41356. if (fromAnimation) {
  41357. animationRunners.push(fromAnimation.start());
  41358. }
  41359. if (toAnimation) {
  41360. animationRunners.push(toAnimation.start());
  41361. }
  41362. $$AnimateRunner.all(animationRunners, done);
  41363. var runner = new $$AnimateRunner({
  41364. end: endFnFactory(),
  41365. cancel: endFnFactory()
  41366. });
  41367. return runner;
  41368. function endFnFactory() {
  41369. return function() {
  41370. forEach(animationRunners, function(runner) {
  41371. // at this point we cannot cancel animations for groups just yet. 1.5+
  41372. runner.end();
  41373. });
  41374. };
  41375. }
  41376. function done(status) {
  41377. runner.complete(status);
  41378. }
  41379. }
  41380. };
  41381. } else {
  41382. return prepareAnimation(animationDetails);
  41383. }
  41384. };
  41385. function prepareAnimation(animationDetails) {
  41386. // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations
  41387. var element = animationDetails.element;
  41388. var event = animationDetails.event;
  41389. var options = animationDetails.options;
  41390. var classes = animationDetails.classes;
  41391. return $$animateJs(element, event, classes, options);
  41392. }
  41393. }];
  41394. }];
  41395. var NG_ANIMATE_ATTR_NAME = 'data-ng-animate';
  41396. var NG_ANIMATE_PIN_DATA = '$ngAnimatePin';
  41397. var $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {
  41398. var PRE_DIGEST_STATE = 1;
  41399. var RUNNING_STATE = 2;
  41400. var ONE_SPACE = ' ';
  41401. var rules = this.rules = {
  41402. skip: [],
  41403. cancel: [],
  41404. join: []
  41405. };
  41406. function makeTruthyCssClassMap(classString) {
  41407. if (!classString) {
  41408. return null;
  41409. }
  41410. var keys = classString.split(ONE_SPACE);
  41411. var map = Object.create(null);
  41412. forEach(keys, function(key) {
  41413. map[key] = true;
  41414. });
  41415. return map;
  41416. }
  41417. function hasMatchingClasses(newClassString, currentClassString) {
  41418. if (newClassString && currentClassString) {
  41419. var currentClassMap = makeTruthyCssClassMap(currentClassString);
  41420. return newClassString.split(ONE_SPACE).some(function(className) {
  41421. return currentClassMap[className];
  41422. });
  41423. }
  41424. }
  41425. function isAllowed(ruleType, element, currentAnimation, previousAnimation) {
  41426. return rules[ruleType].some(function(fn) {
  41427. return fn(element, currentAnimation, previousAnimation);
  41428. });
  41429. }
  41430. function hasAnimationClasses(animation, and) {
  41431. var a = (animation.addClass || '').length > 0;
  41432. var b = (animation.removeClass || '').length > 0;
  41433. return and ? a && b : a || b;
  41434. }
  41435. rules.join.push(function(element, newAnimation, currentAnimation) {
  41436. // if the new animation is class-based then we can just tack that on
  41437. return !newAnimation.structural && hasAnimationClasses(newAnimation);
  41438. });
  41439. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41440. // there is no need to animate anything if no classes are being added and
  41441. // there is no structural animation that will be triggered
  41442. return !newAnimation.structural && !hasAnimationClasses(newAnimation);
  41443. });
  41444. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41445. // why should we trigger a new structural animation if the element will
  41446. // be removed from the DOM anyway?
  41447. return currentAnimation.event == 'leave' && newAnimation.structural;
  41448. });
  41449. rules.skip.push(function(element, newAnimation, currentAnimation) {
  41450. // if there is an ongoing current animation then don't even bother running the class-based animation
  41451. return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;
  41452. });
  41453. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41454. // there can never be two structural animations running at the same time
  41455. return currentAnimation.structural && newAnimation.structural;
  41456. });
  41457. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41458. // if the previous animation is already running, but the new animation will
  41459. // be triggered, but the new animation is structural
  41460. return currentAnimation.state === RUNNING_STATE && newAnimation.structural;
  41461. });
  41462. rules.cancel.push(function(element, newAnimation, currentAnimation) {
  41463. // cancel the animation if classes added / removed in both animation cancel each other out,
  41464. // but only if the current animation isn't structural
  41465. if (currentAnimation.structural) return false;
  41466. var nA = newAnimation.addClass;
  41467. var nR = newAnimation.removeClass;
  41468. var cA = currentAnimation.addClass;
  41469. var cR = currentAnimation.removeClass;
  41470. // early detection to save the global CPU shortage :)
  41471. if ((isUndefined(nA) && isUndefined(nR)) || (isUndefined(cA) && isUndefined(cR))) {
  41472. return false;
  41473. }
  41474. return hasMatchingClasses(nA, cR) || hasMatchingClasses(nR, cA);
  41475. });
  41476. this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',
  41477. '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',
  41478. function($$rAF, $rootScope, $rootElement, $document, $$HashMap,
  41479. $$animation, $$AnimateRunner, $templateRequest, $$jqLite, $$forceReflow) {
  41480. var activeAnimationsLookup = new $$HashMap();
  41481. var disabledElementsLookup = new $$HashMap();
  41482. var animationsEnabled = null;
  41483. function postDigestTaskFactory() {
  41484. var postDigestCalled = false;
  41485. return function(fn) {
  41486. // we only issue a call to postDigest before
  41487. // it has first passed. This prevents any callbacks
  41488. // from not firing once the animation has completed
  41489. // since it will be out of the digest cycle.
  41490. if (postDigestCalled) {
  41491. fn();
  41492. } else {
  41493. $rootScope.$$postDigest(function() {
  41494. postDigestCalled = true;
  41495. fn();
  41496. });
  41497. }
  41498. };
  41499. }
  41500. // Wait until all directive and route-related templates are downloaded and
  41501. // compiled. The $templateRequest.totalPendingRequests variable keeps track of
  41502. // all of the remote templates being currently downloaded. If there are no
  41503. // templates currently downloading then the watcher will still fire anyway.
  41504. var deregisterWatch = $rootScope.$watch(
  41505. function() { return $templateRequest.totalPendingRequests === 0; },
  41506. function(isEmpty) {
  41507. if (!isEmpty) return;
  41508. deregisterWatch();
  41509. // Now that all templates have been downloaded, $animate will wait until
  41510. // the post digest queue is empty before enabling animations. By having two
  41511. // calls to $postDigest calls we can ensure that the flag is enabled at the
  41512. // very end of the post digest queue. Since all of the animations in $animate
  41513. // use $postDigest, it's important that the code below executes at the end.
  41514. // This basically means that the page is fully downloaded and compiled before
  41515. // any animations are triggered.
  41516. $rootScope.$$postDigest(function() {
  41517. $rootScope.$$postDigest(function() {
  41518. // we check for null directly in the event that the application already called
  41519. // .enabled() with whatever arguments that it provided it with
  41520. if (animationsEnabled === null) {
  41521. animationsEnabled = true;
  41522. }
  41523. });
  41524. });
  41525. }
  41526. );
  41527. var callbackRegistry = {};
  41528. // remember that the classNameFilter is set during the provider/config
  41529. // stage therefore we can optimize here and setup a helper function
  41530. var classNameFilter = $animateProvider.classNameFilter();
  41531. var isAnimatableClassName = !classNameFilter
  41532. ? function() { return true; }
  41533. : function(className) {
  41534. return classNameFilter.test(className);
  41535. };
  41536. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41537. function normalizeAnimationDetails(element, animation) {
  41538. return mergeAnimationDetails(element, animation, {});
  41539. }
  41540. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  41541. var contains = Node.prototype.contains || function(arg) {
  41542. // jshint bitwise: false
  41543. return this === arg || !!(this.compareDocumentPosition(arg) & 16);
  41544. // jshint bitwise: true
  41545. };
  41546. function findCallbacks(parent, element, event) {
  41547. var targetNode = getDomNode(element);
  41548. var targetParentNode = getDomNode(parent);
  41549. var matches = [];
  41550. var entries = callbackRegistry[event];
  41551. if (entries) {
  41552. forEach(entries, function(entry) {
  41553. if (contains.call(entry.node, targetNode)) {
  41554. matches.push(entry.callback);
  41555. } else if (event === 'leave' && contains.call(entry.node, targetParentNode)) {
  41556. matches.push(entry.callback);
  41557. }
  41558. });
  41559. }
  41560. return matches;
  41561. }
  41562. var $animate = {
  41563. on: function(event, container, callback) {
  41564. var node = extractElementNode(container);
  41565. callbackRegistry[event] = callbackRegistry[event] || [];
  41566. callbackRegistry[event].push({
  41567. node: node,
  41568. callback: callback
  41569. });
  41570. // Remove the callback when the element is removed from the DOM
  41571. jqLite(container).on('$destroy', function() {
  41572. $animate.off(event, container, callback);
  41573. });
  41574. },
  41575. off: function(event, container, callback) {
  41576. var entries = callbackRegistry[event];
  41577. if (!entries) return;
  41578. callbackRegistry[event] = arguments.length === 1
  41579. ? null
  41580. : filterFromRegistry(entries, container, callback);
  41581. function filterFromRegistry(list, matchContainer, matchCallback) {
  41582. var containerNode = extractElementNode(matchContainer);
  41583. return list.filter(function(entry) {
  41584. var isMatch = entry.node === containerNode &&
  41585. (!matchCallback || entry.callback === matchCallback);
  41586. return !isMatch;
  41587. });
  41588. }
  41589. },
  41590. pin: function(element, parentElement) {
  41591. assertArg(isElement(element), 'element', 'not an element');
  41592. assertArg(isElement(parentElement), 'parentElement', 'not an element');
  41593. element.data(NG_ANIMATE_PIN_DATA, parentElement);
  41594. },
  41595. push: function(element, event, options, domOperation) {
  41596. options = options || {};
  41597. options.domOperation = domOperation;
  41598. return queueAnimation(element, event, options);
  41599. },
  41600. // this method has four signatures:
  41601. // () - global getter
  41602. // (bool) - global setter
  41603. // (element) - element getter
  41604. // (element, bool) - element setter<F37>
  41605. enabled: function(element, bool) {
  41606. var argCount = arguments.length;
  41607. if (argCount === 0) {
  41608. // () - Global getter
  41609. bool = !!animationsEnabled;
  41610. } else {
  41611. var hasElement = isElement(element);
  41612. if (!hasElement) {
  41613. // (bool) - Global setter
  41614. bool = animationsEnabled = !!element;
  41615. } else {
  41616. var node = getDomNode(element);
  41617. var recordExists = disabledElementsLookup.get(node);
  41618. if (argCount === 1) {
  41619. // (element) - Element getter
  41620. bool = !recordExists;
  41621. } else {
  41622. // (element, bool) - Element setter
  41623. disabledElementsLookup.put(node, !bool);
  41624. }
  41625. }
  41626. }
  41627. return bool;
  41628. }
  41629. };
  41630. return $animate;
  41631. function queueAnimation(element, event, initialOptions) {
  41632. // we always make a copy of the options since
  41633. // there should never be any side effects on
  41634. // the input data when running `$animateCss`.
  41635. var options = copy(initialOptions);
  41636. var node, parent;
  41637. element = stripCommentsFromElement(element);
  41638. if (element) {
  41639. node = getDomNode(element);
  41640. parent = element.parent();
  41641. }
  41642. options = prepareAnimationOptions(options);
  41643. // we create a fake runner with a working promise.
  41644. // These methods will become available after the digest has passed
  41645. var runner = new $$AnimateRunner();
  41646. // this is used to trigger callbacks in postDigest mode
  41647. var runInNextPostDigestOrNow = postDigestTaskFactory();
  41648. if (isArray(options.addClass)) {
  41649. options.addClass = options.addClass.join(' ');
  41650. }
  41651. if (options.addClass && !isString(options.addClass)) {
  41652. options.addClass = null;
  41653. }
  41654. if (isArray(options.removeClass)) {
  41655. options.removeClass = options.removeClass.join(' ');
  41656. }
  41657. if (options.removeClass && !isString(options.removeClass)) {
  41658. options.removeClass = null;
  41659. }
  41660. if (options.from && !isObject(options.from)) {
  41661. options.from = null;
  41662. }
  41663. if (options.to && !isObject(options.to)) {
  41664. options.to = null;
  41665. }
  41666. // there are situations where a directive issues an animation for
  41667. // a jqLite wrapper that contains only comment nodes... If this
  41668. // happens then there is no way we can perform an animation
  41669. if (!node) {
  41670. close();
  41671. return runner;
  41672. }
  41673. var className = [node.className, options.addClass, options.removeClass].join(' ');
  41674. if (!isAnimatableClassName(className)) {
  41675. close();
  41676. return runner;
  41677. }
  41678. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  41679. // this is a hard disable of all animations for the application or on
  41680. // the element itself, therefore there is no need to continue further
  41681. // past this point if not enabled
  41682. // Animations are also disabled if the document is currently hidden (page is not visible
  41683. // to the user), because browsers slow down or do not flush calls to requestAnimationFrame
  41684. var skipAnimations = !animationsEnabled || $document[0].hidden || disabledElementsLookup.get(node);
  41685. var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};
  41686. var hasExistingAnimation = !!existingAnimation.state;
  41687. // there is no point in traversing the same collection of parent ancestors if a followup
  41688. // animation will be run on the same element that already did all that checking work
  41689. if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {
  41690. skipAnimations = !areAnimationsAllowed(element, parent, event);
  41691. }
  41692. if (skipAnimations) {
  41693. close();
  41694. return runner;
  41695. }
  41696. if (isStructural) {
  41697. closeChildAnimations(element);
  41698. }
  41699. var newAnimation = {
  41700. structural: isStructural,
  41701. element: element,
  41702. event: event,
  41703. addClass: options.addClass,
  41704. removeClass: options.removeClass,
  41705. close: close,
  41706. options: options,
  41707. runner: runner
  41708. };
  41709. if (hasExistingAnimation) {
  41710. var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);
  41711. if (skipAnimationFlag) {
  41712. if (existingAnimation.state === RUNNING_STATE) {
  41713. close();
  41714. return runner;
  41715. } else {
  41716. mergeAnimationDetails(element, existingAnimation, newAnimation);
  41717. return existingAnimation.runner;
  41718. }
  41719. }
  41720. var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);
  41721. if (cancelAnimationFlag) {
  41722. if (existingAnimation.state === RUNNING_STATE) {
  41723. // this will end the animation right away and it is safe
  41724. // to do so since the animation is already running and the
  41725. // runner callback code will run in async
  41726. existingAnimation.runner.end();
  41727. } else if (existingAnimation.structural) {
  41728. // this means that the animation is queued into a digest, but
  41729. // hasn't started yet. Therefore it is safe to run the close
  41730. // method which will call the runner methods in async.
  41731. existingAnimation.close();
  41732. } else {
  41733. // this will merge the new animation options into existing animation options
  41734. mergeAnimationDetails(element, existingAnimation, newAnimation);
  41735. return existingAnimation.runner;
  41736. }
  41737. } else {
  41738. // a joined animation means that this animation will take over the existing one
  41739. // so an example would involve a leave animation taking over an enter. Then when
  41740. // the postDigest kicks in the enter will be ignored.
  41741. var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);
  41742. if (joinAnimationFlag) {
  41743. if (existingAnimation.state === RUNNING_STATE) {
  41744. normalizeAnimationDetails(element, newAnimation);
  41745. } else {
  41746. applyGeneratedPreparationClasses(element, isStructural ? event : null, options);
  41747. event = newAnimation.event = existingAnimation.event;
  41748. options = mergeAnimationDetails(element, existingAnimation, newAnimation);
  41749. //we return the same runner since only the option values of this animation will
  41750. //be fed into the `existingAnimation`.
  41751. return existingAnimation.runner;
  41752. }
  41753. }
  41754. }
  41755. } else {
  41756. // normalization in this case means that it removes redundant CSS classes that
  41757. // already exist (addClass) or do not exist (removeClass) on the element
  41758. normalizeAnimationDetails(element, newAnimation);
  41759. }
  41760. // when the options are merged and cleaned up we may end up not having to do
  41761. // an animation at all, therefore we should check this before issuing a post
  41762. // digest callback. Structural animations will always run no matter what.
  41763. var isValidAnimation = newAnimation.structural;
  41764. if (!isValidAnimation) {
  41765. // animate (from/to) can be quickly checked first, otherwise we check if any classes are present
  41766. isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)
  41767. || hasAnimationClasses(newAnimation);
  41768. }
  41769. if (!isValidAnimation) {
  41770. close();
  41771. clearElementAnimationState(element);
  41772. return runner;
  41773. }
  41774. // the counter keeps track of cancelled animations
  41775. var counter = (existingAnimation.counter || 0) + 1;
  41776. newAnimation.counter = counter;
  41777. markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);
  41778. $rootScope.$$postDigest(function() {
  41779. var animationDetails = activeAnimationsLookup.get(node);
  41780. var animationCancelled = !animationDetails;
  41781. animationDetails = animationDetails || {};
  41782. // if addClass/removeClass is called before something like enter then the
  41783. // registered parent element may not be present. The code below will ensure
  41784. // that a final value for parent element is obtained
  41785. var parentElement = element.parent() || [];
  41786. // animate/structural/class-based animations all have requirements. Otherwise there
  41787. // is no point in performing an animation. The parent node must also be set.
  41788. var isValidAnimation = parentElement.length > 0
  41789. && (animationDetails.event === 'animate'
  41790. || animationDetails.structural
  41791. || hasAnimationClasses(animationDetails));
  41792. // this means that the previous animation was cancelled
  41793. // even if the follow-up animation is the same event
  41794. if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {
  41795. // if another animation did not take over then we need
  41796. // to make sure that the domOperation and options are
  41797. // handled accordingly
  41798. if (animationCancelled) {
  41799. applyAnimationClasses(element, options);
  41800. applyAnimationStyles(element, options);
  41801. }
  41802. // if the event changed from something like enter to leave then we do
  41803. // it, otherwise if it's the same then the end result will be the same too
  41804. if (animationCancelled || (isStructural && animationDetails.event !== event)) {
  41805. options.domOperation();
  41806. runner.end();
  41807. }
  41808. // in the event that the element animation was not cancelled or a follow-up animation
  41809. // isn't allowed to animate from here then we need to clear the state of the element
  41810. // so that any future animations won't read the expired animation data.
  41811. if (!isValidAnimation) {
  41812. clearElementAnimationState(element);
  41813. }
  41814. return;
  41815. }
  41816. // this combined multiple class to addClass / removeClass into a setClass event
  41817. // so long as a structural event did not take over the animation
  41818. event = !animationDetails.structural && hasAnimationClasses(animationDetails, true)
  41819. ? 'setClass'
  41820. : animationDetails.event;
  41821. markElementAnimationState(element, RUNNING_STATE);
  41822. var realRunner = $$animation(element, event, animationDetails.options);
  41823. realRunner.done(function(status) {
  41824. close(!status);
  41825. var animationDetails = activeAnimationsLookup.get(node);
  41826. if (animationDetails && animationDetails.counter === counter) {
  41827. clearElementAnimationState(getDomNode(element));
  41828. }
  41829. notifyProgress(runner, event, 'close', {});
  41830. });
  41831. // this will update the runner's flow-control events based on
  41832. // the `realRunner` object.
  41833. runner.setHost(realRunner);
  41834. notifyProgress(runner, event, 'start', {});
  41835. });
  41836. return runner;
  41837. function notifyProgress(runner, event, phase, data) {
  41838. runInNextPostDigestOrNow(function() {
  41839. var callbacks = findCallbacks(parent, element, event);
  41840. if (callbacks.length) {
  41841. // do not optimize this call here to RAF because
  41842. // we don't know how heavy the callback code here will
  41843. // be and if this code is buffered then this can
  41844. // lead to a performance regression.
  41845. $$rAF(function() {
  41846. forEach(callbacks, function(callback) {
  41847. callback(element, phase, data);
  41848. });
  41849. });
  41850. }
  41851. });
  41852. runner.progress(event, phase, data);
  41853. }
  41854. function close(reject) { // jshint ignore:line
  41855. clearGeneratedClasses(element, options);
  41856. applyAnimationClasses(element, options);
  41857. applyAnimationStyles(element, options);
  41858. options.domOperation();
  41859. runner.complete(!reject);
  41860. }
  41861. }
  41862. function closeChildAnimations(element) {
  41863. var node = getDomNode(element);
  41864. var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');
  41865. forEach(children, function(child) {
  41866. var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));
  41867. var animationDetails = activeAnimationsLookup.get(child);
  41868. if (animationDetails) {
  41869. switch (state) {
  41870. case RUNNING_STATE:
  41871. animationDetails.runner.end();
  41872. /* falls through */
  41873. case PRE_DIGEST_STATE:
  41874. activeAnimationsLookup.remove(child);
  41875. break;
  41876. }
  41877. }
  41878. });
  41879. }
  41880. function clearElementAnimationState(element) {
  41881. var node = getDomNode(element);
  41882. node.removeAttribute(NG_ANIMATE_ATTR_NAME);
  41883. activeAnimationsLookup.remove(node);
  41884. }
  41885. function isMatchingElement(nodeOrElmA, nodeOrElmB) {
  41886. return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);
  41887. }
  41888. /**
  41889. * This fn returns false if any of the following is true:
  41890. * a) animations on any parent element are disabled, and animations on the element aren't explicitly allowed
  41891. * b) a parent element has an ongoing structural animation, and animateChildren is false
  41892. * c) the element is not a child of the body
  41893. * d) the element is not a child of the $rootElement
  41894. */
  41895. function areAnimationsAllowed(element, parentElement, event) {
  41896. var bodyElement = jqLite($document[0].body);
  41897. var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';
  41898. var rootElementDetected = isMatchingElement(element, $rootElement);
  41899. var parentAnimationDetected = false;
  41900. var animateChildren;
  41901. var elementDisabled = disabledElementsLookup.get(getDomNode(element));
  41902. var parentHost = jqLite.data(element[0], NG_ANIMATE_PIN_DATA);
  41903. if (parentHost) {
  41904. parentElement = parentHost;
  41905. }
  41906. parentElement = getDomNode(parentElement);
  41907. while (parentElement) {
  41908. if (!rootElementDetected) {
  41909. // angular doesn't want to attempt to animate elements outside of the application
  41910. // therefore we need to ensure that the rootElement is an ancestor of the current element
  41911. rootElementDetected = isMatchingElement(parentElement, $rootElement);
  41912. }
  41913. if (parentElement.nodeType !== ELEMENT_NODE) {
  41914. // no point in inspecting the #document element
  41915. break;
  41916. }
  41917. var details = activeAnimationsLookup.get(parentElement) || {};
  41918. // either an enter, leave or move animation will commence
  41919. // therefore we can't allow any animations to take place
  41920. // but if a parent animation is class-based then that's ok
  41921. if (!parentAnimationDetected) {
  41922. var parentElementDisabled = disabledElementsLookup.get(parentElement);
  41923. if (parentElementDisabled === true && elementDisabled !== false) {
  41924. // disable animations if the user hasn't explicitly enabled animations on the
  41925. // current element
  41926. elementDisabled = true;
  41927. // element is disabled via parent element, no need to check anything else
  41928. break;
  41929. } else if (parentElementDisabled === false) {
  41930. elementDisabled = false;
  41931. }
  41932. parentAnimationDetected = details.structural;
  41933. }
  41934. if (isUndefined(animateChildren) || animateChildren === true) {
  41935. var value = jqLite.data(parentElement, NG_ANIMATE_CHILDREN_DATA);
  41936. if (isDefined(value)) {
  41937. animateChildren = value;
  41938. }
  41939. }
  41940. // there is no need to continue traversing at this point
  41941. if (parentAnimationDetected && animateChildren === false) break;
  41942. if (!bodyElementDetected) {
  41943. // we also need to ensure that the element is or will be a part of the body element
  41944. // otherwise it is pointless to even issue an animation to be rendered
  41945. bodyElementDetected = isMatchingElement(parentElement, bodyElement);
  41946. }
  41947. if (bodyElementDetected && rootElementDetected) {
  41948. // If both body and root have been found, any other checks are pointless,
  41949. // as no animation data should live outside the application
  41950. break;
  41951. }
  41952. if (!rootElementDetected) {
  41953. // If no rootElement is detected, check if the parentElement is pinned to another element
  41954. parentHost = jqLite.data(parentElement, NG_ANIMATE_PIN_DATA);
  41955. if (parentHost) {
  41956. // The pin target element becomes the next parent element
  41957. parentElement = getDomNode(parentHost);
  41958. continue;
  41959. }
  41960. }
  41961. parentElement = parentElement.parentNode;
  41962. }
  41963. var allowAnimation = (!parentAnimationDetected || animateChildren) && elementDisabled !== true;
  41964. return allowAnimation && rootElementDetected && bodyElementDetected;
  41965. }
  41966. function markElementAnimationState(element, state, details) {
  41967. details = details || {};
  41968. details.state = state;
  41969. var node = getDomNode(element);
  41970. node.setAttribute(NG_ANIMATE_ATTR_NAME, state);
  41971. var oldValue = activeAnimationsLookup.get(node);
  41972. var newValue = oldValue
  41973. ? extend(oldValue, details)
  41974. : details;
  41975. activeAnimationsLookup.put(node, newValue);
  41976. }
  41977. }];
  41978. }];
  41979. var $$AnimationProvider = ['$animateProvider', function($animateProvider) {
  41980. var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';
  41981. var drivers = this.drivers = [];
  41982. var RUNNER_STORAGE_KEY = '$$animationRunner';
  41983. function setRunner(element, runner) {
  41984. element.data(RUNNER_STORAGE_KEY, runner);
  41985. }
  41986. function removeRunner(element) {
  41987. element.removeData(RUNNER_STORAGE_KEY);
  41988. }
  41989. function getRunner(element) {
  41990. return element.data(RUNNER_STORAGE_KEY);
  41991. }
  41992. this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',
  41993. function($$jqLite, $rootScope, $injector, $$AnimateRunner, $$HashMap, $$rAFScheduler) {
  41994. var animationQueue = [];
  41995. var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);
  41996. function sortAnimations(animations) {
  41997. var tree = { children: [] };
  41998. var i, lookup = new $$HashMap();
  41999. // this is done first beforehand so that the hashmap
  42000. // is filled with a list of the elements that will be animated
  42001. for (i = 0; i < animations.length; i++) {
  42002. var animation = animations[i];
  42003. lookup.put(animation.domNode, animations[i] = {
  42004. domNode: animation.domNode,
  42005. fn: animation.fn,
  42006. children: []
  42007. });
  42008. }
  42009. for (i = 0; i < animations.length; i++) {
  42010. processNode(animations[i]);
  42011. }
  42012. return flatten(tree);
  42013. function processNode(entry) {
  42014. if (entry.processed) return entry;
  42015. entry.processed = true;
  42016. var elementNode = entry.domNode;
  42017. var parentNode = elementNode.parentNode;
  42018. lookup.put(elementNode, entry);
  42019. var parentEntry;
  42020. while (parentNode) {
  42021. parentEntry = lookup.get(parentNode);
  42022. if (parentEntry) {
  42023. if (!parentEntry.processed) {
  42024. parentEntry = processNode(parentEntry);
  42025. }
  42026. break;
  42027. }
  42028. parentNode = parentNode.parentNode;
  42029. }
  42030. (parentEntry || tree).children.push(entry);
  42031. return entry;
  42032. }
  42033. function flatten(tree) {
  42034. var result = [];
  42035. var queue = [];
  42036. var i;
  42037. for (i = 0; i < tree.children.length; i++) {
  42038. queue.push(tree.children[i]);
  42039. }
  42040. var remainingLevelEntries = queue.length;
  42041. var nextLevelEntries = 0;
  42042. var row = [];
  42043. for (i = 0; i < queue.length; i++) {
  42044. var entry = queue[i];
  42045. if (remainingLevelEntries <= 0) {
  42046. remainingLevelEntries = nextLevelEntries;
  42047. nextLevelEntries = 0;
  42048. result.push(row);
  42049. row = [];
  42050. }
  42051. row.push(entry.fn);
  42052. entry.children.forEach(function(childEntry) {
  42053. nextLevelEntries++;
  42054. queue.push(childEntry);
  42055. });
  42056. remainingLevelEntries--;
  42057. }
  42058. if (row.length) {
  42059. result.push(row);
  42060. }
  42061. return result;
  42062. }
  42063. }
  42064. // TODO(matsko): document the signature in a better way
  42065. return function(element, event, options) {
  42066. options = prepareAnimationOptions(options);
  42067. var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;
  42068. // there is no animation at the current moment, however
  42069. // these runner methods will get later updated with the
  42070. // methods leading into the driver's end/cancel methods
  42071. // for now they just stop the animation from starting
  42072. var runner = new $$AnimateRunner({
  42073. end: function() { close(); },
  42074. cancel: function() { close(true); }
  42075. });
  42076. if (!drivers.length) {
  42077. close();
  42078. return runner;
  42079. }
  42080. setRunner(element, runner);
  42081. var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));
  42082. var tempClasses = options.tempClasses;
  42083. if (tempClasses) {
  42084. classes += ' ' + tempClasses;
  42085. options.tempClasses = null;
  42086. }
  42087. var prepareClassName;
  42088. if (isStructural) {
  42089. prepareClassName = 'ng-' + event + PREPARE_CLASS_SUFFIX;
  42090. $$jqLite.addClass(element, prepareClassName);
  42091. }
  42092. animationQueue.push({
  42093. // this data is used by the postDigest code and passed into
  42094. // the driver step function
  42095. element: element,
  42096. classes: classes,
  42097. event: event,
  42098. structural: isStructural,
  42099. options: options,
  42100. beforeStart: beforeStart,
  42101. close: close
  42102. });
  42103. element.on('$destroy', handleDestroyedElement);
  42104. // we only want there to be one function called within the post digest
  42105. // block. This way we can group animations for all the animations that
  42106. // were apart of the same postDigest flush call.
  42107. if (animationQueue.length > 1) return runner;
  42108. $rootScope.$$postDigest(function() {
  42109. var animations = [];
  42110. forEach(animationQueue, function(entry) {
  42111. // the element was destroyed early on which removed the runner
  42112. // form its storage. This means we can't animate this element
  42113. // at all and it already has been closed due to destruction.
  42114. if (getRunner(entry.element)) {
  42115. animations.push(entry);
  42116. } else {
  42117. entry.close();
  42118. }
  42119. });
  42120. // now any future animations will be in another postDigest
  42121. animationQueue.length = 0;
  42122. var groupedAnimations = groupAnimations(animations);
  42123. var toBeSortedAnimations = [];
  42124. forEach(groupedAnimations, function(animationEntry) {
  42125. toBeSortedAnimations.push({
  42126. domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),
  42127. fn: function triggerAnimationStart() {
  42128. // it's important that we apply the `ng-animate` CSS class and the
  42129. // temporary classes before we do any driver invoking since these
  42130. // CSS classes may be required for proper CSS detection.
  42131. animationEntry.beforeStart();
  42132. var startAnimationFn, closeFn = animationEntry.close;
  42133. // in the event that the element was removed before the digest runs or
  42134. // during the RAF sequencing then we should not trigger the animation.
  42135. var targetElement = animationEntry.anchors
  42136. ? (animationEntry.from.element || animationEntry.to.element)
  42137. : animationEntry.element;
  42138. if (getRunner(targetElement)) {
  42139. var operation = invokeFirstDriver(animationEntry);
  42140. if (operation) {
  42141. startAnimationFn = operation.start;
  42142. }
  42143. }
  42144. if (!startAnimationFn) {
  42145. closeFn();
  42146. } else {
  42147. var animationRunner = startAnimationFn();
  42148. animationRunner.done(function(status) {
  42149. closeFn(!status);
  42150. });
  42151. updateAnimationRunners(animationEntry, animationRunner);
  42152. }
  42153. }
  42154. });
  42155. });
  42156. // we need to sort each of the animations in order of parent to child
  42157. // relationships. This ensures that the child classes are applied at the
  42158. // right time.
  42159. $$rAFScheduler(sortAnimations(toBeSortedAnimations));
  42160. });
  42161. return runner;
  42162. // TODO(matsko): change to reference nodes
  42163. function getAnchorNodes(node) {
  42164. var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';
  42165. var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)
  42166. ? [node]
  42167. : node.querySelectorAll(SELECTOR);
  42168. var anchors = [];
  42169. forEach(items, function(node) {
  42170. var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);
  42171. if (attr && attr.length) {
  42172. anchors.push(node);
  42173. }
  42174. });
  42175. return anchors;
  42176. }
  42177. function groupAnimations(animations) {
  42178. var preparedAnimations = [];
  42179. var refLookup = {};
  42180. forEach(animations, function(animation, index) {
  42181. var element = animation.element;
  42182. var node = getDomNode(element);
  42183. var event = animation.event;
  42184. var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;
  42185. var anchorNodes = animation.structural ? getAnchorNodes(node) : [];
  42186. if (anchorNodes.length) {
  42187. var direction = enterOrMove ? 'to' : 'from';
  42188. forEach(anchorNodes, function(anchor) {
  42189. var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);
  42190. refLookup[key] = refLookup[key] || {};
  42191. refLookup[key][direction] = {
  42192. animationID: index,
  42193. element: jqLite(anchor)
  42194. };
  42195. });
  42196. } else {
  42197. preparedAnimations.push(animation);
  42198. }
  42199. });
  42200. var usedIndicesLookup = {};
  42201. var anchorGroups = {};
  42202. forEach(refLookup, function(operations, key) {
  42203. var from = operations.from;
  42204. var to = operations.to;
  42205. if (!from || !to) {
  42206. // only one of these is set therefore we can't have an
  42207. // anchor animation since all three pieces are required
  42208. var index = from ? from.animationID : to.animationID;
  42209. var indexKey = index.toString();
  42210. if (!usedIndicesLookup[indexKey]) {
  42211. usedIndicesLookup[indexKey] = true;
  42212. preparedAnimations.push(animations[index]);
  42213. }
  42214. return;
  42215. }
  42216. var fromAnimation = animations[from.animationID];
  42217. var toAnimation = animations[to.animationID];
  42218. var lookupKey = from.animationID.toString();
  42219. if (!anchorGroups[lookupKey]) {
  42220. var group = anchorGroups[lookupKey] = {
  42221. structural: true,
  42222. beforeStart: function() {
  42223. fromAnimation.beforeStart();
  42224. toAnimation.beforeStart();
  42225. },
  42226. close: function() {
  42227. fromAnimation.close();
  42228. toAnimation.close();
  42229. },
  42230. classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),
  42231. from: fromAnimation,
  42232. to: toAnimation,
  42233. anchors: [] // TODO(matsko): change to reference nodes
  42234. };
  42235. // the anchor animations require that the from and to elements both have at least
  42236. // one shared CSS class which effectively marries the two elements together to use
  42237. // the same animation driver and to properly sequence the anchor animation.
  42238. if (group.classes.length) {
  42239. preparedAnimations.push(group);
  42240. } else {
  42241. preparedAnimations.push(fromAnimation);
  42242. preparedAnimations.push(toAnimation);
  42243. }
  42244. }
  42245. anchorGroups[lookupKey].anchors.push({
  42246. 'out': from.element, 'in': to.element
  42247. });
  42248. });
  42249. return preparedAnimations;
  42250. }
  42251. function cssClassesIntersection(a,b) {
  42252. a = a.split(' ');
  42253. b = b.split(' ');
  42254. var matches = [];
  42255. for (var i = 0; i < a.length; i++) {
  42256. var aa = a[i];
  42257. if (aa.substring(0,3) === 'ng-') continue;
  42258. for (var j = 0; j < b.length; j++) {
  42259. if (aa === b[j]) {
  42260. matches.push(aa);
  42261. break;
  42262. }
  42263. }
  42264. }
  42265. return matches.join(' ');
  42266. }
  42267. function invokeFirstDriver(animationDetails) {
  42268. // we loop in reverse order since the more general drivers (like CSS and JS)
  42269. // may attempt more elements, but custom drivers are more particular
  42270. for (var i = drivers.length - 1; i >= 0; i--) {
  42271. var driverName = drivers[i];
  42272. if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check
  42273. var factory = $injector.get(driverName);
  42274. var driver = factory(animationDetails);
  42275. if (driver) {
  42276. return driver;
  42277. }
  42278. }
  42279. }
  42280. function beforeStart() {
  42281. element.addClass(NG_ANIMATE_CLASSNAME);
  42282. if (tempClasses) {
  42283. $$jqLite.addClass(element, tempClasses);
  42284. }
  42285. if (prepareClassName) {
  42286. $$jqLite.removeClass(element, prepareClassName);
  42287. prepareClassName = null;
  42288. }
  42289. }
  42290. function updateAnimationRunners(animation, newRunner) {
  42291. if (animation.from && animation.to) {
  42292. update(animation.from.element);
  42293. update(animation.to.element);
  42294. } else {
  42295. update(animation.element);
  42296. }
  42297. function update(element) {
  42298. getRunner(element).setHost(newRunner);
  42299. }
  42300. }
  42301. function handleDestroyedElement() {
  42302. var runner = getRunner(element);
  42303. if (runner && (event !== 'leave' || !options.$$domOperationFired)) {
  42304. runner.end();
  42305. }
  42306. }
  42307. function close(rejected) { // jshint ignore:line
  42308. element.off('$destroy', handleDestroyedElement);
  42309. removeRunner(element);
  42310. applyAnimationClasses(element, options);
  42311. applyAnimationStyles(element, options);
  42312. options.domOperation();
  42313. if (tempClasses) {
  42314. $$jqLite.removeClass(element, tempClasses);
  42315. }
  42316. element.removeClass(NG_ANIMATE_CLASSNAME);
  42317. runner.complete(!rejected);
  42318. }
  42319. };
  42320. }];
  42321. }];
  42322. /**
  42323. * @ngdoc directive
  42324. * @name ngAnimateSwap
  42325. * @restrict A
  42326. * @scope
  42327. *
  42328. * @description
  42329. *
  42330. * ngAnimateSwap is a animation-oriented directive that allows for the container to
  42331. * be removed and entered in whenever the associated expression changes. A
  42332. * common usecase for this directive is a rotating banner or slider component which
  42333. * contains one image being present at a time. When the active image changes
  42334. * then the old image will perform a `leave` animation and the new element
  42335. * will be inserted via an `enter` animation.
  42336. *
  42337. * @animations
  42338. * | Animation | Occurs |
  42339. * |----------------------------------|--------------------------------------|
  42340. * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM |
  42341. * | {@link ng.$animate#leave leave} | when the old element is removed from the DOM |
  42342. *
  42343. * @example
  42344. * <example name="ngAnimateSwap-directive" module="ngAnimateSwapExample"
  42345. * deps="angular-animate.js"
  42346. * animations="true" fixBase="true">
  42347. * <file name="index.html">
  42348. * <div class="container" ng-controller="AppCtrl">
  42349. * <div ng-animate-swap="number" class="cell swap-animation" ng-class="colorClass(number)">
  42350. * {{ number }}
  42351. * </div>
  42352. * </div>
  42353. * </file>
  42354. * <file name="script.js">
  42355. * angular.module('ngAnimateSwapExample', ['ngAnimate'])
  42356. * .controller('AppCtrl', ['$scope', '$interval', function($scope, $interval) {
  42357. * $scope.number = 0;
  42358. * $interval(function() {
  42359. * $scope.number++;
  42360. * }, 1000);
  42361. *
  42362. * var colors = ['red','blue','green','yellow','orange'];
  42363. * $scope.colorClass = function(number) {
  42364. * return colors[number % colors.length];
  42365. * };
  42366. * }]);
  42367. * </file>
  42368. * <file name="animations.css">
  42369. * .container {
  42370. * height:250px;
  42371. * width:250px;
  42372. * position:relative;
  42373. * overflow:hidden;
  42374. * border:2px solid black;
  42375. * }
  42376. * .container .cell {
  42377. * font-size:150px;
  42378. * text-align:center;
  42379. * line-height:250px;
  42380. * position:absolute;
  42381. * top:0;
  42382. * left:0;
  42383. * right:0;
  42384. * border-bottom:2px solid black;
  42385. * }
  42386. * .swap-animation.ng-enter, .swap-animation.ng-leave {
  42387. * transition:0.5s linear all;
  42388. * }
  42389. * .swap-animation.ng-enter {
  42390. * top:-250px;
  42391. * }
  42392. * .swap-animation.ng-enter-active {
  42393. * top:0px;
  42394. * }
  42395. * .swap-animation.ng-leave {
  42396. * top:0px;
  42397. * }
  42398. * .swap-animation.ng-leave-active {
  42399. * top:250px;
  42400. * }
  42401. * .red { background:red; }
  42402. * .green { background:green; }
  42403. * .blue { background:blue; }
  42404. * .yellow { background:yellow; }
  42405. * .orange { background:orange; }
  42406. * </file>
  42407. * </example>
  42408. */
  42409. var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
  42410. return {
  42411. restrict: 'A',
  42412. transclude: 'element',
  42413. terminal: true,
  42414. priority: 600, // we use 600 here to ensure that the directive is caught before others
  42415. link: function(scope, $element, attrs, ctrl, $transclude) {
  42416. var previousElement, previousScope;
  42417. scope.$watchCollection(attrs.ngAnimateSwap || attrs['for'], function(value) {
  42418. if (previousElement) {
  42419. $animate.leave(previousElement);
  42420. }
  42421. if (previousScope) {
  42422. previousScope.$destroy();
  42423. previousScope = null;
  42424. }
  42425. if (value || value === 0) {
  42426. previousScope = scope.$new();
  42427. $transclude(previousScope, function(element) {
  42428. previousElement = element;
  42429. $animate.enter(element, null, $element);
  42430. });
  42431. }
  42432. });
  42433. }
  42434. };
  42435. }];
  42436. /* global angularAnimateModule: true,
  42437. ngAnimateSwapDirective,
  42438. $$AnimateAsyncRunFactory,
  42439. $$rAFSchedulerFactory,
  42440. $$AnimateChildrenDirective,
  42441. $$AnimateQueueProvider,
  42442. $$AnimationProvider,
  42443. $AnimateCssProvider,
  42444. $$AnimateCssDriverProvider,
  42445. $$AnimateJsProvider,
  42446. $$AnimateJsDriverProvider,
  42447. */
  42448. /**
  42449. * @ngdoc module
  42450. * @name ngAnimate
  42451. * @description
  42452. *
  42453. * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via
  42454. * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.
  42455. *
  42456. * <div doc-module-components="ngAnimate"></div>
  42457. *
  42458. * # Usage
  42459. * 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
  42460. * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For
  42461. * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within
  42462. * the HTML element that the animation will be triggered on.
  42463. *
  42464. * ## Directive Support
  42465. * The following directives are "animation aware":
  42466. *
  42467. * | Directive | Supported Animations |
  42468. * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|
  42469. * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move |
  42470. * | {@link ngRoute.directive:ngView#animations ngView} | enter and leave |
  42471. * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave |
  42472. * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave |
  42473. * | {@link ng.directive:ngIf#animations ngIf} | enter and leave |
  42474. * | {@link ng.directive:ngClass#animations ngClass} | add and remove (the CSS class(es) present) |
  42475. * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide} | add and remove (the ng-hide class value) |
  42476. * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
  42477. * | {@link module:ngMessages#animations ngMessages} | add and remove (ng-active & ng-inactive) |
  42478. * | {@link module:ngMessages#animations ngMessage} | enter and leave |
  42479. *
  42480. * (More information can be found by visiting each the documentation associated with each directive.)
  42481. *
  42482. * ## CSS-based Animations
  42483. *
  42484. * 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
  42485. * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.
  42486. *
  42487. * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:
  42488. *
  42489. * ```html
  42490. * <div ng-if="bool" class="fade">
  42491. * Fade me in out
  42492. * </div>
  42493. * <button ng-click="bool=true">Fade In!</button>
  42494. * <button ng-click="bool=false">Fade Out!</button>
  42495. * ```
  42496. *
  42497. * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:
  42498. *
  42499. * ```css
  42500. * /&#42; The starting CSS styles for the enter animation &#42;/
  42501. * .fade.ng-enter {
  42502. * transition:0.5s linear all;
  42503. * opacity:0;
  42504. * }
  42505. *
  42506. * /&#42; The finishing CSS styles for the enter animation &#42;/
  42507. * .fade.ng-enter.ng-enter-active {
  42508. * opacity:1;
  42509. * }
  42510. * ```
  42511. *
  42512. * 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
  42513. * 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
  42514. * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.
  42515. *
  42516. * 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:
  42517. *
  42518. * ```css
  42519. * /&#42; now the element will fade out before it is removed from the DOM &#42;/
  42520. * .fade.ng-leave {
  42521. * transition:0.5s linear all;
  42522. * opacity:1;
  42523. * }
  42524. * .fade.ng-leave.ng-leave-active {
  42525. * opacity:0;
  42526. * }
  42527. * ```
  42528. *
  42529. * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:
  42530. *
  42531. * ```css
  42532. * /&#42; there is no need to define anything inside of the destination
  42533. * CSS class since the keyframe will take charge of the animation &#42;/
  42534. * .fade.ng-leave {
  42535. * animation: my_fade_animation 0.5s linear;
  42536. * -webkit-animation: my_fade_animation 0.5s linear;
  42537. * }
  42538. *
  42539. * @keyframes my_fade_animation {
  42540. * from { opacity:1; }
  42541. * to { opacity:0; }
  42542. * }
  42543. *
  42544. * @-webkit-keyframes my_fade_animation {
  42545. * from { opacity:1; }
  42546. * to { opacity:0; }
  42547. * }
  42548. * ```
  42549. *
  42550. * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.
  42551. *
  42552. * ### CSS Class-based Animations
  42553. *
  42554. * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different
  42555. * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added
  42556. * and removed.
  42557. *
  42558. * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:
  42559. *
  42560. * ```html
  42561. * <div ng-show="bool" class="fade">
  42562. * Show and hide me
  42563. * </div>
  42564. * <button ng-click="bool=true">Toggle</button>
  42565. *
  42566. * <style>
  42567. * .fade.ng-hide {
  42568. * transition:0.5s linear all;
  42569. * opacity:0;
  42570. * }
  42571. * </style>
  42572. * ```
  42573. *
  42574. * 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
  42575. * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.
  42576. *
  42577. * 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
  42578. * with CSS styles.
  42579. *
  42580. * ```html
  42581. * <div ng-class="{on:onOff}" class="highlight">
  42582. * Highlight this box
  42583. * </div>
  42584. * <button ng-click="onOff=!onOff">Toggle</button>
  42585. *
  42586. * <style>
  42587. * .highlight {
  42588. * transition:0.5s linear all;
  42589. * }
  42590. * .highlight.on-add {
  42591. * background:white;
  42592. * }
  42593. * .highlight.on {
  42594. * background:yellow;
  42595. * }
  42596. * .highlight.on-remove {
  42597. * background:black;
  42598. * }
  42599. * </style>
  42600. * ```
  42601. *
  42602. * We can also make use of CSS keyframes by placing them within the CSS classes.
  42603. *
  42604. *
  42605. * ### CSS Staggering Animations
  42606. * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
  42607. * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be
  42608. * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
  42609. * the animation. The style property expected within the stagger class can either be a **transition-delay** or an
  42610. * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
  42611. *
  42612. * ```css
  42613. * .my-animation.ng-enter {
  42614. * /&#42; standard transition code &#42;/
  42615. * transition: 1s linear all;
  42616. * opacity:0;
  42617. * }
  42618. * .my-animation.ng-enter-stagger {
  42619. * /&#42; this will have a 100ms delay between each successive leave animation &#42;/
  42620. * transition-delay: 0.1s;
  42621. *
  42622. * /&#42; As of 1.4.4, this must always be set: it signals ngAnimate
  42623. * to not accidentally inherit a delay property from another CSS class &#42;/
  42624. * transition-duration: 0s;
  42625. * }
  42626. * .my-animation.ng-enter.ng-enter-active {
  42627. * /&#42; standard transition styles &#42;/
  42628. * opacity:1;
  42629. * }
  42630. * ```
  42631. *
  42632. * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
  42633. * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
  42634. * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
  42635. * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.
  42636. *
  42637. * The following code will issue the **ng-leave-stagger** event on the element provided:
  42638. *
  42639. * ```js
  42640. * var kids = parent.children();
  42641. *
  42642. * $animate.leave(kids[0]); //stagger index=0
  42643. * $animate.leave(kids[1]); //stagger index=1
  42644. * $animate.leave(kids[2]); //stagger index=2
  42645. * $animate.leave(kids[3]); //stagger index=3
  42646. * $animate.leave(kids[4]); //stagger index=4
  42647. *
  42648. * window.requestAnimationFrame(function() {
  42649. * //stagger has reset itself
  42650. * $animate.leave(kids[5]); //stagger index=0
  42651. * $animate.leave(kids[6]); //stagger index=1
  42652. *
  42653. * $scope.$digest();
  42654. * });
  42655. * ```
  42656. *
  42657. * Stagger animations are currently only supported within CSS-defined animations.
  42658. *
  42659. * ### The `ng-animate` CSS class
  42660. *
  42661. * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.
  42662. * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).
  42663. *
  42664. * Therefore, animations can be applied to an element using this temporary class directly via CSS.
  42665. *
  42666. * ```css
  42667. * .zipper.ng-animate {
  42668. * transition:0.5s linear all;
  42669. * }
  42670. * .zipper.ng-enter {
  42671. * opacity:0;
  42672. * }
  42673. * .zipper.ng-enter.ng-enter-active {
  42674. * opacity:1;
  42675. * }
  42676. * .zipper.ng-leave {
  42677. * opacity:1;
  42678. * }
  42679. * .zipper.ng-leave.ng-leave-active {
  42680. * opacity:0;
  42681. * }
  42682. * ```
  42683. *
  42684. * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove
  42685. * the CSS class once an animation has completed.)
  42686. *
  42687. *
  42688. * ### The `ng-[event]-prepare` class
  42689. *
  42690. * This is a special class that can be used to prevent unwanted flickering / flash of content before
  42691. * the actual animation starts. The class is added as soon as an animation is initialized, but removed
  42692. * before the actual animation starts (after waiting for a $digest).
  42693. * It is also only added for *structural* animations (`enter`, `move`, and `leave`).
  42694. *
  42695. * In practice, flickering can appear when nesting elements with structural animations such as `ngIf`
  42696. * into elements that have class-based animations such as `ngClass`.
  42697. *
  42698. * ```html
  42699. * <div ng-class="{red: myProp}">
  42700. * <div ng-class="{blue: myProp}">
  42701. * <div class="message" ng-if="myProp"></div>
  42702. * </div>
  42703. * </div>
  42704. * ```
  42705. *
  42706. * It is possible that during the `enter` animation, the `.message` div will be briefly visible before it starts animating.
  42707. * In that case, you can add styles to the CSS that make sure the element stays hidden before the animation starts:
  42708. *
  42709. * ```css
  42710. * .message.ng-enter-prepare {
  42711. * opacity: 0;
  42712. * }
  42713. *
  42714. * ```
  42715. *
  42716. * ## JavaScript-based Animations
  42717. *
  42718. * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared
  42719. * 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
  42720. * `module.animation()` module function we can register the animation.
  42721. *
  42722. * Let's see an example of a enter/leave animation using `ngRepeat`:
  42723. *
  42724. * ```html
  42725. * <div ng-repeat="item in items" class="slide">
  42726. * {{ item }}
  42727. * </div>
  42728. * ```
  42729. *
  42730. * 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`:
  42731. *
  42732. * ```js
  42733. * myModule.animation('.slide', [function() {
  42734. * return {
  42735. * // make note that other events (like addClass/removeClass)
  42736. * // have different function input parameters
  42737. * enter: function(element, doneFn) {
  42738. * jQuery(element).fadeIn(1000, doneFn);
  42739. *
  42740. * // remember to call doneFn so that angular
  42741. * // knows that the animation has concluded
  42742. * },
  42743. *
  42744. * move: function(element, doneFn) {
  42745. * jQuery(element).fadeIn(1000, doneFn);
  42746. * },
  42747. *
  42748. * leave: function(element, doneFn) {
  42749. * jQuery(element).fadeOut(1000, doneFn);
  42750. * }
  42751. * }
  42752. * }]);
  42753. * ```
  42754. *
  42755. * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as
  42756. * greensock.js and velocity.js.
  42757. *
  42758. * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define
  42759. * our animations inside of the same registered animation, however, the function input arguments are a bit different:
  42760. *
  42761. * ```html
  42762. * <div ng-class="color" class="colorful">
  42763. * this box is moody
  42764. * </div>
  42765. * <button ng-click="color='red'">Change to red</button>
  42766. * <button ng-click="color='blue'">Change to blue</button>
  42767. * <button ng-click="color='green'">Change to green</button>
  42768. * ```
  42769. *
  42770. * ```js
  42771. * myModule.animation('.colorful', [function() {
  42772. * return {
  42773. * addClass: function(element, className, doneFn) {
  42774. * // do some cool animation and call the doneFn
  42775. * },
  42776. * removeClass: function(element, className, doneFn) {
  42777. * // do some cool animation and call the doneFn
  42778. * },
  42779. * setClass: function(element, addedClass, removedClass, doneFn) {
  42780. * // do some cool animation and call the doneFn
  42781. * }
  42782. * }
  42783. * }]);
  42784. * ```
  42785. *
  42786. * ## CSS + JS Animations Together
  42787. *
  42788. * 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,
  42789. * 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
  42790. * charge of the animation**:
  42791. *
  42792. * ```html
  42793. * <div ng-if="bool" class="slide">
  42794. * Slide in and out
  42795. * </div>
  42796. * ```
  42797. *
  42798. * ```js
  42799. * myModule.animation('.slide', [function() {
  42800. * return {
  42801. * enter: function(element, doneFn) {
  42802. * jQuery(element).slideIn(1000, doneFn);
  42803. * }
  42804. * }
  42805. * }]);
  42806. * ```
  42807. *
  42808. * ```css
  42809. * .slide.ng-enter {
  42810. * transition:0.5s linear all;
  42811. * transform:translateY(-100px);
  42812. * }
  42813. * .slide.ng-enter.ng-enter-active {
  42814. * transform:translateY(0);
  42815. * }
  42816. * ```
  42817. *
  42818. * 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
  42819. * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from
  42820. * our own JS-based animation code:
  42821. *
  42822. * ```js
  42823. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  42824. * return {
  42825. * enter: function(element) {
  42826. * // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.
  42827. * return $animateCss(element, {
  42828. * event: 'enter',
  42829. * structural: true
  42830. * });
  42831. * }
  42832. * }
  42833. * }]);
  42834. * ```
  42835. *
  42836. * 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.
  42837. *
  42838. * 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
  42839. * 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
  42840. * data into `$animateCss` directly:
  42841. *
  42842. * ```js
  42843. * myModule.animation('.slide', ['$animateCss', function($animateCss) {
  42844. * return {
  42845. * enter: function(element) {
  42846. * return $animateCss(element, {
  42847. * event: 'enter',
  42848. * structural: true,
  42849. * addClass: 'maroon-setting',
  42850. * from: { height:0 },
  42851. * to: { height: 200 }
  42852. * });
  42853. * }
  42854. * }
  42855. * }]);
  42856. * ```
  42857. *
  42858. * Now we can fill in the rest via our transition CSS code:
  42859. *
  42860. * ```css
  42861. * /&#42; the transition tells ngAnimate to make the animation happen &#42;/
  42862. * .slide.ng-enter { transition:0.5s linear all; }
  42863. *
  42864. * /&#42; this extra CSS class will be absorbed into the transition
  42865. * since the $animateCss code is adding the class &#42;/
  42866. * .maroon-setting { background:red; }
  42867. * ```
  42868. *
  42869. * 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.
  42870. *
  42871. * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.
  42872. *
  42873. * ## Animation Anchoring (via `ng-animate-ref`)
  42874. *
  42875. * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between
  42876. * structural areas of an application (like views) by pairing up elements using an attribute
  42877. * called `ng-animate-ref`.
  42878. *
  42879. * Let's say for example we have two views that are managed by `ng-view` and we want to show
  42880. * that there is a relationship between two components situated in within these views. By using the
  42881. * `ng-animate-ref` attribute we can identify that the two components are paired together and we
  42882. * can then attach an animation, which is triggered when the view changes.
  42883. *
  42884. * Say for example we have the following template code:
  42885. *
  42886. * ```html
  42887. * <!-- index.html -->
  42888. * <div ng-view class="view-animation">
  42889. * </div>
  42890. *
  42891. * <!-- home.html -->
  42892. * <a href="#/banner-page">
  42893. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  42894. * </a>
  42895. *
  42896. * <!-- banner-page.html -->
  42897. * <img src="./banner.jpg" class="banner" ng-animate-ref="banner">
  42898. * ```
  42899. *
  42900. * Now, when the view changes (once the link is clicked), ngAnimate will examine the
  42901. * HTML contents to see if there is a match reference between any components in the view
  42902. * that is leaving and the view that is entering. It will scan both the view which is being
  42903. * removed (leave) and inserted (enter) to see if there are any paired DOM elements that
  42904. * contain a matching ref value.
  42905. *
  42906. * The two images match since they share the same ref value. ngAnimate will now create a
  42907. * transport element (which is a clone of the first image element) and it will then attempt
  42908. * to animate to the position of the second image element in the next view. For the animation to
  42909. * work a special CSS class called `ng-anchor` will be added to the transported element.
  42910. *
  42911. * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then
  42912. * ngAnimate will handle the entire transition for us as well as the addition and removal of
  42913. * any changes of CSS classes between the elements:
  42914. *
  42915. * ```css
  42916. * .banner.ng-anchor {
  42917. * /&#42; this animation will last for 1 second since there are
  42918. * two phases to the animation (an `in` and an `out` phase) &#42;/
  42919. * transition:0.5s linear all;
  42920. * }
  42921. * ```
  42922. *
  42923. * We also **must** include animations for the views that are being entered and removed
  42924. * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).
  42925. *
  42926. * ```css
  42927. * .view-animation.ng-enter, .view-animation.ng-leave {
  42928. * transition:0.5s linear all;
  42929. * position:fixed;
  42930. * left:0;
  42931. * top:0;
  42932. * width:100%;
  42933. * }
  42934. * .view-animation.ng-enter {
  42935. * transform:translateX(100%);
  42936. * }
  42937. * .view-animation.ng-leave,
  42938. * .view-animation.ng-enter.ng-enter-active {
  42939. * transform:translateX(0%);
  42940. * }
  42941. * .view-animation.ng-leave.ng-leave-active {
  42942. * transform:translateX(-100%);
  42943. * }
  42944. * ```
  42945. *
  42946. * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:
  42947. * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away
  42948. * from its origin. Once that animation is over then the `in` stage occurs which animates the
  42949. * element to its destination. The reason why there are two animations is to give enough time
  42950. * for the enter animation on the new element to be ready.
  42951. *
  42952. * The example above sets up a transition for both the in and out phases, but we can also target the out or
  42953. * in phases directly via `ng-anchor-out` and `ng-anchor-in`.
  42954. *
  42955. * ```css
  42956. * .banner.ng-anchor-out {
  42957. * transition: 0.5s linear all;
  42958. *
  42959. * /&#42; the scale will be applied during the out animation,
  42960. * but will be animated away when the in animation runs &#42;/
  42961. * transform: scale(1.2);
  42962. * }
  42963. *
  42964. * .banner.ng-anchor-in {
  42965. * transition: 1s linear all;
  42966. * }
  42967. * ```
  42968. *
  42969. *
  42970. *
  42971. *
  42972. * ### Anchoring Demo
  42973. *
  42974. <example module="anchoringExample"
  42975. name="anchoringExample"
  42976. id="anchoringExample"
  42977. deps="angular-animate.js;angular-route.js"
  42978. animations="true">
  42979. <file name="index.html">
  42980. <a href="#/">Home</a>
  42981. <hr />
  42982. <div class="view-container">
  42983. <div ng-view class="view"></div>
  42984. </div>
  42985. </file>
  42986. <file name="script.js">
  42987. angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])
  42988. .config(['$routeProvider', function($routeProvider) {
  42989. $routeProvider.when('/', {
  42990. templateUrl: 'home.html',
  42991. controller: 'HomeController as home'
  42992. });
  42993. $routeProvider.when('/profile/:id', {
  42994. templateUrl: 'profile.html',
  42995. controller: 'ProfileController as profile'
  42996. });
  42997. }])
  42998. .run(['$rootScope', function($rootScope) {
  42999. $rootScope.records = [
  43000. { id:1, title: "Miss Beulah Roob" },
  43001. { id:2, title: "Trent Morissette" },
  43002. { id:3, title: "Miss Ava Pouros" },
  43003. { id:4, title: "Rod Pouros" },
  43004. { id:5, title: "Abdul Rice" },
  43005. { id:6, title: "Laurie Rutherford Sr." },
  43006. { id:7, title: "Nakia McLaughlin" },
  43007. { id:8, title: "Jordon Blanda DVM" },
  43008. { id:9, title: "Rhoda Hand" },
  43009. { id:10, title: "Alexandrea Sauer" }
  43010. ];
  43011. }])
  43012. .controller('HomeController', [function() {
  43013. //empty
  43014. }])
  43015. .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {
  43016. var index = parseInt($routeParams.id, 10);
  43017. var record = $rootScope.records[index - 1];
  43018. this.title = record.title;
  43019. this.id = record.id;
  43020. }]);
  43021. </file>
  43022. <file name="home.html">
  43023. <h2>Welcome to the home page</h1>
  43024. <p>Please click on an element</p>
  43025. <a class="record"
  43026. ng-href="#/profile/{{ record.id }}"
  43027. ng-animate-ref="{{ record.id }}"
  43028. ng-repeat="record in records">
  43029. {{ record.title }}
  43030. </a>
  43031. </file>
  43032. <file name="profile.html">
  43033. <div class="profile record" ng-animate-ref="{{ profile.id }}">
  43034. {{ profile.title }}
  43035. </div>
  43036. </file>
  43037. <file name="animations.css">
  43038. .record {
  43039. display:block;
  43040. font-size:20px;
  43041. }
  43042. .profile {
  43043. background:black;
  43044. color:white;
  43045. font-size:100px;
  43046. }
  43047. .view-container {
  43048. position:relative;
  43049. }
  43050. .view-container > .view.ng-animate {
  43051. position:absolute;
  43052. top:0;
  43053. left:0;
  43054. width:100%;
  43055. min-height:500px;
  43056. }
  43057. .view.ng-enter, .view.ng-leave,
  43058. .record.ng-anchor {
  43059. transition:0.5s linear all;
  43060. }
  43061. .view.ng-enter {
  43062. transform:translateX(100%);
  43063. }
  43064. .view.ng-enter.ng-enter-active, .view.ng-leave {
  43065. transform:translateX(0%);
  43066. }
  43067. .view.ng-leave.ng-leave-active {
  43068. transform:translateX(-100%);
  43069. }
  43070. .record.ng-anchor-out {
  43071. background:red;
  43072. }
  43073. </file>
  43074. </example>
  43075. *
  43076. * ### How is the element transported?
  43077. *
  43078. * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting
  43079. * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element
  43080. * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The
  43081. * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match
  43082. * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied
  43083. * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class
  43084. * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element
  43085. * will become visible since the shim class will be removed.
  43086. *
  43087. * ### How is the morphing handled?
  43088. *
  43089. * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out
  43090. * what CSS classes differ between the starting element and the destination element. These different CSS classes
  43091. * will be added/removed on the anchor element and a transition will be applied (the transition that is provided
  43092. * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will
  43093. * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that
  43094. * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since
  43095. * the cloned element is placed inside of root element which is likely close to the body element).
  43096. *
  43097. * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.
  43098. *
  43099. *
  43100. * ## Using $animate in your directive code
  43101. *
  43102. * 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?
  43103. * 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
  43104. * imagine we have a greeting box that shows and hides itself when the data changes
  43105. *
  43106. * ```html
  43107. * <greeting-box active="onOrOff">Hi there</greeting-box>
  43108. * ```
  43109. *
  43110. * ```js
  43111. * ngModule.directive('greetingBox', ['$animate', function($animate) {
  43112. * return function(scope, element, attrs) {
  43113. * attrs.$observe('active', function(value) {
  43114. * value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');
  43115. * });
  43116. * });
  43117. * }]);
  43118. * ```
  43119. *
  43120. * 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
  43121. * in our HTML code then we can trigger a CSS or JS animation to happen.
  43122. *
  43123. * ```css
  43124. * /&#42; normally we would create a CSS class to reference on the element &#42;/
  43125. * greeting-box.on { transition:0.5s linear all; background:green; color:white; }
  43126. * ```
  43127. *
  43128. * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's
  43129. * possible be sure to visit the {@link ng.$animate $animate service API page}.
  43130. *
  43131. *
  43132. * ## Callbacks and Promises
  43133. *
  43134. * 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
  43135. * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has
  43136. * ended by chaining onto the returned promise that animation method returns.
  43137. *
  43138. * ```js
  43139. * // somewhere within the depths of the directive
  43140. * $animate.enter(element, parent).then(function() {
  43141. * //the animation has completed
  43142. * });
  43143. * ```
  43144. *
  43145. * (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
  43146. * anymore.)
  43147. *
  43148. * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering
  43149. * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view
  43150. * routing controller to hook into that:
  43151. *
  43152. * ```js
  43153. * ngModule.controller('HomePageController', ['$animate', function($animate) {
  43154. * $animate.on('enter', ngViewElement, function(element) {
  43155. * // the animation for this route has completed
  43156. * }]);
  43157. * }])
  43158. * ```
  43159. *
  43160. * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)
  43161. */
  43162. /**
  43163. * @ngdoc service
  43164. * @name $animate
  43165. * @kind object
  43166. *
  43167. * @description
  43168. * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.
  43169. *
  43170. * Click here {@link ng.$animate to learn more about animations with `$animate`}.
  43171. */
  43172. angular.module('ngAnimate', [])
  43173. .directive('ngAnimateSwap', ngAnimateSwapDirective)
  43174. .directive('ngAnimateChildren', $$AnimateChildrenDirective)
  43175. .factory('$$rAFScheduler', $$rAFSchedulerFactory)
  43176. .provider('$$animateQueue', $$AnimateQueueProvider)
  43177. .provider('$$animation', $$AnimationProvider)
  43178. .provider('$animateCss', $AnimateCssProvider)
  43179. .provider('$$animateCssDriver', $$AnimateCssDriverProvider)
  43180. .provider('$$animateJs', $$AnimateJsProvider)
  43181. .provider('$$animateJsDriver', $$AnimateJsDriverProvider);
  43182. })(window, window.angular);
  43183. /*!
  43184. * ionic.bundle.js is a concatenation of:
  43185. * ionic.js, angular.js, angular-animate.js,
  43186. * angular-sanitize.js, angular-ui-router.js,
  43187. * and ionic-angular.js
  43188. */
  43189. /**
  43190. * @license AngularJS v1.5.3
  43191. * (c) 2010-2016 Google, Inc. http://angularjs.org
  43192. * License: MIT
  43193. */
  43194. (function(window, angular, undefined) {'use strict';
  43195. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  43196. * Any commits to this file should be reviewed with security in mind. *
  43197. * Changes to this file can potentially create security vulnerabilities. *
  43198. * An approval from 2 Core members with history of modifying *
  43199. * this file is required. *
  43200. * *
  43201. * Does the change somehow allow for arbitrary javascript to be executed? *
  43202. * Or allows for someone to change the prototype of built-in objects? *
  43203. * Or gives undesired access to variables likes document or window? *
  43204. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  43205. var $sanitizeMinErr = angular.$$minErr('$sanitize');
  43206. /**
  43207. * @ngdoc module
  43208. * @name ngSanitize
  43209. * @description
  43210. *
  43211. * # ngSanitize
  43212. *
  43213. * The `ngSanitize` module provides functionality to sanitize HTML.
  43214. *
  43215. *
  43216. * <div doc-module-components="ngSanitize"></div>
  43217. *
  43218. * See {@link ngSanitize.$sanitize `$sanitize`} for usage.
  43219. */
  43220. /**
  43221. * @ngdoc service
  43222. * @name $sanitize
  43223. * @kind function
  43224. *
  43225. * @description
  43226. * Sanitizes an html string by stripping all potentially dangerous tokens.
  43227. *
  43228. * The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are
  43229. * then serialized back to properly escaped html string. This means that no unsafe input can make
  43230. * it into the returned string.
  43231. *
  43232. * The whitelist for URL sanitization of attribute values is configured using the functions
  43233. * `aHrefSanitizationWhitelist` and `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider
  43234. * `$compileProvider`}.
  43235. *
  43236. * The input may also contain SVG markup if this is enabled via {@link $sanitizeProvider}.
  43237. *
  43238. * @param {string} html HTML input.
  43239. * @returns {string} Sanitized HTML.
  43240. *
  43241. * @example
  43242. <example module="sanitizeExample" deps="angular-sanitize.js">
  43243. <file name="index.html">
  43244. <script>
  43245. angular.module('sanitizeExample', ['ngSanitize'])
  43246. .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  43247. $scope.snippet =
  43248. '<p style="color:blue">an html\n' +
  43249. '<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
  43250. 'snippet</p>';
  43251. $scope.deliberatelyTrustDangerousSnippet = function() {
  43252. return $sce.trustAsHtml($scope.snippet);
  43253. };
  43254. }]);
  43255. </script>
  43256. <div ng-controller="ExampleController">
  43257. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  43258. <table>
  43259. <tr>
  43260. <td>Directive</td>
  43261. <td>How</td>
  43262. <td>Source</td>
  43263. <td>Rendered</td>
  43264. </tr>
  43265. <tr id="bind-html-with-sanitize">
  43266. <td>ng-bind-html</td>
  43267. <td>Automatically uses $sanitize</td>
  43268. <td><pre>&lt;div ng-bind-html="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  43269. <td><div ng-bind-html="snippet"></div></td>
  43270. </tr>
  43271. <tr id="bind-html-with-trust">
  43272. <td>ng-bind-html</td>
  43273. <td>Bypass $sanitize by explicitly trusting the dangerous value</td>
  43274. <td>
  43275. <pre>&lt;div ng-bind-html="deliberatelyTrustDangerousSnippet()"&gt;
  43276. &lt;/div&gt;</pre>
  43277. </td>
  43278. <td><div ng-bind-html="deliberatelyTrustDangerousSnippet()"></div></td>
  43279. </tr>
  43280. <tr id="bind-default">
  43281. <td>ng-bind</td>
  43282. <td>Automatically escapes</td>
  43283. <td><pre>&lt;div ng-bind="snippet"&gt;<br/>&lt;/div&gt;</pre></td>
  43284. <td><div ng-bind="snippet"></div></td>
  43285. </tr>
  43286. </table>
  43287. </div>
  43288. </file>
  43289. <file name="protractor.js" type="protractor">
  43290. it('should sanitize the html snippet by default', function() {
  43291. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  43292. toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
  43293. });
  43294. it('should inline raw snippet if bound to a trusted value', function() {
  43295. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
  43296. toBe("<p style=\"color:blue\">an html\n" +
  43297. "<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
  43298. "snippet</p>");
  43299. });
  43300. it('should escape snippet without any filter', function() {
  43301. expect(element(by.css('#bind-default div')).getInnerHtml()).
  43302. toBe("&lt;p style=\"color:blue\"&gt;an html\n" +
  43303. "&lt;em onmouseover=\"this.textContent='PWN3D!'\"&gt;click here&lt;/em&gt;\n" +
  43304. "snippet&lt;/p&gt;");
  43305. });
  43306. it('should update', function() {
  43307. element(by.model('snippet')).clear();
  43308. element(by.model('snippet')).sendKeys('new <b onclick="alert(1)">text</b>');
  43309. expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
  43310. toBe('new <b>text</b>');
  43311. expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
  43312. 'new <b onclick="alert(1)">text</b>');
  43313. expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
  43314. "new &lt;b onclick=\"alert(1)\"&gt;text&lt;/b&gt;");
  43315. });
  43316. </file>
  43317. </example>
  43318. */
  43319. /**
  43320. * @ngdoc provider
  43321. * @name $sanitizeProvider
  43322. *
  43323. * @description
  43324. * Creates and configures {@link $sanitize} instance.
  43325. */
  43326. function $SanitizeProvider() {
  43327. var svgEnabled = false;
  43328. this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
  43329. if (svgEnabled) {
  43330. angular.extend(validElements, svgElements);
  43331. }
  43332. return function(html) {
  43333. var buf = [];
  43334. htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
  43335. return !/^unsafe:/.test($$sanitizeUri(uri, isImage));
  43336. }));
  43337. return buf.join('');
  43338. };
  43339. }];
  43340. /**
  43341. * @ngdoc method
  43342. * @name $sanitizeProvider#enableSvg
  43343. * @kind function
  43344. *
  43345. * @description
  43346. * Enables a subset of svg to be supported by the sanitizer.
  43347. *
  43348. * <div class="alert alert-warning">
  43349. * <p>By enabling this setting without taking other precautions, you might expose your
  43350. * application to click-hijacking attacks. In these attacks, sanitized svg elements could be positioned
  43351. * outside of the containing element and be rendered over other elements on the page (e.g. a login
  43352. * link). Such behavior can then result in phishing incidents.</p>
  43353. *
  43354. * <p>To protect against these, explicitly setup `overflow: hidden` css rule for all potential svg
  43355. * tags within the sanitized content:</p>
  43356. *
  43357. * <br>
  43358. *
  43359. * <pre><code>
  43360. * .rootOfTheIncludedContent svg {
  43361. * overflow: hidden !important;
  43362. * }
  43363. * </code></pre>
  43364. * </div>
  43365. *
  43366. * @param {boolean=} regexp New regexp to whitelist urls with.
  43367. * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
  43368. * without an argument or self for chaining otherwise.
  43369. */
  43370. this.enableSvg = function(enableSvg) {
  43371. if (angular.isDefined(enableSvg)) {
  43372. svgEnabled = enableSvg;
  43373. return this;
  43374. } else {
  43375. return svgEnabled;
  43376. }
  43377. };
  43378. }
  43379. function sanitizeText(chars) {
  43380. var buf = [];
  43381. var writer = htmlSanitizeWriter(buf, angular.noop);
  43382. writer.chars(chars);
  43383. return buf.join('');
  43384. }
  43385. // Regular Expressions for parsing tags and attributes
  43386. var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  43387. // Match everything outside of normal chars and " (quote character)
  43388. NON_ALPHANUMERIC_REGEXP = /([^\#-~ |!])/g;
  43389. // Good source of info about elements and attributes
  43390. // http://dev.w3.org/html5/spec/Overview.html#semantics
  43391. // http://simon.html5.org/html-elements
  43392. // Safe Void Elements - HTML5
  43393. // http://dev.w3.org/html5/spec/Overview.html#void-elements
  43394. var voidElements = toMap("area,br,col,hr,img,wbr");
  43395. // Elements that you can, intentionally, leave open (and which close themselves)
  43396. // http://dev.w3.org/html5/spec/Overview.html#optional-tags
  43397. var optionalEndTagBlockElements = toMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
  43398. optionalEndTagInlineElements = toMap("rp,rt"),
  43399. optionalEndTagElements = angular.extend({},
  43400. optionalEndTagInlineElements,
  43401. optionalEndTagBlockElements);
  43402. // Safe Block Elements - HTML5
  43403. var blockElements = angular.extend({}, optionalEndTagBlockElements, toMap("address,article," +
  43404. "aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
  43405. "h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul"));
  43406. // Inline Elements - HTML5
  43407. var inlineElements = angular.extend({}, optionalEndTagInlineElements, toMap("a,abbr,acronym,b," +
  43408. "bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
  43409. "samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
  43410. // SVG Elements
  43411. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
  43412. // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
  43413. // They can potentially allow for arbitrary javascript to be executed. See #11290
  43414. var svgElements = toMap("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph," +
  43415. "hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline," +
  43416. "radialGradient,rect,stop,svg,switch,text,title,tspan");
  43417. // Blocked Elements (will be stripped)
  43418. var blockedElements = toMap("script,style");
  43419. var validElements = angular.extend({},
  43420. voidElements,
  43421. blockElements,
  43422. inlineElements,
  43423. optionalEndTagElements);
  43424. //Attributes that have href and hence need to be sanitized
  43425. var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href");
  43426. var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
  43427. 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
  43428. 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
  43429. 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
  43430. 'valign,value,vspace,width');
  43431. // SVG attributes (without "id" and "name" attributes)
  43432. // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
  43433. var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
  43434. 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
  43435. 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
  43436. 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
  43437. 'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +
  43438. 'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +
  43439. 'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +
  43440. 'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +
  43441. 'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +
  43442. 'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +
  43443. 'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +
  43444. 'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +
  43445. 'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +
  43446. 'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +
  43447. 'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);
  43448. var validAttrs = angular.extend({},
  43449. uriAttrs,
  43450. svgAttrs,
  43451. htmlAttrs);
  43452. function toMap(str, lowercaseKeys) {
  43453. var obj = {}, items = str.split(','), i;
  43454. for (i = 0; i < items.length; i++) {
  43455. obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true;
  43456. }
  43457. return obj;
  43458. }
  43459. var inertBodyElement;
  43460. (function(window) {
  43461. var doc;
  43462. if (window.document && window.document.implementation) {
  43463. doc = window.document.implementation.createHTMLDocument("inert");
  43464. } else {
  43465. throw $sanitizeMinErr('noinert', "Can't create an inert html document");
  43466. }
  43467. var docElement = doc.documentElement || doc.getDocumentElement();
  43468. var bodyElements = docElement.getElementsByTagName('body');
  43469. // usually there should be only one body element in the document, but IE doesn't have any, so we need to create one
  43470. if (bodyElements.length === 1) {
  43471. inertBodyElement = bodyElements[0];
  43472. } else {
  43473. var html = doc.createElement('html');
  43474. inertBodyElement = doc.createElement('body');
  43475. html.appendChild(inertBodyElement);
  43476. doc.appendChild(html);
  43477. }
  43478. })(window);
  43479. /**
  43480. * @example
  43481. * htmlParser(htmlString, {
  43482. * start: function(tag, attrs) {},
  43483. * end: function(tag) {},
  43484. * chars: function(text) {},
  43485. * comment: function(text) {}
  43486. * });
  43487. *
  43488. * @param {string} html string
  43489. * @param {object} handler
  43490. */
  43491. function htmlParser(html, handler) {
  43492. if (html === null || html === undefined) {
  43493. html = '';
  43494. } else if (typeof html !== 'string') {
  43495. html = '' + html;
  43496. }
  43497. inertBodyElement.innerHTML = html;
  43498. //mXSS protection
  43499. var mXSSAttempts = 5;
  43500. do {
  43501. if (mXSSAttempts === 0) {
  43502. throw $sanitizeMinErr('uinput', "Failed to sanitize html because the input is unstable");
  43503. }
  43504. mXSSAttempts--;
  43505. // strip custom-namespaced attributes on IE<=11
  43506. if (document.documentMode <= 11) {
  43507. stripCustomNsAttrs(inertBodyElement);
  43508. }
  43509. html = inertBodyElement.innerHTML; //trigger mXSS
  43510. inertBodyElement.innerHTML = html;
  43511. } while (html !== inertBodyElement.innerHTML);
  43512. var node = inertBodyElement.firstChild;
  43513. while (node) {
  43514. switch (node.nodeType) {
  43515. case 1: // ELEMENT_NODE
  43516. handler.start(node.nodeName.toLowerCase(), attrToMap(node.attributes));
  43517. break;
  43518. case 3: // TEXT NODE
  43519. handler.chars(node.textContent);
  43520. break;
  43521. }
  43522. var nextNode;
  43523. if (!(nextNode = node.firstChild)) {
  43524. if (node.nodeType == 1) {
  43525. handler.end(node.nodeName.toLowerCase());
  43526. }
  43527. nextNode = node.nextSibling;
  43528. if (!nextNode) {
  43529. while (nextNode == null) {
  43530. node = node.parentNode;
  43531. if (node === inertBodyElement) break;
  43532. nextNode = node.nextSibling;
  43533. if (node.nodeType == 1) {
  43534. handler.end(node.nodeName.toLowerCase());
  43535. }
  43536. }
  43537. }
  43538. }
  43539. node = nextNode;
  43540. }
  43541. while (node = inertBodyElement.firstChild) {
  43542. inertBodyElement.removeChild(node);
  43543. }
  43544. }
  43545. function attrToMap(attrs) {
  43546. var map = {};
  43547. for (var i = 0, ii = attrs.length; i < ii; i++) {
  43548. var attr = attrs[i];
  43549. map[attr.name] = attr.value;
  43550. }
  43551. return map;
  43552. }
  43553. /**
  43554. * Escapes all potentially dangerous characters, so that the
  43555. * resulting string can be safely inserted into attribute or
  43556. * element text.
  43557. * @param value
  43558. * @returns {string} escaped text
  43559. */
  43560. function encodeEntities(value) {
  43561. return value.
  43562. replace(/&/g, '&amp;').
  43563. replace(SURROGATE_PAIR_REGEXP, function(value) {
  43564. var hi = value.charCodeAt(0);
  43565. var low = value.charCodeAt(1);
  43566. return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
  43567. }).
  43568. replace(NON_ALPHANUMERIC_REGEXP, function(value) {
  43569. return '&#' + value.charCodeAt(0) + ';';
  43570. }).
  43571. replace(/</g, '&lt;').
  43572. replace(/>/g, '&gt;');
  43573. }
  43574. /**
  43575. * create an HTML/XML writer which writes to buffer
  43576. * @param {Array} buf use buf.join('') to get out sanitized html string
  43577. * @returns {object} in the form of {
  43578. * start: function(tag, attrs) {},
  43579. * end: function(tag) {},
  43580. * chars: function(text) {},
  43581. * comment: function(text) {}
  43582. * }
  43583. */
  43584. function htmlSanitizeWriter(buf, uriValidator) {
  43585. var ignoreCurrentElement = false;
  43586. var out = angular.bind(buf, buf.push);
  43587. return {
  43588. start: function(tag, attrs) {
  43589. tag = angular.lowercase(tag);
  43590. if (!ignoreCurrentElement && blockedElements[tag]) {
  43591. ignoreCurrentElement = tag;
  43592. }
  43593. if (!ignoreCurrentElement && validElements[tag] === true) {
  43594. out('<');
  43595. out(tag);
  43596. angular.forEach(attrs, function(value, key) {
  43597. var lkey=angular.lowercase(key);
  43598. var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
  43599. if (validAttrs[lkey] === true &&
  43600. (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
  43601. out(' ');
  43602. out(key);
  43603. out('="');
  43604. out(encodeEntities(value));
  43605. out('"');
  43606. }
  43607. });
  43608. out('>');
  43609. }
  43610. },
  43611. end: function(tag) {
  43612. tag = angular.lowercase(tag);
  43613. if (!ignoreCurrentElement && validElements[tag] === true && voidElements[tag] !== true) {
  43614. out('</');
  43615. out(tag);
  43616. out('>');
  43617. }
  43618. if (tag == ignoreCurrentElement) {
  43619. ignoreCurrentElement = false;
  43620. }
  43621. },
  43622. chars: function(chars) {
  43623. if (!ignoreCurrentElement) {
  43624. out(encodeEntities(chars));
  43625. }
  43626. }
  43627. };
  43628. }
  43629. /**
  43630. * When IE9-11 comes across an unknown namespaced attribute e.g. 'xlink:foo' it adds 'xmlns:ns1' attribute to declare
  43631. * ns1 namespace and prefixes the attribute with 'ns1' (e.g. 'ns1:xlink:foo'). This is undesirable since we don't want
  43632. * to allow any of these custom attributes. This method strips them all.
  43633. *
  43634. * @param node Root element to process
  43635. */
  43636. function stripCustomNsAttrs(node) {
  43637. if (node.nodeType === Node.ELEMENT_NODE) {
  43638. var attrs = node.attributes;
  43639. for (var i = 0, l = attrs.length; i < l; i++) {
  43640. var attrNode = attrs[i];
  43641. var attrName = attrNode.name.toLowerCase();
  43642. if (attrName === 'xmlns:ns1' || attrName.indexOf('ns1:') === 0) {
  43643. node.removeAttributeNode(attrNode);
  43644. i--;
  43645. l--;
  43646. }
  43647. }
  43648. }
  43649. var nextNode = node.firstChild;
  43650. if (nextNode) {
  43651. stripCustomNsAttrs(nextNode);
  43652. }
  43653. nextNode = node.nextSibling;
  43654. if (nextNode) {
  43655. stripCustomNsAttrs(nextNode);
  43656. }
  43657. }
  43658. // define ngSanitize module and register $sanitize service
  43659. angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
  43660. /* global sanitizeText: false */
  43661. /**
  43662. * @ngdoc filter
  43663. * @name linky
  43664. * @kind function
  43665. *
  43666. * @description
  43667. * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
  43668. * plain email address links.
  43669. *
  43670. * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
  43671. *
  43672. * @param {string} text Input text.
  43673. * @param {string} target Window (`_blank|_self|_parent|_top`) or named frame to open links in.
  43674. * @param {object|function(url)} [attributes] Add custom attributes to the link element.
  43675. *
  43676. * Can be one of:
  43677. *
  43678. * - `object`: A map of attributes
  43679. * - `function`: Takes the url as a parameter and returns a map of attributes
  43680. *
  43681. * If the map of attributes contains a value for `target`, it overrides the value of
  43682. * the target parameter.
  43683. *
  43684. *
  43685. * @returns {string} Html-linkified and {@link $sanitize sanitized} text.
  43686. *
  43687. * @usage
  43688. <span ng-bind-html="linky_expression | linky"></span>
  43689. *
  43690. * @example
  43691. <example module="linkyExample" deps="angular-sanitize.js">
  43692. <file name="index.html">
  43693. <div ng-controller="ExampleController">
  43694. Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
  43695. <table>
  43696. <tr>
  43697. <th>Filter</th>
  43698. <th>Source</th>
  43699. <th>Rendered</th>
  43700. </tr>
  43701. <tr id="linky-filter">
  43702. <td>linky filter</td>
  43703. <td>
  43704. <pre>&lt;div ng-bind-html="snippet | linky"&gt;<br>&lt;/div&gt;</pre>
  43705. </td>
  43706. <td>
  43707. <div ng-bind-html="snippet | linky"></div>
  43708. </td>
  43709. </tr>
  43710. <tr id="linky-target">
  43711. <td>linky target</td>
  43712. <td>
  43713. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_blank'"&gt;<br>&lt;/div&gt;</pre>
  43714. </td>
  43715. <td>
  43716. <div ng-bind-html="snippetWithSingleURL | linky:'_blank'"></div>
  43717. </td>
  43718. </tr>
  43719. <tr id="linky-custom-attributes">
  43720. <td>linky custom attributes</td>
  43721. <td>
  43722. <pre>&lt;div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"&gt;<br>&lt;/div&gt;</pre>
  43723. </td>
  43724. <td>
  43725. <div ng-bind-html="snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}"></div>
  43726. </td>
  43727. </tr>
  43728. <tr id="escaped-html">
  43729. <td>no filter</td>
  43730. <td><pre>&lt;div ng-bind="snippet"&gt;<br>&lt;/div&gt;</pre></td>
  43731. <td><div ng-bind="snippet"></div></td>
  43732. </tr>
  43733. </table>
  43734. </file>
  43735. <file name="script.js">
  43736. angular.module('linkyExample', ['ngSanitize'])
  43737. .controller('ExampleController', ['$scope', function($scope) {
  43738. $scope.snippet =
  43739. 'Pretty text with some links:\n'+
  43740. 'http://angularjs.org/,\n'+
  43741. 'mailto:us@somewhere.org,\n'+
  43742. 'another@somewhere.org,\n'+
  43743. 'and one more: ftp://127.0.0.1/.';
  43744. $scope.snippetWithSingleURL = 'http://angularjs.org/';
  43745. }]);
  43746. </file>
  43747. <file name="protractor.js" type="protractor">
  43748. it('should linkify the snippet with urls', function() {
  43749. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  43750. toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +
  43751. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  43752. expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);
  43753. });
  43754. it('should not linkify snippet without the linky filter', function() {
  43755. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).
  43756. toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +
  43757. 'another@somewhere.org, and one more: ftp://127.0.0.1/.');
  43758. expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);
  43759. });
  43760. it('should update', function() {
  43761. element(by.model('snippet')).clear();
  43762. element(by.model('snippet')).sendKeys('new http://link.');
  43763. expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).
  43764. toBe('new http://link.');
  43765. expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);
  43766. expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())
  43767. .toBe('new http://link.');
  43768. });
  43769. it('should work with the target property', function() {
  43770. expect(element(by.id('linky-target')).
  43771. element(by.binding("snippetWithSingleURL | linky:'_blank'")).getText()).
  43772. toBe('http://angularjs.org/');
  43773. expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');
  43774. });
  43775. it('should optionally add custom attributes', function() {
  43776. expect(element(by.id('linky-custom-attributes')).
  43777. element(by.binding("snippetWithSingleURL | linky:'_self':{rel: 'nofollow'}")).getText()).
  43778. toBe('http://angularjs.org/');
  43779. expect(element(by.css('#linky-custom-attributes a')).getAttribute('rel')).toEqual('nofollow');
  43780. });
  43781. </file>
  43782. </example>
  43783. */
  43784. angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
  43785. var LINKY_URL_REGEXP =
  43786. /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
  43787. MAILTO_REGEXP = /^mailto:/i;
  43788. var linkyMinErr = angular.$$minErr('linky');
  43789. var isString = angular.isString;
  43790. return function(text, target, attributes) {
  43791. if (text == null || text === '') return text;
  43792. if (!isString(text)) throw linkyMinErr('notstring', 'Expected string but received: {0}', text);
  43793. var match;
  43794. var raw = text;
  43795. var html = [];
  43796. var url;
  43797. var i;
  43798. while ((match = raw.match(LINKY_URL_REGEXP))) {
  43799. // We can not end in these as they are sometimes found at the end of the sentence
  43800. url = match[0];
  43801. // if we did not match ftp/http/www/mailto then assume mailto
  43802. if (!match[2] && !match[4]) {
  43803. url = (match[3] ? 'http://' : 'mailto:') + url;
  43804. }
  43805. i = match.index;
  43806. addText(raw.substr(0, i));
  43807. addLink(url, match[0].replace(MAILTO_REGEXP, ''));
  43808. raw = raw.substring(i + match[0].length);
  43809. }
  43810. addText(raw);
  43811. return $sanitize(html.join(''));
  43812. function addText(text) {
  43813. if (!text) {
  43814. return;
  43815. }
  43816. html.push(sanitizeText(text));
  43817. }
  43818. function addLink(url, text) {
  43819. var key;
  43820. html.push('<a ');
  43821. if (angular.isFunction(attributes)) {
  43822. attributes = attributes(url);
  43823. }
  43824. if (angular.isObject(attributes)) {
  43825. for (key in attributes) {
  43826. html.push(key + '="' + attributes[key] + '" ');
  43827. }
  43828. } else {
  43829. attributes = {};
  43830. }
  43831. if (angular.isDefined(target) && !('target' in attributes)) {
  43832. html.push('target="',
  43833. target,
  43834. '" ');
  43835. }
  43836. html.push('href="',
  43837. url.replace(/"/g, '&quot;'),
  43838. '">');
  43839. addText(text);
  43840. html.push('</a>');
  43841. }
  43842. };
  43843. }]);
  43844. })(window, window.angular);
  43845. /*!
  43846. * ionic.bundle.js is a concatenation of:
  43847. * ionic.js, angular.js, angular-animate.js,
  43848. * angular-sanitize.js, angular-ui-router.js,
  43849. * and ionic-angular.js
  43850. */
  43851. /**
  43852. * State-based routing for AngularJS
  43853. * @version v0.2.13
  43854. * @link http://angular-ui.github.com/
  43855. * @license MIT License, http://www.opensource.org/licenses/MIT
  43856. */
  43857. /* commonjs package manager support (eg componentjs) */
  43858. if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
  43859. module.exports = 'ui.router';
  43860. }
  43861. (function (window, angular, undefined) {
  43862. /*jshint globalstrict:true*/
  43863. /*global angular:false*/
  43864. 'use strict';
  43865. var isDefined = angular.isDefined,
  43866. isFunction = angular.isFunction,
  43867. isString = angular.isString,
  43868. isObject = angular.isObject,
  43869. isArray = angular.isArray,
  43870. forEach = angular.forEach,
  43871. extend = angular.extend,
  43872. copy = angular.copy;
  43873. function inherit(parent, extra) {
  43874. return extend(new (extend(function() {}, { prototype: parent }))(), extra);
  43875. }
  43876. function merge(dst) {
  43877. forEach(arguments, function(obj) {
  43878. if (obj !== dst) {
  43879. forEach(obj, function(value, key) {
  43880. if (!dst.hasOwnProperty(key)) dst[key] = value;
  43881. });
  43882. }
  43883. });
  43884. return dst;
  43885. }
  43886. /**
  43887. * Finds the common ancestor path between two states.
  43888. *
  43889. * @param {Object} first The first state.
  43890. * @param {Object} second The second state.
  43891. * @return {Array} Returns an array of state names in descending order, not including the root.
  43892. */
  43893. function ancestors(first, second) {
  43894. var path = [];
  43895. for (var n in first.path) {
  43896. if (first.path[n] !== second.path[n]) break;
  43897. path.push(first.path[n]);
  43898. }
  43899. return path;
  43900. }
  43901. /**
  43902. * IE8-safe wrapper for `Object.keys()`.
  43903. *
  43904. * @param {Object} object A JavaScript object.
  43905. * @return {Array} Returns the keys of the object as an array.
  43906. */
  43907. function objectKeys(object) {
  43908. if (Object.keys) {
  43909. return Object.keys(object);
  43910. }
  43911. var result = [];
  43912. angular.forEach(object, function(val, key) {
  43913. result.push(key);
  43914. });
  43915. return result;
  43916. }
  43917. /**
  43918. * IE8-safe wrapper for `Array.prototype.indexOf()`.
  43919. *
  43920. * @param {Array} array A JavaScript array.
  43921. * @param {*} value A value to search the array for.
  43922. * @return {Number} Returns the array index value of `value`, or `-1` if not present.
  43923. */
  43924. function indexOf(array, value) {
  43925. if (Array.prototype.indexOf) {
  43926. return array.indexOf(value, Number(arguments[2]) || 0);
  43927. }
  43928. var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  43929. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  43930. if (from < 0) from += len;
  43931. for (; from < len; from++) {
  43932. if (from in array && array[from] === value) return from;
  43933. }
  43934. return -1;
  43935. }
  43936. /**
  43937. * Merges a set of parameters with all parameters inherited between the common parents of the
  43938. * current state and a given destination state.
  43939. *
  43940. * @param {Object} currentParams The value of the current state parameters ($stateParams).
  43941. * @param {Object} newParams The set of parameters which will be composited with inherited params.
  43942. * @param {Object} $current Internal definition of object representing the current state.
  43943. * @param {Object} $to Internal definition of object representing state to transition to.
  43944. */
  43945. function inheritParams(currentParams, newParams, $current, $to) {
  43946. var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
  43947. for (var i in parents) {
  43948. if (!parents[i].params) continue;
  43949. parentParams = objectKeys(parents[i].params);
  43950. if (!parentParams.length) continue;
  43951. for (var j in parentParams) {
  43952. if (indexOf(inheritList, parentParams[j]) >= 0) continue;
  43953. inheritList.push(parentParams[j]);
  43954. inherited[parentParams[j]] = currentParams[parentParams[j]];
  43955. }
  43956. }
  43957. return extend({}, inherited, newParams);
  43958. }
  43959. /**
  43960. * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
  43961. *
  43962. * @param {Object} a The first object.
  43963. * @param {Object} b The second object.
  43964. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
  43965. * it defaults to the list of keys in `a`.
  43966. * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
  43967. */
  43968. function equalForKeys(a, b, keys) {
  43969. if (!keys) {
  43970. keys = [];
  43971. for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  43972. }
  43973. for (var i=0; i<keys.length; i++) {
  43974. var k = keys[i];
  43975. if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  43976. }
  43977. return true;
  43978. }
  43979. /**
  43980. * Returns the subset of an object, based on a list of keys.
  43981. *
  43982. * @param {Array} keys
  43983. * @param {Object} values
  43984. * @return {Boolean} Returns a subset of `values`.
  43985. */
  43986. function filterByKeys(keys, values) {
  43987. var filtered = {};
  43988. forEach(keys, function (name) {
  43989. filtered[name] = values[name];
  43990. });
  43991. return filtered;
  43992. }
  43993. // like _.indexBy
  43994. // when you know that your index values will be unique, or you want last-one-in to win
  43995. function indexBy(array, propName) {
  43996. var result = {};
  43997. forEach(array, function(item) {
  43998. result[item[propName]] = item;
  43999. });
  44000. return result;
  44001. }
  44002. // extracted from underscore.js
  44003. // Return a copy of the object only containing the whitelisted properties.
  44004. function pick(obj) {
  44005. var copy = {};
  44006. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  44007. forEach(keys, function(key) {
  44008. if (key in obj) copy[key] = obj[key];
  44009. });
  44010. return copy;
  44011. }
  44012. // extracted from underscore.js
  44013. // Return a copy of the object omitting the blacklisted properties.
  44014. function omit(obj) {
  44015. var copy = {};
  44016. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  44017. for (var key in obj) {
  44018. if (indexOf(keys, key) == -1) copy[key] = obj[key];
  44019. }
  44020. return copy;
  44021. }
  44022. function pluck(collection, key) {
  44023. var result = isArray(collection) ? [] : {};
  44024. forEach(collection, function(val, i) {
  44025. result[i] = isFunction(key) ? key(val) : val[key];
  44026. });
  44027. return result;
  44028. }
  44029. function filter(collection, callback) {
  44030. var array = isArray(collection);
  44031. var result = array ? [] : {};
  44032. forEach(collection, function(val, i) {
  44033. if (callback(val, i)) {
  44034. result[array ? result.length : i] = val;
  44035. }
  44036. });
  44037. return result;
  44038. }
  44039. function map(collection, callback) {
  44040. var result = isArray(collection) ? [] : {};
  44041. forEach(collection, function(val, i) {
  44042. result[i] = callback(val, i);
  44043. });
  44044. return result;
  44045. }
  44046. /**
  44047. * @ngdoc overview
  44048. * @name ui.router.util
  44049. *
  44050. * @description
  44051. * # ui.router.util sub-module
  44052. *
  44053. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  44054. * in your angular app (use {@link ui.router} module instead).
  44055. *
  44056. */
  44057. angular.module('ui.router.util', ['ng']);
  44058. /**
  44059. * @ngdoc overview
  44060. * @name ui.router.router
  44061. *
  44062. * @requires ui.router.util
  44063. *
  44064. * @description
  44065. * # ui.router.router sub-module
  44066. *
  44067. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  44068. * in your angular app (use {@link ui.router} module instead).
  44069. */
  44070. angular.module('ui.router.router', ['ui.router.util']);
  44071. /**
  44072. * @ngdoc overview
  44073. * @name ui.router.state
  44074. *
  44075. * @requires ui.router.router
  44076. * @requires ui.router.util
  44077. *
  44078. * @description
  44079. * # ui.router.state sub-module
  44080. *
  44081. * This module is a dependency of the main ui.router module. Do not include this module as a dependency
  44082. * in your angular app (use {@link ui.router} module instead).
  44083. *
  44084. */
  44085. angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
  44086. /**
  44087. * @ngdoc overview
  44088. * @name ui.router
  44089. *
  44090. * @requires ui.router.state
  44091. *
  44092. * @description
  44093. * # ui.router
  44094. *
  44095. * ## The main module for ui.router
  44096. * There are several sub-modules included with the ui.router module, however only this module is needed
  44097. * as a dependency within your angular app. The other modules are for organization purposes.
  44098. *
  44099. * The modules are:
  44100. * * ui.router - the main "umbrella" module
  44101. * * ui.router.router -
  44102. *
  44103. * *You'll need to include **only** this module as the dependency within your angular app.*
  44104. *
  44105. * <pre>
  44106. * <!doctype html>
  44107. * <html ng-app="myApp">
  44108. * <head>
  44109. * <script src="js/angular.js"></script>
  44110. * <!-- Include the ui-router script -->
  44111. * <script src="js/angular-ui-router.min.js"></script>
  44112. * <script>
  44113. * // ...and add 'ui.router' as a dependency
  44114. * var myApp = angular.module('myApp', ['ui.router']);
  44115. * </script>
  44116. * </head>
  44117. * <body>
  44118. * </body>
  44119. * </html>
  44120. * </pre>
  44121. */
  44122. angular.module('ui.router', ['ui.router.state']);
  44123. angular.module('ui.router.compat', ['ui.router']);
  44124. /**
  44125. * @ngdoc object
  44126. * @name ui.router.util.$resolve
  44127. *
  44128. * @requires $q
  44129. * @requires $injector
  44130. *
  44131. * @description
  44132. * Manages resolution of (acyclic) graphs of promises.
  44133. */
  44134. $Resolve.$inject = ['$q', '$injector'];
  44135. function $Resolve( $q, $injector) {
  44136. var VISIT_IN_PROGRESS = 1,
  44137. VISIT_DONE = 2,
  44138. NOTHING = {},
  44139. NO_DEPENDENCIES = [],
  44140. NO_LOCALS = NOTHING,
  44141. NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });
  44142. /**
  44143. * @ngdoc function
  44144. * @name ui.router.util.$resolve#study
  44145. * @methodOf ui.router.util.$resolve
  44146. *
  44147. * @description
  44148. * Studies a set of invocables that are likely to be used multiple times.
  44149. * <pre>
  44150. * $resolve.study(invocables)(locals, parent, self)
  44151. * </pre>
  44152. * is equivalent to
  44153. * <pre>
  44154. * $resolve.resolve(invocables, locals, parent, self)
  44155. * </pre>
  44156. * but the former is more efficient (in fact `resolve` just calls `study`
  44157. * internally).
  44158. *
  44159. * @param {object} invocables Invocable objects
  44160. * @return {function} a function to pass in locals, parent and self
  44161. */
  44162. this.study = function (invocables) {
  44163. if (!isObject(invocables)) throw new Error("'invocables' must be an object");
  44164. var invocableKeys = objectKeys(invocables || {});
  44165. // Perform a topological sort of invocables to build an ordered plan
  44166. var plan = [], cycle = [], visited = {};
  44167. function visit(value, key) {
  44168. if (visited[key] === VISIT_DONE) return;
  44169. cycle.push(key);
  44170. if (visited[key] === VISIT_IN_PROGRESS) {
  44171. cycle.splice(0, indexOf(cycle, key));
  44172. throw new Error("Cyclic dependency: " + cycle.join(" -> "));
  44173. }
  44174. visited[key] = VISIT_IN_PROGRESS;
  44175. if (isString(value)) {
  44176. plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);
  44177. } else {
  44178. var params = $injector.annotate(value);
  44179. forEach(params, function (param) {
  44180. if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
  44181. });
  44182. plan.push(key, value, params);
  44183. }
  44184. cycle.pop();
  44185. visited[key] = VISIT_DONE;
  44186. }
  44187. forEach(invocables, visit);
  44188. invocables = cycle = visited = null; // plan is all that's required
  44189. function isResolve(value) {
  44190. return isObject(value) && value.then && value.$$promises;
  44191. }
  44192. return function (locals, parent, self) {
  44193. if (isResolve(locals) && self === undefined) {
  44194. self = parent; parent = locals; locals = null;
  44195. }
  44196. if (!locals) locals = NO_LOCALS;
  44197. else if (!isObject(locals)) {
  44198. throw new Error("'locals' must be an object");
  44199. }
  44200. if (!parent) parent = NO_PARENT;
  44201. else if (!isResolve(parent)) {
  44202. throw new Error("'parent' must be a promise returned by $resolve.resolve()");
  44203. }
  44204. // To complete the overall resolution, we have to wait for the parent
  44205. // promise and for the promise for each invokable in our plan.
  44206. var resolution = $q.defer(),
  44207. result = resolution.promise,
  44208. promises = result.$$promises = {},
  44209. values = extend({}, locals),
  44210. wait = 1 + plan.length/3,
  44211. merged = false;
  44212. function done() {
  44213. // Merge parent values we haven't got yet and publish our own $$values
  44214. if (!--wait) {
  44215. if (!merged) merge(values, parent.$$values);
  44216. result.$$values = values;
  44217. result.$$promises = result.$$promises || true; // keep for isResolve()
  44218. delete result.$$inheritedValues;
  44219. resolution.resolve(values);
  44220. }
  44221. }
  44222. function fail(reason) {
  44223. result.$$failure = reason;
  44224. resolution.reject(reason);
  44225. }
  44226. // Short-circuit if parent has already failed
  44227. if (isDefined(parent.$$failure)) {
  44228. fail(parent.$$failure);
  44229. return result;
  44230. }
  44231. if (parent.$$inheritedValues) {
  44232. merge(values, omit(parent.$$inheritedValues, invocableKeys));
  44233. }
  44234. // Merge parent values if the parent has already resolved, or merge
  44235. // parent promises and wait if the parent resolve is still in progress.
  44236. extend(promises, parent.$$promises);
  44237. if (parent.$$values) {
  44238. merged = merge(values, omit(parent.$$values, invocableKeys));
  44239. result.$$inheritedValues = omit(parent.$$values, invocableKeys);
  44240. done();
  44241. } else {
  44242. if (parent.$$inheritedValues) {
  44243. result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
  44244. }
  44245. parent.then(done, fail);
  44246. }
  44247. // Process each invocable in the plan, but ignore any where a local of the same name exists.
  44248. for (var i=0, ii=plan.length; i<ii; i+=3) {
  44249. if (locals.hasOwnProperty(plan[i])) done();
  44250. else invoke(plan[i], plan[i+1], plan[i+2]);
  44251. }
  44252. function invoke(key, invocable, params) {
  44253. // Create a deferred for this invocation. Failures will propagate to the resolution as well.
  44254. var invocation = $q.defer(), waitParams = 0;
  44255. function onfailure(reason) {
  44256. invocation.reject(reason);
  44257. fail(reason);
  44258. }
  44259. // Wait for any parameter that we have a promise for (either from parent or from this
  44260. // resolve; in that case study() will have made sure it's ordered before us in the plan).
  44261. forEach(params, function (dep) {
  44262. if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
  44263. waitParams++;
  44264. promises[dep].then(function (result) {
  44265. values[dep] = result;
  44266. if (!(--waitParams)) proceed();
  44267. }, onfailure);
  44268. }
  44269. });
  44270. if (!waitParams) proceed();
  44271. function proceed() {
  44272. if (isDefined(result.$$failure)) return;
  44273. try {
  44274. invocation.resolve($injector.invoke(invocable, self, values));
  44275. invocation.promise.then(function (result) {
  44276. values[key] = result;
  44277. done();
  44278. }, onfailure);
  44279. } catch (e) {
  44280. onfailure(e);
  44281. }
  44282. }
  44283. // Publish promise synchronously; invocations further down in the plan may depend on it.
  44284. promises[key] = invocation.promise;
  44285. }
  44286. return result;
  44287. };
  44288. };
  44289. /**
  44290. * @ngdoc function
  44291. * @name ui.router.util.$resolve#resolve
  44292. * @methodOf ui.router.util.$resolve
  44293. *
  44294. * @description
  44295. * Resolves a set of invocables. An invocable is a function to be invoked via
  44296. * `$injector.invoke()`, and can have an arbitrary number of dependencies.
  44297. * An invocable can either return a value directly,
  44298. * or a `$q` promise. If a promise is returned it will be resolved and the
  44299. * resulting value will be used instead. Dependencies of invocables are resolved
  44300. * (in this order of precedence)
  44301. *
  44302. * - from the specified `locals`
  44303. * - from another invocable that is part of this `$resolve` call
  44304. * - from an invocable that is inherited from a `parent` call to `$resolve`
  44305. * (or recursively
  44306. * - from any ancestor `$resolve` of that parent).
  44307. *
  44308. * The return value of `$resolve` is a promise for an object that contains
  44309. * (in this order of precedence)
  44310. *
  44311. * - any `locals` (if specified)
  44312. * - the resolved return values of all injectables
  44313. * - any values inherited from a `parent` call to `$resolve` (if specified)
  44314. *
  44315. * The promise will resolve after the `parent` promise (if any) and all promises
  44316. * returned by injectables have been resolved. If any invocable
  44317. * (or `$injector.invoke`) throws an exception, or if a promise returned by an
  44318. * invocable is rejected, the `$resolve` promise is immediately rejected with the
  44319. * same error. A rejection of a `parent` promise (if specified) will likewise be
  44320. * propagated immediately. Once the `$resolve` promise has been rejected, no
  44321. * further invocables will be called.
  44322. *
  44323. * Cyclic dependencies between invocables are not permitted and will caues `$resolve`
  44324. * to throw an error. As a special case, an injectable can depend on a parameter
  44325. * with the same name as the injectable, which will be fulfilled from the `parent`
  44326. * injectable of the same name. This allows inherited values to be decorated.
  44327. * Note that in this case any other injectable in the same `$resolve` with the same
  44328. * dependency would see the decorated value, not the inherited value.
  44329. *
  44330. * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
  44331. * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
  44332. * exception.
  44333. *
  44334. * Invocables are invoked eagerly as soon as all dependencies are available.
  44335. * This is true even for dependencies inherited from a `parent` call to `$resolve`.
  44336. *
  44337. * As a special case, an invocable can be a string, in which case it is taken to
  44338. * be a service name to be passed to `$injector.get()`. This is supported primarily
  44339. * for backwards-compatibility with the `resolve` property of `$routeProvider`
  44340. * routes.
  44341. *
  44342. * @param {object} invocables functions to invoke or
  44343. * `$injector` services to fetch.
  44344. * @param {object} locals values to make available to the injectables
  44345. * @param {object} parent a promise returned by another call to `$resolve`.
  44346. * @param {object} self the `this` for the invoked methods
  44347. * @return {object} Promise for an object that contains the resolved return value
  44348. * of all invocables, as well as any inherited and local values.
  44349. */
  44350. this.resolve = function (invocables, locals, parent, self) {
  44351. return this.study(invocables)(locals, parent, self);
  44352. };
  44353. }
  44354. angular.module('ui.router.util').service('$resolve', $Resolve);
  44355. /**
  44356. * @ngdoc object
  44357. * @name ui.router.util.$templateFactory
  44358. *
  44359. * @requires $http
  44360. * @requires $templateCache
  44361. * @requires $injector
  44362. *
  44363. * @description
  44364. * Service. Manages loading of templates.
  44365. */
  44366. $TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];
  44367. function $TemplateFactory( $http, $templateCache, $injector) {
  44368. /**
  44369. * @ngdoc function
  44370. * @name ui.router.util.$templateFactory#fromConfig
  44371. * @methodOf ui.router.util.$templateFactory
  44372. *
  44373. * @description
  44374. * Creates a template from a configuration object.
  44375. *
  44376. * @param {object} config Configuration object for which to load a template.
  44377. * The following properties are search in the specified order, and the first one
  44378. * that is defined is used to create the template:
  44379. *
  44380. * @param {string|object} config.template html string template or function to
  44381. * load via {@link ui.router.util.$templateFactory#fromString fromString}.
  44382. * @param {string|object} config.templateUrl url to load or a function returning
  44383. * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
  44384. * @param {Function} config.templateProvider function to invoke via
  44385. * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
  44386. * @param {object} params Parameters to pass to the template function.
  44387. * @param {object} locals Locals to pass to `invoke` if the template is loaded
  44388. * via a `templateProvider`. Defaults to `{ params: params }`.
  44389. *
  44390. * @return {string|object} The template html as a string, or a promise for
  44391. * that string,or `null` if no template is configured.
  44392. */
  44393. this.fromConfig = function (config, params, locals) {
  44394. return (
  44395. isDefined(config.template) ? this.fromString(config.template, params) :
  44396. isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
  44397. isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
  44398. null
  44399. );
  44400. };
  44401. /**
  44402. * @ngdoc function
  44403. * @name ui.router.util.$templateFactory#fromString
  44404. * @methodOf ui.router.util.$templateFactory
  44405. *
  44406. * @description
  44407. * Creates a template from a string or a function returning a string.
  44408. *
  44409. * @param {string|object} template html template as a string or function that
  44410. * returns an html template as a string.
  44411. * @param {object} params Parameters to pass to the template function.
  44412. *
  44413. * @return {string|object} The template html as a string, or a promise for that
  44414. * string.
  44415. */
  44416. this.fromString = function (template, params) {
  44417. return isFunction(template) ? template(params) : template;
  44418. };
  44419. /**
  44420. * @ngdoc function
  44421. * @name ui.router.util.$templateFactory#fromUrl
  44422. * @methodOf ui.router.util.$templateFactory
  44423. *
  44424. * @description
  44425. * Loads a template from the a URL via `$http` and `$templateCache`.
  44426. *
  44427. * @param {string|Function} url url of the template to load, or a function
  44428. * that returns a url.
  44429. * @param {Object} params Parameters to pass to the url function.
  44430. * @return {string|Promise.<string>} The template html as a string, or a promise
  44431. * for that string.
  44432. */
  44433. this.fromUrl = function (url, params) {
  44434. if (isFunction(url)) url = url(params);
  44435. if (url == null) return null;
  44436. else return $http
  44437. .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})
  44438. .then(function(response) { return response.data; });
  44439. };
  44440. /**
  44441. * @ngdoc function
  44442. * @name ui.router.util.$templateFactory#fromProvider
  44443. * @methodOf ui.router.util.$templateFactory
  44444. *
  44445. * @description
  44446. * Creates a template by invoking an injectable provider function.
  44447. *
  44448. * @param {Function} provider Function to invoke via `$injector.invoke`
  44449. * @param {Object} params Parameters for the template.
  44450. * @param {Object} locals Locals to pass to `invoke`. Defaults to
  44451. * `{ params: params }`.
  44452. * @return {string|Promise.<string>} The template html as a string, or a promise
  44453. * for that string.
  44454. */
  44455. this.fromProvider = function (provider, params, locals) {
  44456. return $injector.invoke(provider, null, locals || { params: params });
  44457. };
  44458. }
  44459. angular.module('ui.router.util').service('$templateFactory', $TemplateFactory);
  44460. var $$UMFP; // reference to $UrlMatcherFactoryProvider
  44461. /**
  44462. * @ngdoc object
  44463. * @name ui.router.util.type:UrlMatcher
  44464. *
  44465. * @description
  44466. * Matches URLs against patterns and extracts named parameters from the path or the search
  44467. * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
  44468. * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
  44469. * do not influence whether or not a URL is matched, but their values are passed through into
  44470. * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
  44471. *
  44472. * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
  44473. * syntax, which optionally allows a regular expression for the parameter to be specified:
  44474. *
  44475. * * `':'` name - colon placeholder
  44476. * * `'*'` name - catch-all placeholder
  44477. * * `'{' name '}'` - curly placeholder
  44478. * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
  44479. * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
  44480. *
  44481. * Parameter names may contain only word characters (latin letters, digits, and underscore) and
  44482. * must be unique within the pattern (across both path and search parameters). For colon
  44483. * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
  44484. * number of characters other than '/'. For catch-all placeholders the path parameter matches
  44485. * any number of characters.
  44486. *
  44487. * Examples:
  44488. *
  44489. * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
  44490. * trailing slashes, and patterns have to match the entire path, not just a prefix.
  44491. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
  44492. * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
  44493. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
  44494. * * `'/user/{id:[^/]*}'` - Same as the previous example.
  44495. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
  44496. * parameter consists of 1 to 8 hex digits.
  44497. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
  44498. * path into the parameter 'path'.
  44499. * * `'/files/*path'` - ditto.
  44500. * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
  44501. * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
  44502. *
  44503. * @param {string} pattern The pattern to compile into a matcher.
  44504. * @param {Object} config A configuration object hash:
  44505. * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
  44506. * an existing UrlMatcher
  44507. *
  44508. * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
  44509. * * `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`.
  44510. *
  44511. * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
  44512. * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
  44513. * non-null) will start with this prefix.
  44514. *
  44515. * @property {string} source The pattern that was passed into the constructor
  44516. *
  44517. * @property {string} sourcePath The path portion of the source property
  44518. *
  44519. * @property {string} sourceSearch The search portion of the source property
  44520. *
  44521. * @property {string} regex The constructed regex that will be used to match against the url when
  44522. * it is time to determine which url will match.
  44523. *
  44524. * @returns {Object} New `UrlMatcher` object
  44525. */
  44526. function UrlMatcher(pattern, config, parentMatcher) {
  44527. config = extend({ params: {} }, isObject(config) ? config : {});
  44528. // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
  44529. // '*' name
  44530. // ':' name
  44531. // '{' name '}'
  44532. // '{' name ':' regexp '}'
  44533. // The regular expression is somewhat complicated due to the need to allow curly braces
  44534. // inside the regular expression. The placeholder regexp breaks down as follows:
  44535. // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
  44536. // \{([\w\[\]]+)(?:\:( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
  44537. // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
  44538. // [^{}\\]+ - anything other than curly braces or backslash
  44539. // \\. - a backslash escape
  44540. // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
  44541. var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  44542. searchPlaceholder = /([:]?)([\w\[\]-]+)|\{([\w\[\]-]+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  44543. compiled = '^', last = 0, m,
  44544. segments = this.segments = [],
  44545. parentParams = parentMatcher ? parentMatcher.params : {},
  44546. params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
  44547. paramNames = [];
  44548. function addParameter(id, type, config, location) {
  44549. paramNames.push(id);
  44550. if (parentParams[id]) return parentParams[id];
  44551. if (!/^\w+(-+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
  44552. if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
  44553. params[id] = new $$UMFP.Param(id, type, config, location);
  44554. return params[id];
  44555. }
  44556. function quoteRegExp(string, pattern, squash) {
  44557. var surroundPattern = ['',''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
  44558. if (!pattern) return result;
  44559. switch(squash) {
  44560. case false: surroundPattern = ['(', ')']; break;
  44561. case true: surroundPattern = ['?(', ')?']; break;
  44562. default: surroundPattern = ['(' + squash + "|", ')?']; break;
  44563. }
  44564. return result + surroundPattern[0] + pattern + surroundPattern[1];
  44565. }
  44566. this.source = pattern;
  44567. // Split into static segments separated by path parameter placeholders.
  44568. // The number of segments is always 1 more than the number of parameters.
  44569. function matchDetails(m, isSearch) {
  44570. var id, regexp, segment, type, cfg, arrayMode;
  44571. id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
  44572. cfg = config.params[id];
  44573. segment = pattern.substring(last, m.index);
  44574. regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
  44575. type = $$UMFP.type(regexp || "string") || inherit($$UMFP.type("string"), { pattern: new RegExp(regexp) });
  44576. return {
  44577. id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
  44578. };
  44579. }
  44580. var p, param, segment;
  44581. while ((m = placeholder.exec(pattern))) {
  44582. p = matchDetails(m, false);
  44583. if (p.segment.indexOf('?') >= 0) break; // we're into the search part
  44584. param = addParameter(p.id, p.type, p.cfg, "path");
  44585. compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);
  44586. segments.push(p.segment);
  44587. last = placeholder.lastIndex;
  44588. }
  44589. segment = pattern.substring(last);
  44590. // Find any search parameter names and remove them from the last segment
  44591. var i = segment.indexOf('?');
  44592. if (i >= 0) {
  44593. var search = this.sourceSearch = segment.substring(i);
  44594. segment = segment.substring(0, i);
  44595. this.sourcePath = pattern.substring(0, last + i);
  44596. if (search.length > 0) {
  44597. last = 0;
  44598. while ((m = searchPlaceholder.exec(search))) {
  44599. p = matchDetails(m, true);
  44600. param = addParameter(p.id, p.type, p.cfg, "search");
  44601. last = placeholder.lastIndex;
  44602. // check if ?&
  44603. }
  44604. }
  44605. } else {
  44606. this.sourcePath = pattern;
  44607. this.sourceSearch = '';
  44608. }
  44609. compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
  44610. segments.push(segment);
  44611. this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
  44612. this.prefix = segments[0];
  44613. this.$$paramNames = paramNames;
  44614. }
  44615. /**
  44616. * @ngdoc function
  44617. * @name ui.router.util.type:UrlMatcher#concat
  44618. * @methodOf ui.router.util.type:UrlMatcher
  44619. *
  44620. * @description
  44621. * Returns a new matcher for a pattern constructed by appending the path part and adding the
  44622. * search parameters of the specified pattern to this pattern. The current pattern is not
  44623. * modified. This can be understood as creating a pattern for URLs that are relative to (or
  44624. * suffixes of) the current pattern.
  44625. *
  44626. * @example
  44627. * The following two matchers are equivalent:
  44628. * <pre>
  44629. * new UrlMatcher('/user/{id}?q').concat('/details?date');
  44630. * new UrlMatcher('/user/{id}/details?q&date');
  44631. * </pre>
  44632. *
  44633. * @param {string} pattern The pattern to append.
  44634. * @param {Object} config An object hash of the configuration for the matcher.
  44635. * @returns {UrlMatcher} A matcher for the concatenated pattern.
  44636. */
  44637. UrlMatcher.prototype.concat = function (pattern, config) {
  44638. // Because order of search parameters is irrelevant, we can add our own search
  44639. // parameters to the end of the new pattern. Parse the new pattern by itself
  44640. // and then join the bits together, but it's much easier to do this on a string level.
  44641. var defaultConfig = {
  44642. caseInsensitive: $$UMFP.caseInsensitive(),
  44643. strict: $$UMFP.strictMode(),
  44644. squash: $$UMFP.defaultSquashPolicy()
  44645. };
  44646. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
  44647. };
  44648. UrlMatcher.prototype.toString = function () {
  44649. return this.source;
  44650. };
  44651. /**
  44652. * @ngdoc function
  44653. * @name ui.router.util.type:UrlMatcher#exec
  44654. * @methodOf ui.router.util.type:UrlMatcher
  44655. *
  44656. * @description
  44657. * Tests the specified path against this matcher, and returns an object containing the captured
  44658. * parameter values, or null if the path does not match. The returned object contains the values
  44659. * of any search parameters that are mentioned in the pattern, but their value may be null if
  44660. * they are not present in `searchParams`. This means that search parameters are always treated
  44661. * as optional.
  44662. *
  44663. * @example
  44664. * <pre>
  44665. * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
  44666. * x: '1', q: 'hello'
  44667. * });
  44668. * // returns { id: 'bob', q: 'hello', r: null }
  44669. * </pre>
  44670. *
  44671. * @param {string} path The URL path to match, e.g. `$location.path()`.
  44672. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
  44673. * @returns {Object} The captured parameter values.
  44674. */
  44675. UrlMatcher.prototype.exec = function (path, searchParams) {
  44676. var m = this.regexp.exec(path);
  44677. if (!m) return null;
  44678. searchParams = searchParams || {};
  44679. var paramNames = this.parameters(), nTotal = paramNames.length,
  44680. nPath = this.segments.length - 1,
  44681. values = {}, i, j, cfg, paramName;
  44682. if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
  44683. function decodePathArray(string) {
  44684. function reverseString(str) { return str.split("").reverse().join(""); }
  44685. function unquoteDashes(str) { return str.replace(/\\-/, "-"); }
  44686. var split = reverseString(string).split(/-(?!\\)/);
  44687. var allReversed = map(split, reverseString);
  44688. return map(allReversed, unquoteDashes).reverse();
  44689. }
  44690. for (i = 0; i < nPath; i++) {
  44691. paramName = paramNames[i];
  44692. var param = this.params[paramName];
  44693. var paramVal = m[i+1];
  44694. // if the param value matches a pre-replace pair, replace the value before decoding.
  44695. for (j = 0; j < param.replace; j++) {
  44696. if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
  44697. }
  44698. if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
  44699. values[paramName] = param.value(paramVal);
  44700. }
  44701. for (/**/; i < nTotal; i++) {
  44702. paramName = paramNames[i];
  44703. values[paramName] = this.params[paramName].value(searchParams[paramName]);
  44704. }
  44705. return values;
  44706. };
  44707. /**
  44708. * @ngdoc function
  44709. * @name ui.router.util.type:UrlMatcher#parameters
  44710. * @methodOf ui.router.util.type:UrlMatcher
  44711. *
  44712. * @description
  44713. * Returns the names of all path and search parameters of this pattern in an unspecified order.
  44714. *
  44715. * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
  44716. * pattern has no parameters, an empty array is returned.
  44717. */
  44718. UrlMatcher.prototype.parameters = function (param) {
  44719. if (!isDefined(param)) return this.$$paramNames;
  44720. return this.params[param] || null;
  44721. };
  44722. /**
  44723. * @ngdoc function
  44724. * @name ui.router.util.type:UrlMatcher#validate
  44725. * @methodOf ui.router.util.type:UrlMatcher
  44726. *
  44727. * @description
  44728. * Checks an object hash of parameters to validate their correctness according to the parameter
  44729. * types of this `UrlMatcher`.
  44730. *
  44731. * @param {Object} params The object hash of parameters to validate.
  44732. * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
  44733. */
  44734. UrlMatcher.prototype.validates = function (params) {
  44735. return this.params.$$validates(params);
  44736. };
  44737. /**
  44738. * @ngdoc function
  44739. * @name ui.router.util.type:UrlMatcher#format
  44740. * @methodOf ui.router.util.type:UrlMatcher
  44741. *
  44742. * @description
  44743. * Creates a URL that matches this pattern by substituting the specified values
  44744. * for the path and search parameters. Null values for path parameters are
  44745. * treated as empty strings.
  44746. *
  44747. * @example
  44748. * <pre>
  44749. * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
  44750. * // returns '/user/bob?q=yes'
  44751. * </pre>
  44752. *
  44753. * @param {Object} values the values to substitute for the parameters in this pattern.
  44754. * @returns {string} the formatted URL (path and optionally search part).
  44755. */
  44756. UrlMatcher.prototype.format = function (values) {
  44757. values = values || {};
  44758. var segments = this.segments, params = this.parameters(), paramset = this.params;
  44759. if (!this.validates(values)) return null;
  44760. var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
  44761. function encodeDashes(str) { // Replace dashes with encoded "\-"
  44762. return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });
  44763. }
  44764. for (i = 0; i < nTotal; i++) {
  44765. var isPathParam = i < nPath;
  44766. var name = params[i], param = paramset[name], value = param.value(values[name]);
  44767. var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
  44768. var squash = isDefaultValue ? param.squash : false;
  44769. var encoded = param.type.encode(value);
  44770. if (isPathParam) {
  44771. var nextSegment = segments[i + 1];
  44772. if (squash === false) {
  44773. if (encoded != null) {
  44774. if (isArray(encoded)) {
  44775. result += map(encoded, encodeDashes).join("-");
  44776. } else {
  44777. result += encodeURIComponent(encoded);
  44778. }
  44779. }
  44780. result += nextSegment;
  44781. } else if (squash === true) {
  44782. var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
  44783. result += nextSegment.match(capture)[1];
  44784. } else if (isString(squash)) {
  44785. result += squash + nextSegment;
  44786. }
  44787. } else {
  44788. if (encoded == null || (isDefaultValue && squash !== false)) continue;
  44789. if (!isArray(encoded)) encoded = [ encoded ];
  44790. encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
  44791. result += (search ? '&' : '?') + (name + '=' + encoded);
  44792. search = true;
  44793. }
  44794. }
  44795. return result;
  44796. };
  44797. /**
  44798. * @ngdoc object
  44799. * @name ui.router.util.type:Type
  44800. *
  44801. * @description
  44802. * Implements an interface to define custom parameter types that can be decoded from and encoded to
  44803. * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
  44804. * objects when matching or formatting URLs, or comparing or validating parameter values.
  44805. *
  44806. * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
  44807. * information on registering custom types.
  44808. *
  44809. * @param {Object} config A configuration object which contains the custom type definition. The object's
  44810. * properties will override the default methods and/or pattern in `Type`'s public interface.
  44811. * @example
  44812. * <pre>
  44813. * {
  44814. * decode: function(val) { return parseInt(val, 10); },
  44815. * encode: function(val) { return val && val.toString(); },
  44816. * equals: function(a, b) { return this.is(a) && a === b; },
  44817. * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
  44818. * pattern: /\d+/
  44819. * }
  44820. * </pre>
  44821. *
  44822. * @property {RegExp} pattern The regular expression pattern used to match values of this type when
  44823. * coming from a substring of a URL.
  44824. *
  44825. * @returns {Object} Returns a new `Type` object.
  44826. */
  44827. function Type(config) {
  44828. extend(this, config);
  44829. }
  44830. /**
  44831. * @ngdoc function
  44832. * @name ui.router.util.type:Type#is
  44833. * @methodOf ui.router.util.type:Type
  44834. *
  44835. * @description
  44836. * Detects whether a value is of a particular type. Accepts a native (decoded) value
  44837. * and determines whether it matches the current `Type` object.
  44838. *
  44839. * @param {*} val The value to check.
  44840. * @param {string} key Optional. If the type check is happening in the context of a specific
  44841. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
  44842. * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
  44843. * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
  44844. */
  44845. Type.prototype.is = function(val, key) {
  44846. return true;
  44847. };
  44848. /**
  44849. * @ngdoc function
  44850. * @name ui.router.util.type:Type#encode
  44851. * @methodOf ui.router.util.type:Type
  44852. *
  44853. * @description
  44854. * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
  44855. * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
  44856. * only needs to be a representation of `val` that has been coerced to a string.
  44857. *
  44858. * @param {*} val The value to encode.
  44859. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  44860. * meta-programming of `Type` objects.
  44861. * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
  44862. */
  44863. Type.prototype.encode = function(val, key) {
  44864. return val;
  44865. };
  44866. /**
  44867. * @ngdoc function
  44868. * @name ui.router.util.type:Type#decode
  44869. * @methodOf ui.router.util.type:Type
  44870. *
  44871. * @description
  44872. * Converts a parameter value (from URL string or transition param) to a custom/native value.
  44873. *
  44874. * @param {string} val The URL parameter value to decode.
  44875. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  44876. * meta-programming of `Type` objects.
  44877. * @returns {*} Returns a custom representation of the URL parameter value.
  44878. */
  44879. Type.prototype.decode = function(val, key) {
  44880. return val;
  44881. };
  44882. /**
  44883. * @ngdoc function
  44884. * @name ui.router.util.type:Type#equals
  44885. * @methodOf ui.router.util.type:Type
  44886. *
  44887. * @description
  44888. * Determines whether two decoded values are equivalent.
  44889. *
  44890. * @param {*} a A value to compare against.
  44891. * @param {*} b A value to compare against.
  44892. * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
  44893. */
  44894. Type.prototype.equals = function(a, b) {
  44895. return a == b;
  44896. };
  44897. Type.prototype.$subPattern = function() {
  44898. var sub = this.pattern.toString();
  44899. return sub.substr(1, sub.length - 2);
  44900. };
  44901. Type.prototype.pattern = /.*/;
  44902. Type.prototype.toString = function() { return "{Type:" + this.name + "}"; };
  44903. /*
  44904. * Wraps an existing custom Type as an array of Type, depending on 'mode'.
  44905. * e.g.:
  44906. * - urlmatcher pattern "/path?{queryParam[]:int}"
  44907. * - url: "/path?queryParam=1&queryParam=2
  44908. * - $stateParams.queryParam will be [1, 2]
  44909. * if `mode` is "auto", then
  44910. * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
  44911. * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
  44912. */
  44913. Type.prototype.$asArray = function(mode, isSearch) {
  44914. if (!mode) return this;
  44915. if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
  44916. return new ArrayType(this, mode);
  44917. function ArrayType(type, mode) {
  44918. function bindTo(type, callbackName) {
  44919. return function() {
  44920. return type[callbackName].apply(type, arguments);
  44921. };
  44922. }
  44923. // Wrap non-array value as array
  44924. function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }
  44925. // Unwrap array value for "auto" mode. Return undefined for empty array.
  44926. function arrayUnwrap(val) {
  44927. switch(val.length) {
  44928. case 0: return undefined;
  44929. case 1: return mode === "auto" ? val[0] : val;
  44930. default: return val;
  44931. }
  44932. }
  44933. function falsey(val) { return !val; }
  44934. // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
  44935. function arrayHandler(callback, allTruthyMode) {
  44936. return function handleArray(val) {
  44937. val = arrayWrap(val);
  44938. var result = map(val, callback);
  44939. if (allTruthyMode === true)
  44940. return filter(result, falsey).length === 0;
  44941. return arrayUnwrap(result);
  44942. };
  44943. }
  44944. // Wraps type (.equals) functions to operate on each value of an array
  44945. function arrayEqualsHandler(callback) {
  44946. return function handleArray(val1, val2) {
  44947. var left = arrayWrap(val1), right = arrayWrap(val2);
  44948. if (left.length !== right.length) return false;
  44949. for (var i = 0; i < left.length; i++) {
  44950. if (!callback(left[i], right[i])) return false;
  44951. }
  44952. return true;
  44953. };
  44954. }
  44955. this.encode = arrayHandler(bindTo(type, 'encode'));
  44956. this.decode = arrayHandler(bindTo(type, 'decode'));
  44957. this.is = arrayHandler(bindTo(type, 'is'), true);
  44958. this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
  44959. this.pattern = type.pattern;
  44960. this.$arrayMode = mode;
  44961. }
  44962. };
  44963. /**
  44964. * @ngdoc object
  44965. * @name ui.router.util.$urlMatcherFactory
  44966. *
  44967. * @description
  44968. * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
  44969. * is also available to providers under the name `$urlMatcherFactoryProvider`.
  44970. */
  44971. function $UrlMatcherFactory() {
  44972. $$UMFP = this;
  44973. var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
  44974. function valToString(val) { return val != null ? val.toString().replace(/\//g, "%2F") : val; }
  44975. function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, "/") : val; }
  44976. // TODO: in 1.0, make string .is() return false if value is undefined by default.
  44977. // function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); }
  44978. function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }
  44979. var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
  44980. string: {
  44981. encode: valToString,
  44982. decode: valFromString,
  44983. is: regexpMatches,
  44984. pattern: /[^/]*/
  44985. },
  44986. int: {
  44987. encode: valToString,
  44988. decode: function(val) { return parseInt(val, 10); },
  44989. is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },
  44990. pattern: /\d+/
  44991. },
  44992. bool: {
  44993. encode: function(val) { return val ? 1 : 0; },
  44994. decode: function(val) { return parseInt(val, 10) !== 0; },
  44995. is: function(val) { return val === true || val === false; },
  44996. pattern: /0|1/
  44997. },
  44998. date: {
  44999. encode: function (val) {
  45000. if (!this.is(val))
  45001. return undefined;
  45002. return [ val.getFullYear(),
  45003. ('0' + (val.getMonth() + 1)).slice(-2),
  45004. ('0' + val.getDate()).slice(-2)
  45005. ].join("-");
  45006. },
  45007. decode: function (val) {
  45008. if (this.is(val)) return val;
  45009. var match = this.capture.exec(val);
  45010. return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
  45011. },
  45012. is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },
  45013. equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },
  45014. pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
  45015. capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
  45016. },
  45017. json: {
  45018. encode: angular.toJson,
  45019. decode: angular.fromJson,
  45020. is: angular.isObject,
  45021. equals: angular.equals,
  45022. pattern: /[^/]*/
  45023. },
  45024. any: { // does not encode/decode
  45025. encode: angular.identity,
  45026. decode: angular.identity,
  45027. is: angular.identity,
  45028. equals: angular.equals,
  45029. pattern: /.*/
  45030. }
  45031. };
  45032. function getDefaultConfig() {
  45033. return {
  45034. strict: isStrictMode,
  45035. caseInsensitive: isCaseInsensitive
  45036. };
  45037. }
  45038. function isInjectable(value) {
  45039. return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
  45040. }
  45041. /**
  45042. * [Internal] Get the default value of a parameter, which may be an injectable function.
  45043. */
  45044. $UrlMatcherFactory.$$getDefaultValue = function(config) {
  45045. if (!isInjectable(config.value)) return config.value;
  45046. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  45047. return injector.invoke(config.value);
  45048. };
  45049. /**
  45050. * @ngdoc function
  45051. * @name ui.router.util.$urlMatcherFactory#caseInsensitive
  45052. * @methodOf ui.router.util.$urlMatcherFactory
  45053. *
  45054. * @description
  45055. * Defines whether URL matching should be case sensitive (the default behavior), or not.
  45056. *
  45057. * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
  45058. * @returns {boolean} the current value of caseInsensitive
  45059. */
  45060. this.caseInsensitive = function(value) {
  45061. if (isDefined(value))
  45062. isCaseInsensitive = value;
  45063. return isCaseInsensitive;
  45064. };
  45065. /**
  45066. * @ngdoc function
  45067. * @name ui.router.util.$urlMatcherFactory#strictMode
  45068. * @methodOf ui.router.util.$urlMatcherFactory
  45069. *
  45070. * @description
  45071. * Defines whether URLs should match trailing slashes, or not (the default behavior).
  45072. *
  45073. * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
  45074. * @returns {boolean} the current value of strictMode
  45075. */
  45076. this.strictMode = function(value) {
  45077. if (isDefined(value))
  45078. isStrictMode = value;
  45079. return isStrictMode;
  45080. };
  45081. /**
  45082. * @ngdoc function
  45083. * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
  45084. * @methodOf ui.router.util.$urlMatcherFactory
  45085. *
  45086. * @description
  45087. * Sets the default behavior when generating or matching URLs with default parameter values.
  45088. *
  45089. * @param {string} value A string that defines the default parameter URL squashing behavior.
  45090. * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
  45091. * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
  45092. * parameter is surrounded by slashes, squash (remove) one slash from the URL
  45093. * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
  45094. * the parameter value from the URL and replace it with this string.
  45095. */
  45096. this.defaultSquashPolicy = function(value) {
  45097. if (!isDefined(value)) return defaultSquashPolicy;
  45098. if (value !== true && value !== false && !isString(value))
  45099. throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
  45100. defaultSquashPolicy = value;
  45101. return value;
  45102. };
  45103. /**
  45104. * @ngdoc function
  45105. * @name ui.router.util.$urlMatcherFactory#compile
  45106. * @methodOf ui.router.util.$urlMatcherFactory
  45107. *
  45108. * @description
  45109. * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
  45110. *
  45111. * @param {string} pattern The URL pattern.
  45112. * @param {Object} config The config object hash.
  45113. * @returns {UrlMatcher} The UrlMatcher.
  45114. */
  45115. this.compile = function (pattern, config) {
  45116. return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
  45117. };
  45118. /**
  45119. * @ngdoc function
  45120. * @name ui.router.util.$urlMatcherFactory#isMatcher
  45121. * @methodOf ui.router.util.$urlMatcherFactory
  45122. *
  45123. * @description
  45124. * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
  45125. *
  45126. * @param {Object} object The object to perform the type check against.
  45127. * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
  45128. * implementing all the same methods.
  45129. */
  45130. this.isMatcher = function (o) {
  45131. if (!isObject(o)) return false;
  45132. var result = true;
  45133. forEach(UrlMatcher.prototype, function(val, name) {
  45134. if (isFunction(val)) {
  45135. result = result && (isDefined(o[name]) && isFunction(o[name]));
  45136. }
  45137. });
  45138. return result;
  45139. };
  45140. /**
  45141. * @ngdoc function
  45142. * @name ui.router.util.$urlMatcherFactory#type
  45143. * @methodOf ui.router.util.$urlMatcherFactory
  45144. *
  45145. * @description
  45146. * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
  45147. * generate URLs with typed parameters.
  45148. *
  45149. * @param {string} name The type name.
  45150. * @param {Object|Function} definition The type definition. See
  45151. * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  45152. * @param {Object|Function} definitionFn (optional) A function that is injected before the app
  45153. * runtime starts. The result of this function is merged into the existing `definition`.
  45154. * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  45155. *
  45156. * @returns {Object} Returns `$urlMatcherFactoryProvider`.
  45157. *
  45158. * @example
  45159. * This is a simple example of a custom type that encodes and decodes items from an
  45160. * array, using the array index as the URL-encoded value:
  45161. *
  45162. * <pre>
  45163. * var list = ['John', 'Paul', 'George', 'Ringo'];
  45164. *
  45165. * $urlMatcherFactoryProvider.type('listItem', {
  45166. * encode: function(item) {
  45167. * // Represent the list item in the URL using its corresponding index
  45168. * return list.indexOf(item);
  45169. * },
  45170. * decode: function(item) {
  45171. * // Look up the list item by index
  45172. * return list[parseInt(item, 10)];
  45173. * },
  45174. * is: function(item) {
  45175. * // Ensure the item is valid by checking to see that it appears
  45176. * // in the list
  45177. * return list.indexOf(item) > -1;
  45178. * }
  45179. * });
  45180. *
  45181. * $stateProvider.state('list', {
  45182. * url: "/list/{item:listItem}",
  45183. * controller: function($scope, $stateParams) {
  45184. * console.log($stateParams.item);
  45185. * }
  45186. * });
  45187. *
  45188. * // ...
  45189. *
  45190. * // Changes URL to '/list/3', logs "Ringo" to the console
  45191. * $state.go('list', { item: "Ringo" });
  45192. * </pre>
  45193. *
  45194. * This is a more complex example of a type that relies on dependency injection to
  45195. * interact with services, and uses the parameter name from the URL to infer how to
  45196. * handle encoding and decoding parameter values:
  45197. *
  45198. * <pre>
  45199. * // Defines a custom type that gets a value from a service,
  45200. * // where each service gets different types of values from
  45201. * // a backend API:
  45202. * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
  45203. *
  45204. * // Matches up services to URL parameter names
  45205. * var services = {
  45206. * user: Users,
  45207. * post: Posts
  45208. * };
  45209. *
  45210. * return {
  45211. * encode: function(object) {
  45212. * // Represent the object in the URL using its unique ID
  45213. * return object.id;
  45214. * },
  45215. * decode: function(value, key) {
  45216. * // Look up the object by ID, using the parameter
  45217. * // name (key) to call the correct service
  45218. * return services[key].findById(value);
  45219. * },
  45220. * is: function(object, key) {
  45221. * // Check that object is a valid dbObject
  45222. * return angular.isObject(object) && object.id && services[key];
  45223. * }
  45224. * equals: function(a, b) {
  45225. * // Check the equality of decoded objects by comparing
  45226. * // their unique IDs
  45227. * return a.id === b.id;
  45228. * }
  45229. * };
  45230. * });
  45231. *
  45232. * // In a config() block, you can then attach URLs with
  45233. * // type-annotated parameters:
  45234. * $stateProvider.state('users', {
  45235. * url: "/users",
  45236. * // ...
  45237. * }).state('users.item', {
  45238. * url: "/{user:dbObject}",
  45239. * controller: function($scope, $stateParams) {
  45240. * // $stateParams.user will now be an object returned from
  45241. * // the Users service
  45242. * },
  45243. * // ...
  45244. * });
  45245. * </pre>
  45246. */
  45247. this.type = function (name, definition, definitionFn) {
  45248. if (!isDefined(definition)) return $types[name];
  45249. if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
  45250. $types[name] = new Type(extend({ name: name }, definition));
  45251. if (definitionFn) {
  45252. typeQueue.push({ name: name, def: definitionFn });
  45253. if (!enqueue) flushTypeQueue();
  45254. }
  45255. return this;
  45256. };
  45257. // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
  45258. function flushTypeQueue() {
  45259. while(typeQueue.length) {
  45260. var type = typeQueue.shift();
  45261. if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
  45262. angular.extend($types[type.name], injector.invoke(type.def));
  45263. }
  45264. }
  45265. // Register default types. Store them in the prototype of $types.
  45266. forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });
  45267. $types = inherit($types, {});
  45268. /* No need to document $get, since it returns this */
  45269. this.$get = ['$injector', function ($injector) {
  45270. injector = $injector;
  45271. enqueue = false;
  45272. flushTypeQueue();
  45273. forEach(defaultTypes, function(type, name) {
  45274. if (!$types[name]) $types[name] = new Type(type);
  45275. });
  45276. return this;
  45277. }];
  45278. this.Param = function Param(id, type, config, location) {
  45279. var self = this;
  45280. config = unwrapShorthand(config);
  45281. type = getType(config, type, location);
  45282. var arrayMode = getArrayMode();
  45283. type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
  45284. if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
  45285. config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
  45286. var isOptional = config.value !== undefined;
  45287. var squash = getSquashPolicy(config, isOptional);
  45288. var replace = getReplace(config, arrayMode, isOptional, squash);
  45289. function unwrapShorthand(config) {
  45290. var keys = isObject(config) ? objectKeys(config) : [];
  45291. var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
  45292. indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
  45293. if (isShorthand) config = { value: config };
  45294. config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };
  45295. return config;
  45296. }
  45297. function getType(config, urlType, location) {
  45298. if (config.type && urlType) throw new Error("Param '"+id+"' has two type configurations.");
  45299. if (urlType) return urlType;
  45300. if (!config.type) return (location === "config" ? $types.any : $types.string);
  45301. return config.type instanceof Type ? config.type : new Type(config.type);
  45302. }
  45303. // array config: param name (param[]) overrides default settings. explicit config overrides param name.
  45304. function getArrayMode() {
  45305. var arrayDefaults = { array: (location === "search" ? "auto" : false) };
  45306. var arrayParamNomenclature = id.match(/\[\]$/) ? { array: true } : {};
  45307. return extend(arrayDefaults, arrayParamNomenclature, config).array;
  45308. }
  45309. /**
  45310. * returns false, true, or the squash value to indicate the "default parameter url squash policy".
  45311. */
  45312. function getSquashPolicy(config, isOptional) {
  45313. var squash = config.squash;
  45314. if (!isOptional || squash === false) return false;
  45315. if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
  45316. if (squash === true || isString(squash)) return squash;
  45317. throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
  45318. }
  45319. function getReplace(config, arrayMode, isOptional, squash) {
  45320. var replace, configuredKeys, defaultPolicy = [
  45321. { from: "", to: (isOptional || arrayMode ? undefined : "") },
  45322. { from: null, to: (isOptional || arrayMode ? undefined : "") }
  45323. ];
  45324. replace = isArray(config.replace) ? config.replace : [];
  45325. if (isString(squash))
  45326. replace.push({ from: squash, to: undefined });
  45327. configuredKeys = map(replace, function(item) { return item.from; } );
  45328. return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);
  45329. }
  45330. /**
  45331. * [Internal] Get the default value of a parameter, which may be an injectable function.
  45332. */
  45333. function $$getDefaultValue() {
  45334. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  45335. return injector.invoke(config.$$fn);
  45336. }
  45337. /**
  45338. * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
  45339. * default value, which may be the result of an injectable function.
  45340. */
  45341. function $value(value) {
  45342. function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }
  45343. function $replace(value) {
  45344. var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });
  45345. return replacement.length ? replacement[0] : value;
  45346. }
  45347. value = $replace(value);
  45348. return isDefined(value) ? self.type.decode(value) : $$getDefaultValue();
  45349. }
  45350. function toString() { return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}"; }
  45351. extend(this, {
  45352. id: id,
  45353. type: type,
  45354. location: location,
  45355. array: arrayMode,
  45356. squash: squash,
  45357. replace: replace,
  45358. isOptional: isOptional,
  45359. value: $value,
  45360. dynamic: undefined,
  45361. config: config,
  45362. toString: toString
  45363. });
  45364. };
  45365. function ParamSet(params) {
  45366. extend(this, params || {});
  45367. }
  45368. ParamSet.prototype = {
  45369. $$new: function() {
  45370. return inherit(this, extend(new ParamSet(), { $$parent: this}));
  45371. },
  45372. $$keys: function () {
  45373. var keys = [], chain = [], parent = this,
  45374. ignore = objectKeys(ParamSet.prototype);
  45375. while (parent) { chain.push(parent); parent = parent.$$parent; }
  45376. chain.reverse();
  45377. forEach(chain, function(paramset) {
  45378. forEach(objectKeys(paramset), function(key) {
  45379. if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
  45380. });
  45381. });
  45382. return keys;
  45383. },
  45384. $$values: function(paramValues) {
  45385. var values = {}, self = this;
  45386. forEach(self.$$keys(), function(key) {
  45387. values[key] = self[key].value(paramValues && paramValues[key]);
  45388. });
  45389. return values;
  45390. },
  45391. $$equals: function(paramValues1, paramValues2) {
  45392. var equal = true, self = this;
  45393. forEach(self.$$keys(), function(key) {
  45394. var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
  45395. if (!self[key].type.equals(left, right)) equal = false;
  45396. });
  45397. return equal;
  45398. },
  45399. $$validates: function $$validate(paramValues) {
  45400. var result = true, isOptional, val, param, self = this;
  45401. forEach(this.$$keys(), function(key) {
  45402. param = self[key];
  45403. val = paramValues[key];
  45404. isOptional = !val && param.isOptional;
  45405. result = result && (isOptional || !!param.type.is(val));
  45406. });
  45407. return result;
  45408. },
  45409. $$parent: undefined
  45410. };
  45411. this.ParamSet = ParamSet;
  45412. }
  45413. // Register as a provider so it's available to other providers
  45414. angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
  45415. angular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);
  45416. /**
  45417. * @ngdoc object
  45418. * @name ui.router.router.$urlRouterProvider
  45419. *
  45420. * @requires ui.router.util.$urlMatcherFactoryProvider
  45421. * @requires $locationProvider
  45422. *
  45423. * @description
  45424. * `$urlRouterProvider` has the responsibility of watching `$location`.
  45425. * When `$location` changes it runs through a list of rules one by one until a
  45426. * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
  45427. * a url in a state configuration. All urls are compiled into a UrlMatcher object.
  45428. *
  45429. * There are several methods on `$urlRouterProvider` that make it useful to use directly
  45430. * in your module config.
  45431. */
  45432. $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
  45433. function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
  45434. var rules = [], otherwise = null, interceptDeferred = false, listener;
  45435. // Returns a string that is a prefix of all strings matching the RegExp
  45436. function regExpPrefix(re) {
  45437. var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
  45438. return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  45439. }
  45440. // Interpolates matched values into a String.replace()-style pattern
  45441. function interpolate(pattern, match) {
  45442. return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
  45443. return match[what === '$' ? 0 : Number(what)];
  45444. });
  45445. }
  45446. /**
  45447. * @ngdoc function
  45448. * @name ui.router.router.$urlRouterProvider#rule
  45449. * @methodOf ui.router.router.$urlRouterProvider
  45450. *
  45451. * @description
  45452. * Defines rules that are used by `$urlRouterProvider` to find matches for
  45453. * specific URLs.
  45454. *
  45455. * @example
  45456. * <pre>
  45457. * var app = angular.module('app', ['ui.router.router']);
  45458. *
  45459. * app.config(function ($urlRouterProvider) {
  45460. * // Here's an example of how you might allow case insensitive urls
  45461. * $urlRouterProvider.rule(function ($injector, $location) {
  45462. * var path = $location.path(),
  45463. * normalized = path.toLowerCase();
  45464. *
  45465. * if (path !== normalized) {
  45466. * return normalized;
  45467. * }
  45468. * });
  45469. * });
  45470. * </pre>
  45471. *
  45472. * @param {object} rule Handler function that takes `$injector` and `$location`
  45473. * services as arguments. You can use them to return a valid path as a string.
  45474. *
  45475. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  45476. */
  45477. this.rule = function (rule) {
  45478. if (!isFunction(rule)) throw new Error("'rule' must be a function");
  45479. rules.push(rule);
  45480. return this;
  45481. };
  45482. /**
  45483. * @ngdoc object
  45484. * @name ui.router.router.$urlRouterProvider#otherwise
  45485. * @methodOf ui.router.router.$urlRouterProvider
  45486. *
  45487. * @description
  45488. * Defines a path that is used when an invalid route is requested.
  45489. *
  45490. * @example
  45491. * <pre>
  45492. * var app = angular.module('app', ['ui.router.router']);
  45493. *
  45494. * app.config(function ($urlRouterProvider) {
  45495. * // if the path doesn't match any of the urls you configured
  45496. * // otherwise will take care of routing the user to the
  45497. * // specified url
  45498. * $urlRouterProvider.otherwise('/index');
  45499. *
  45500. * // Example of using function rule as param
  45501. * $urlRouterProvider.otherwise(function ($injector, $location) {
  45502. * return '/a/valid/url';
  45503. * });
  45504. * });
  45505. * </pre>
  45506. *
  45507. * @param {string|object} rule The url path you want to redirect to or a function
  45508. * rule that returns the url path. The function version is passed two params:
  45509. * `$injector` and `$location` services, and must return a url string.
  45510. *
  45511. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  45512. */
  45513. this.otherwise = function (rule) {
  45514. if (isString(rule)) {
  45515. var redirect = rule;
  45516. rule = function () { return redirect; };
  45517. }
  45518. else if (!isFunction(rule)) throw new Error("'rule' must be a function");
  45519. otherwise = rule;
  45520. return this;
  45521. };
  45522. function handleIfMatch($injector, handler, match) {
  45523. if (!match) return false;
  45524. var result = $injector.invoke(handler, handler, { $match: match });
  45525. return isDefined(result) ? result : true;
  45526. }
  45527. /**
  45528. * @ngdoc function
  45529. * @name ui.router.router.$urlRouterProvider#when
  45530. * @methodOf ui.router.router.$urlRouterProvider
  45531. *
  45532. * @description
  45533. * Registers a handler for a given url matching. if handle is a string, it is
  45534. * treated as a redirect, and is interpolated according to the syntax of match
  45535. * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
  45536. *
  45537. * If the handler is a function, it is injectable. It gets invoked if `$location`
  45538. * matches. You have the option of inject the match object as `$match`.
  45539. *
  45540. * The handler can return
  45541. *
  45542. * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
  45543. * will continue trying to find another one that matches.
  45544. * - **string** which is treated as a redirect and passed to `$location.url()`
  45545. * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
  45546. *
  45547. * @example
  45548. * <pre>
  45549. * var app = angular.module('app', ['ui.router.router']);
  45550. *
  45551. * app.config(function ($urlRouterProvider) {
  45552. * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
  45553. * if ($state.$current.navigable !== state ||
  45554. * !equalForKeys($match, $stateParams) {
  45555. * $state.transitionTo(state, $match, false);
  45556. * }
  45557. * });
  45558. * });
  45559. * </pre>
  45560. *
  45561. * @param {string|object} what The incoming path that you want to redirect.
  45562. * @param {string|object} handler The path you want to redirect your user to.
  45563. */
  45564. this.when = function (what, handler) {
  45565. var redirect, handlerIsString = isString(handler);
  45566. if (isString(what)) what = $urlMatcherFactory.compile(what);
  45567. if (!handlerIsString && !isFunction(handler) && !isArray(handler))
  45568. throw new Error("invalid 'handler' in when()");
  45569. var strategies = {
  45570. matcher: function (what, handler) {
  45571. if (handlerIsString) {
  45572. redirect = $urlMatcherFactory.compile(handler);
  45573. handler = ['$match', function ($match) { return redirect.format($match); }];
  45574. }
  45575. return extend(function ($injector, $location) {
  45576. return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
  45577. }, {
  45578. prefix: isString(what.prefix) ? what.prefix : ''
  45579. });
  45580. },
  45581. regex: function (what, handler) {
  45582. if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
  45583. if (handlerIsString) {
  45584. redirect = handler;
  45585. handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
  45586. }
  45587. return extend(function ($injector, $location) {
  45588. return handleIfMatch($injector, handler, what.exec($location.path()));
  45589. }, {
  45590. prefix: regExpPrefix(what)
  45591. });
  45592. }
  45593. };
  45594. var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
  45595. for (var n in check) {
  45596. if (check[n]) return this.rule(strategies[n](what, handler));
  45597. }
  45598. throw new Error("invalid 'what' in when()");
  45599. };
  45600. /**
  45601. * @ngdoc function
  45602. * @name ui.router.router.$urlRouterProvider#deferIntercept
  45603. * @methodOf ui.router.router.$urlRouterProvider
  45604. *
  45605. * @description
  45606. * Disables (or enables) deferring location change interception.
  45607. *
  45608. * If you wish to customize the behavior of syncing the URL (for example, if you wish to
  45609. * defer a transition but maintain the current URL), call this method at configuration time.
  45610. * Then, at run time, call `$urlRouter.listen()` after you have configured your own
  45611. * `$locationChangeSuccess` event handler.
  45612. *
  45613. * @example
  45614. * <pre>
  45615. * var app = angular.module('app', ['ui.router.router']);
  45616. *
  45617. * app.config(function ($urlRouterProvider) {
  45618. *
  45619. * // Prevent $urlRouter from automatically intercepting URL changes;
  45620. * // this allows you to configure custom behavior in between
  45621. * // location changes and route synchronization:
  45622. * $urlRouterProvider.deferIntercept();
  45623. *
  45624. * }).run(function ($rootScope, $urlRouter, UserService) {
  45625. *
  45626. * $rootScope.$on('$locationChangeSuccess', function(e) {
  45627. * // UserService is an example service for managing user state
  45628. * if (UserService.isLoggedIn()) return;
  45629. *
  45630. * // Prevent $urlRouter's default handler from firing
  45631. * e.preventDefault();
  45632. *
  45633. * UserService.handleLogin().then(function() {
  45634. * // Once the user has logged in, sync the current URL
  45635. * // to the router:
  45636. * $urlRouter.sync();
  45637. * });
  45638. * });
  45639. *
  45640. * // Configures $urlRouter's listener *after* your custom listener
  45641. * $urlRouter.listen();
  45642. * });
  45643. * </pre>
  45644. *
  45645. * @param {boolean} defer Indicates whether to defer location change interception. Passing
  45646. no parameter is equivalent to `true`.
  45647. */
  45648. this.deferIntercept = function (defer) {
  45649. if (defer === undefined) defer = true;
  45650. interceptDeferred = defer;
  45651. };
  45652. /**
  45653. * @ngdoc object
  45654. * @name ui.router.router.$urlRouter
  45655. *
  45656. * @requires $location
  45657. * @requires $rootScope
  45658. * @requires $injector
  45659. * @requires $browser
  45660. *
  45661. * @description
  45662. *
  45663. */
  45664. this.$get = $get;
  45665. $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
  45666. function $get( $location, $rootScope, $injector, $browser) {
  45667. var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
  45668. function appendBasePath(url, isHtml5, absolute) {
  45669. if (baseHref === '/') return url;
  45670. if (isHtml5) return baseHref.slice(0, -1) + url;
  45671. if (absolute) return baseHref.slice(1) + url;
  45672. return url;
  45673. }
  45674. // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
  45675. function update(evt) {
  45676. if (evt && evt.defaultPrevented) return;
  45677. var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
  45678. lastPushedUrl = undefined;
  45679. if (ignoreUpdate) return true;
  45680. function check(rule) {
  45681. var handled = rule($injector, $location);
  45682. if (!handled) return false;
  45683. if (isString(handled)) $location.replace().url(handled);
  45684. return true;
  45685. }
  45686. var n = rules.length, i;
  45687. for (i = 0; i < n; i++) {
  45688. if (check(rules[i])) return;
  45689. }
  45690. // always check otherwise last to allow dynamic updates to the set of rules
  45691. if (otherwise) check(otherwise);
  45692. }
  45693. function listen() {
  45694. listener = listener || $rootScope.$on('$locationChangeSuccess', update);
  45695. return listener;
  45696. }
  45697. if (!interceptDeferred) listen();
  45698. return {
  45699. /**
  45700. * @ngdoc function
  45701. * @name ui.router.router.$urlRouter#sync
  45702. * @methodOf ui.router.router.$urlRouter
  45703. *
  45704. * @description
  45705. * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
  45706. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
  45707. * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
  45708. * with the transition by calling `$urlRouter.sync()`.
  45709. *
  45710. * @example
  45711. * <pre>
  45712. * angular.module('app', ['ui.router'])
  45713. * .run(function($rootScope, $urlRouter) {
  45714. * $rootScope.$on('$locationChangeSuccess', function(evt) {
  45715. * // Halt state change from even starting
  45716. * evt.preventDefault();
  45717. * // Perform custom logic
  45718. * var meetsRequirement = ...
  45719. * // Continue with the update and state transition if logic allows
  45720. * if (meetsRequirement) $urlRouter.sync();
  45721. * });
  45722. * });
  45723. * </pre>
  45724. */
  45725. sync: function() {
  45726. update();
  45727. },
  45728. listen: function() {
  45729. return listen();
  45730. },
  45731. update: function(read) {
  45732. if (read) {
  45733. location = $location.url();
  45734. return;
  45735. }
  45736. if ($location.url() === location) return;
  45737. $location.url(location);
  45738. $location.replace();
  45739. },
  45740. push: function(urlMatcher, params, options) {
  45741. $location.url(urlMatcher.format(params || {}));
  45742. lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
  45743. if (options && options.replace) $location.replace();
  45744. },
  45745. /**
  45746. * @ngdoc function
  45747. * @name ui.router.router.$urlRouter#href
  45748. * @methodOf ui.router.router.$urlRouter
  45749. *
  45750. * @description
  45751. * A URL generation method that returns the compiled URL for a given
  45752. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
  45753. *
  45754. * @example
  45755. * <pre>
  45756. * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
  45757. * person: "bob"
  45758. * });
  45759. * // $bob == "/about/bob";
  45760. * </pre>
  45761. *
  45762. * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
  45763. * @param {object=} params An object of parameter values to fill the matcher's required parameters.
  45764. * @param {object=} options Options object. The options are:
  45765. *
  45766. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  45767. *
  45768. * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
  45769. */
  45770. href: function(urlMatcher, params, options) {
  45771. if (!urlMatcher.validates(params)) return null;
  45772. var isHtml5 = $locationProvider.html5Mode();
  45773. if (angular.isObject(isHtml5)) {
  45774. isHtml5 = isHtml5.enabled;
  45775. }
  45776. var url = urlMatcher.format(params);
  45777. options = options || {};
  45778. if (!isHtml5 && url !== null) {
  45779. url = "#" + $locationProvider.hashPrefix() + url;
  45780. }
  45781. url = appendBasePath(url, isHtml5, options.absolute);
  45782. if (!options.absolute || !url) {
  45783. return url;
  45784. }
  45785. var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
  45786. port = (port === 80 || port === 443 ? '' : ':' + port);
  45787. return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
  45788. }
  45789. };
  45790. }
  45791. }
  45792. angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
  45793. /**
  45794. * @ngdoc object
  45795. * @name ui.router.state.$stateProvider
  45796. *
  45797. * @requires ui.router.router.$urlRouterProvider
  45798. * @requires ui.router.util.$urlMatcherFactoryProvider
  45799. *
  45800. * @description
  45801. * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
  45802. * on state.
  45803. *
  45804. * A state corresponds to a "place" in the application in terms of the overall UI and
  45805. * navigation. A state describes (via the controller / template / view properties) what
  45806. * the UI looks like and does at that place.
  45807. *
  45808. * States often have things in common, and the primary way of factoring out these
  45809. * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
  45810. * nested states.
  45811. *
  45812. * The `$stateProvider` provides interfaces to declare these states for your app.
  45813. */
  45814. $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
  45815. function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
  45816. var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
  45817. // Builds state properties from definition passed to registerState()
  45818. var stateBuilder = {
  45819. // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
  45820. // state.children = [];
  45821. // if (parent) parent.children.push(state);
  45822. parent: function(state) {
  45823. if (isDefined(state.parent) && state.parent) return findState(state.parent);
  45824. // regex matches any valid composite state name
  45825. // would match "contact.list" but not "contacts"
  45826. var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
  45827. return compositeName ? findState(compositeName[1]) : root;
  45828. },
  45829. // inherit 'data' from parent and override by own values (if any)
  45830. data: function(state) {
  45831. if (state.parent && state.parent.data) {
  45832. state.data = state.self.data = extend({}, state.parent.data, state.data);
  45833. }
  45834. return state.data;
  45835. },
  45836. // Build a URLMatcher if necessary, either via a relative or absolute URL
  45837. url: function(state) {
  45838. var url = state.url, config = { params: state.params || {} };
  45839. if (isString(url)) {
  45840. if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
  45841. return (state.parent.navigable || root).url.concat(url, config);
  45842. }
  45843. if (!url || $urlMatcherFactory.isMatcher(url)) return url;
  45844. throw new Error("Invalid url '" + url + "' in state '" + state + "'");
  45845. },
  45846. // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
  45847. navigable: function(state) {
  45848. return state.url ? state : (state.parent ? state.parent.navigable : null);
  45849. },
  45850. // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
  45851. ownParams: function(state) {
  45852. var params = state.url && state.url.params || new $$UMFP.ParamSet();
  45853. forEach(state.params || {}, function(config, id) {
  45854. if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
  45855. });
  45856. return params;
  45857. },
  45858. // Derive parameters for this state and ensure they're a super-set of parent's parameters
  45859. params: function(state) {
  45860. return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();
  45861. },
  45862. // If there is no explicit multi-view configuration, make one up so we don't have
  45863. // to handle both cases in the view directive later. Note that having an explicit
  45864. // 'views' property will mean the default unnamed view properties are ignored. This
  45865. // is also a good time to resolve view names to absolute names, so everything is a
  45866. // straight lookup at link time.
  45867. views: function(state) {
  45868. var views = {};
  45869. forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
  45870. if (name.indexOf('@') < 0) name += '@' + state.parent.name;
  45871. views[name] = view;
  45872. });
  45873. return views;
  45874. },
  45875. // Keep a full path from the root down to this state as this is needed for state activation.
  45876. path: function(state) {
  45877. return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
  45878. },
  45879. // Speed up $state.contains() as it's used a lot
  45880. includes: function(state) {
  45881. var includes = state.parent ? extend({}, state.parent.includes) : {};
  45882. includes[state.name] = true;
  45883. return includes;
  45884. },
  45885. $delegates: {}
  45886. };
  45887. function isRelative(stateName) {
  45888. return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
  45889. }
  45890. function findState(stateOrName, base) {
  45891. if (!stateOrName) return undefined;
  45892. var isStr = isString(stateOrName),
  45893. name = isStr ? stateOrName : stateOrName.name,
  45894. path = isRelative(name);
  45895. if (path) {
  45896. if (!base) throw new Error("No reference point given for path '" + name + "'");
  45897. base = findState(base);
  45898. var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
  45899. for (; i < pathLength; i++) {
  45900. if (rel[i] === "" && i === 0) {
  45901. current = base;
  45902. continue;
  45903. }
  45904. if (rel[i] === "^") {
  45905. if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
  45906. current = current.parent;
  45907. continue;
  45908. }
  45909. break;
  45910. }
  45911. rel = rel.slice(i).join(".");
  45912. name = current.name + (current.name && rel ? "." : "") + rel;
  45913. }
  45914. var state = states[name];
  45915. if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
  45916. return state;
  45917. }
  45918. return undefined;
  45919. }
  45920. function queueState(parentName, state) {
  45921. if (!queue[parentName]) {
  45922. queue[parentName] = [];
  45923. }
  45924. queue[parentName].push(state);
  45925. }
  45926. function flushQueuedChildren(parentName) {
  45927. var queued = queue[parentName] || [];
  45928. while(queued.length) {
  45929. registerState(queued.shift());
  45930. }
  45931. }
  45932. function registerState(state) {
  45933. // Wrap a new object around the state so we can store our private details easily.
  45934. state = inherit(state, {
  45935. self: state,
  45936. resolve: state.resolve || {},
  45937. toString: function() { return this.name; }
  45938. });
  45939. var name = state.name;
  45940. if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
  45941. if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
  45942. // Get parent name
  45943. var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
  45944. : (isString(state.parent)) ? state.parent
  45945. : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
  45946. : '';
  45947. // If parent is not registered yet, add state to queue and register later
  45948. if (parentName && !states[parentName]) {
  45949. return queueState(parentName, state.self);
  45950. }
  45951. for (var key in stateBuilder) {
  45952. if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
  45953. }
  45954. states[name] = state;
  45955. // Register the state in the global state list and with $urlRouter if necessary.
  45956. if (!state[abstractKey] && state.url) {
  45957. $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
  45958. if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
  45959. $state.transitionTo(state, $match, { inherit: true, location: false });
  45960. }
  45961. }]);
  45962. }
  45963. // Register any queued children
  45964. flushQueuedChildren(name);
  45965. return state;
  45966. }
  45967. // Checks text to see if it looks like a glob.
  45968. function isGlob (text) {
  45969. return text.indexOf('*') > -1;
  45970. }
  45971. // Returns true if glob matches current $state name.
  45972. function doesStateMatchGlob (glob) {
  45973. var globSegments = glob.split('.'),
  45974. segments = $state.$current.name.split('.');
  45975. //match greedy starts
  45976. if (globSegments[0] === '**') {
  45977. segments = segments.slice(indexOf(segments, globSegments[1]));
  45978. segments.unshift('**');
  45979. }
  45980. //match greedy ends
  45981. if (globSegments[globSegments.length - 1] === '**') {
  45982. segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
  45983. segments.push('**');
  45984. }
  45985. if (globSegments.length != segments.length) {
  45986. return false;
  45987. }
  45988. //match single stars
  45989. for (var i = 0, l = globSegments.length; i < l; i++) {
  45990. if (globSegments[i] === '*') {
  45991. segments[i] = '*';
  45992. }
  45993. }
  45994. return segments.join('') === globSegments.join('');
  45995. }
  45996. // Implicit root state that is always active
  45997. root = registerState({
  45998. name: '',
  45999. url: '^',
  46000. views: null,
  46001. 'abstract': true
  46002. });
  46003. root.navigable = null;
  46004. /**
  46005. * @ngdoc function
  46006. * @name ui.router.state.$stateProvider#decorator
  46007. * @methodOf ui.router.state.$stateProvider
  46008. *
  46009. * @description
  46010. * Allows you to extend (carefully) or override (at your own peril) the
  46011. * `stateBuilder` object used internally by `$stateProvider`. This can be used
  46012. * to add custom functionality to ui-router, for example inferring templateUrl
  46013. * based on the state name.
  46014. *
  46015. * When passing only a name, it returns the current (original or decorated) builder
  46016. * function that matches `name`.
  46017. *
  46018. * The builder functions that can be decorated are listed below. Though not all
  46019. * necessarily have a good use case for decoration, that is up to you to decide.
  46020. *
  46021. * In addition, users can attach custom decorators, which will generate new
  46022. * properties within the state's internal definition. There is currently no clear
  46023. * use-case for this beyond accessing internal states (i.e. $state.$current),
  46024. * however, expect this to become increasingly relevant as we introduce additional
  46025. * meta-programming features.
  46026. *
  46027. * **Warning**: Decorators should not be interdependent because the order of
  46028. * execution of the builder functions in non-deterministic. Builder functions
  46029. * should only be dependent on the state definition object and super function.
  46030. *
  46031. *
  46032. * Existing builder functions and current return values:
  46033. *
  46034. * - **parent** `{object}` - returns the parent state object.
  46035. * - **data** `{object}` - returns state data, including any inherited data that is not
  46036. * overridden by own values (if any).
  46037. * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
  46038. * or `null`.
  46039. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
  46040. * navigable).
  46041. * - **params** `{object}` - returns an array of state params that are ensured to
  46042. * be a super-set of parent's params.
  46043. * - **views** `{object}` - returns a views object where each key is an absolute view
  46044. * name (i.e. "viewName@stateName") and each value is the config object
  46045. * (template, controller) for the view. Even when you don't use the views object
  46046. * explicitly on a state config, one is still created for you internally.
  46047. * So by decorating this builder function you have access to decorating template
  46048. * and controller properties.
  46049. * - **ownParams** `{object}` - returns an array of params that belong to the state,
  46050. * not including any params defined by ancestor states.
  46051. * - **path** `{string}` - returns the full path from the root down to this state.
  46052. * Needed for state activation.
  46053. * - **includes** `{object}` - returns an object that includes every state that
  46054. * would pass a `$state.includes()` test.
  46055. *
  46056. * @example
  46057. * <pre>
  46058. * // Override the internal 'views' builder with a function that takes the state
  46059. * // definition, and a reference to the internal function being overridden:
  46060. * $stateProvider.decorator('views', function (state, parent) {
  46061. * var result = {},
  46062. * views = parent(state);
  46063. *
  46064. * angular.forEach(views, function (config, name) {
  46065. * var autoName = (state.name + '.' + name).replace('.', '/');
  46066. * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
  46067. * result[name] = config;
  46068. * });
  46069. * return result;
  46070. * });
  46071. *
  46072. * $stateProvider.state('home', {
  46073. * views: {
  46074. * 'contact.list': { controller: 'ListController' },
  46075. * 'contact.item': { controller: 'ItemController' }
  46076. * }
  46077. * });
  46078. *
  46079. * // ...
  46080. *
  46081. * $state.go('home');
  46082. * // Auto-populates list and item views with /partials/home/contact/list.html,
  46083. * // and /partials/home/contact/item.html, respectively.
  46084. * </pre>
  46085. *
  46086. * @param {string} name The name of the builder function to decorate.
  46087. * @param {object} func A function that is responsible for decorating the original
  46088. * builder function. The function receives two parameters:
  46089. *
  46090. * - `{object}` - state - The state config object.
  46091. * - `{object}` - super - The original builder function.
  46092. *
  46093. * @return {object} $stateProvider - $stateProvider instance
  46094. */
  46095. this.decorator = decorator;
  46096. function decorator(name, func) {
  46097. /*jshint validthis: true */
  46098. if (isString(name) && !isDefined(func)) {
  46099. return stateBuilder[name];
  46100. }
  46101. if (!isFunction(func) || !isString(name)) {
  46102. return this;
  46103. }
  46104. if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
  46105. stateBuilder.$delegates[name] = stateBuilder[name];
  46106. }
  46107. stateBuilder[name] = func;
  46108. return this;
  46109. }
  46110. /**
  46111. * @ngdoc function
  46112. * @name ui.router.state.$stateProvider#state
  46113. * @methodOf ui.router.state.$stateProvider
  46114. *
  46115. * @description
  46116. * Registers a state configuration under a given state name. The stateConfig object
  46117. * has the following acceptable properties.
  46118. *
  46119. * @param {string} name A unique state name, e.g. "home", "about", "contacts".
  46120. * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
  46121. * @param {object} stateConfig State configuration object.
  46122. * @param {string|function=} stateConfig.template
  46123. * <a id='template'></a>
  46124. * html template as a string or a function that returns
  46125. * an html template as a string which should be used by the uiView directives. This property
  46126. * takes precedence over templateUrl.
  46127. *
  46128. * If `template` is a function, it will be called with the following parameters:
  46129. *
  46130. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  46131. * applying the current state
  46132. *
  46133. * <pre>template:
  46134. * "<h1>inline template definition</h1>" +
  46135. * "<div ui-view></div>"</pre>
  46136. * <pre>template: function(params) {
  46137. * return "<h1>generated template</h1>"; }</pre>
  46138. * </div>
  46139. *
  46140. * @param {string|function=} stateConfig.templateUrl
  46141. * <a id='templateUrl'></a>
  46142. *
  46143. * path or function that returns a path to an html
  46144. * template that should be used by uiView.
  46145. *
  46146. * If `templateUrl` is a function, it will be called with the following parameters:
  46147. *
  46148. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  46149. * applying the current state
  46150. *
  46151. * <pre>templateUrl: "home.html"</pre>
  46152. * <pre>templateUrl: function(params) {
  46153. * return myTemplates[params.pageId]; }</pre>
  46154. *
  46155. * @param {function=} stateConfig.templateProvider
  46156. * <a id='templateProvider'></a>
  46157. * Provider function that returns HTML content string.
  46158. * <pre> templateProvider:
  46159. * function(MyTemplateService, params) {
  46160. * return MyTemplateService.getTemplate(params.pageId);
  46161. * }</pre>
  46162. *
  46163. * @param {string|function=} stateConfig.controller
  46164. * <a id='controller'></a>
  46165. *
  46166. * Controller fn that should be associated with newly
  46167. * related scope or the name of a registered controller if passed as a string.
  46168. * Optionally, the ControllerAs may be declared here.
  46169. * <pre>controller: "MyRegisteredController"</pre>
  46170. * <pre>controller:
  46171. * "MyRegisteredController as fooCtrl"}</pre>
  46172. * <pre>controller: function($scope, MyService) {
  46173. * $scope.data = MyService.getData(); }</pre>
  46174. *
  46175. * @param {function=} stateConfig.controllerProvider
  46176. * <a id='controllerProvider'></a>
  46177. *
  46178. * Injectable provider function that returns the actual controller or string.
  46179. * <pre>controllerProvider:
  46180. * function(MyResolveData) {
  46181. * if (MyResolveData.foo)
  46182. * return "FooCtrl"
  46183. * else if (MyResolveData.bar)
  46184. * return "BarCtrl";
  46185. * else return function($scope) {
  46186. * $scope.baz = "Qux";
  46187. * }
  46188. * }</pre>
  46189. *
  46190. * @param {string=} stateConfig.controllerAs
  46191. * <a id='controllerAs'></a>
  46192. *
  46193. * A controller alias name. If present the controller will be
  46194. * published to scope under the controllerAs name.
  46195. * <pre>controllerAs: "myCtrl"</pre>
  46196. *
  46197. * @param {object=} stateConfig.resolve
  46198. * <a id='resolve'></a>
  46199. *
  46200. * An optional map&lt;string, function&gt; of dependencies which
  46201. * should be injected into the controller. If any of these dependencies are promises,
  46202. * the router will wait for them all to be resolved before the controller is instantiated.
  46203. * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
  46204. * and the values of the resolved promises are injected into any controllers that reference them.
  46205. * If any of the promises are rejected the $stateChangeError event is fired.
  46206. *
  46207. * The map object is:
  46208. *
  46209. * - key - {string}: name of dependency to be injected into controller
  46210. * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
  46211. * it is injected and return value it treated as dependency. If result is a promise, it is
  46212. * resolved before its value is injected into controller.
  46213. *
  46214. * <pre>resolve: {
  46215. * myResolve1:
  46216. * function($http, $stateParams) {
  46217. * return $http.get("/api/foos/"+stateParams.fooID);
  46218. * }
  46219. * }</pre>
  46220. *
  46221. * @param {string=} stateConfig.url
  46222. * <a id='url'></a>
  46223. *
  46224. * A url fragment with optional parameters. When a state is navigated or
  46225. * transitioned to, the `$stateParams` service will be populated with any
  46226. * parameters that were passed.
  46227. *
  46228. * examples:
  46229. * <pre>url: "/home"
  46230. * url: "/users/:userid"
  46231. * url: "/books/{bookid:[a-zA-Z_-]}"
  46232. * url: "/books/{categoryid:int}"
  46233. * url: "/books/{publishername:string}/{categoryid:int}"
  46234. * url: "/messages?before&after"
  46235. * url: "/messages?{before:date}&{after:date}"</pre>
  46236. * url: "/messages/:mailboxid?{before:date}&{after:date}"
  46237. *
  46238. * @param {object=} stateConfig.views
  46239. * <a id='views'></a>
  46240. * an optional map&lt;string, object&gt; which defined multiple views, or targets views
  46241. * manually/explicitly.
  46242. *
  46243. * Examples:
  46244. *
  46245. * Targets three named `ui-view`s in the parent state's template
  46246. * <pre>views: {
  46247. * header: {
  46248. * controller: "headerCtrl",
  46249. * templateUrl: "header.html"
  46250. * }, body: {
  46251. * controller: "bodyCtrl",
  46252. * templateUrl: "body.html"
  46253. * }, footer: {
  46254. * controller: "footCtrl",
  46255. * templateUrl: "footer.html"
  46256. * }
  46257. * }</pre>
  46258. *
  46259. * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
  46260. * <pre>views: {
  46261. * 'header@top': {
  46262. * controller: "msgHeaderCtrl",
  46263. * templateUrl: "msgHeader.html"
  46264. * }, 'body': {
  46265. * controller: "messagesCtrl",
  46266. * templateUrl: "messages.html"
  46267. * }
  46268. * }</pre>
  46269. *
  46270. * @param {boolean=} [stateConfig.abstract=false]
  46271. * <a id='abstract'></a>
  46272. * An abstract state will never be directly activated,
  46273. * but can provide inherited properties to its common children states.
  46274. * <pre>abstract: true</pre>
  46275. *
  46276. * @param {function=} stateConfig.onEnter
  46277. * <a id='onEnter'></a>
  46278. *
  46279. * Callback function for when a state is entered. Good way
  46280. * to trigger an action or dispatch an event, such as opening a dialog.
  46281. * If minifying your scripts, make sure to explictly annotate this function,
  46282. * because it won't be automatically annotated by your build tools.
  46283. *
  46284. * <pre>onEnter: function(MyService, $stateParams) {
  46285. * MyService.foo($stateParams.myParam);
  46286. * }</pre>
  46287. *
  46288. * @param {function=} stateConfig.onExit
  46289. * <a id='onExit'></a>
  46290. *
  46291. * Callback function for when a state is exited. Good way to
  46292. * trigger an action or dispatch an event, such as opening a dialog.
  46293. * If minifying your scripts, make sure to explictly annotate this function,
  46294. * because it won't be automatically annotated by your build tools.
  46295. *
  46296. * <pre>onExit: function(MyService, $stateParams) {
  46297. * MyService.cleanup($stateParams.myParam);
  46298. * }</pre>
  46299. *
  46300. * @param {boolean=} [stateConfig.reloadOnSearch=true]
  46301. * <a id='reloadOnSearch'></a>
  46302. *
  46303. * If `false`, will not retrigger the same state
  46304. * just because a search/query parameter has changed (via $location.search() or $location.hash()).
  46305. * Useful for when you'd like to modify $location.search() without triggering a reload.
  46306. * <pre>reloadOnSearch: false</pre>
  46307. *
  46308. * @param {object=} stateConfig.data
  46309. * <a id='data'></a>
  46310. *
  46311. * Arbitrary data object, useful for custom configuration. The parent state's `data` is
  46312. * prototypally inherited. In other words, adding a data property to a state adds it to
  46313. * the entire subtree via prototypal inheritance.
  46314. *
  46315. * <pre>data: {
  46316. * requiredRole: 'foo'
  46317. * } </pre>
  46318. *
  46319. * @param {object=} stateConfig.params
  46320. * <a id='params'></a>
  46321. *
  46322. * A map which optionally configures parameters declared in the `url`, or
  46323. * defines additional non-url parameters. For each parameter being
  46324. * configured, add a configuration object keyed to the name of the parameter.
  46325. *
  46326. * Each parameter configuration object may contain the following properties:
  46327. *
  46328. * - ** value ** - {object|function=}: specifies the default value for this
  46329. * parameter. This implicitly sets this parameter as optional.
  46330. *
  46331. * When UI-Router routes to a state and no value is
  46332. * specified for this parameter in the URL or transition, the
  46333. * default value will be used instead. If `value` is a function,
  46334. * it will be injected and invoked, and the return value used.
  46335. *
  46336. * *Note*: `undefined` is treated as "no default value" while `null`
  46337. * is treated as "the default value is `null`".
  46338. *
  46339. * *Shorthand*: If you only need to configure the default value of the
  46340. * parameter, you may use a shorthand syntax. In the **`params`**
  46341. * map, instead mapping the param name to a full parameter configuration
  46342. * object, simply set map it to the default parameter value, e.g.:
  46343. *
  46344. * <pre>// define a parameter's default value
  46345. * params: {
  46346. * param1: { value: "defaultValue" }
  46347. * }
  46348. * // shorthand default values
  46349. * params: {
  46350. * param1: "defaultValue",
  46351. * param2: "param2Default"
  46352. * }</pre>
  46353. *
  46354. * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
  46355. * treated as an array of values. If you specified a Type, the value will be
  46356. * treated as an array of the specified Type. Note: query parameter values
  46357. * default to a special `"auto"` mode.
  46358. *
  46359. * For query parameters in `"auto"` mode, if multiple values for a single parameter
  46360. * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
  46361. * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
  46362. * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
  46363. * value (e.g.: `{ foo: '1' }`).
  46364. *
  46365. * <pre>params: {
  46366. * param1: { array: true }
  46367. * }</pre>
  46368. *
  46369. * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
  46370. * the current parameter value is the same as the default value. If `squash` is not set, it uses the
  46371. * configured default squash policy.
  46372. * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
  46373. *
  46374. * There are three squash settings:
  46375. *
  46376. * - false: The parameter's default value is not squashed. It is encoded and included in the URL
  46377. * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
  46378. * by slashes in the state's `url` declaration, then one of those slashes are omitted.
  46379. * This can allow for cleaner looking URLs.
  46380. * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
  46381. *
  46382. * <pre>params: {
  46383. * param1: {
  46384. * value: "defaultId",
  46385. * squash: true
  46386. * } }
  46387. * // squash "defaultValue" to "~"
  46388. * params: {
  46389. * param1: {
  46390. * value: "defaultValue",
  46391. * squash: "~"
  46392. * } }
  46393. * </pre>
  46394. *
  46395. *
  46396. * @example
  46397. * <pre>
  46398. * // Some state name examples
  46399. *
  46400. * // stateName can be a single top-level name (must be unique).
  46401. * $stateProvider.state("home", {});
  46402. *
  46403. * // Or it can be a nested state name. This state is a child of the
  46404. * // above "home" state.
  46405. * $stateProvider.state("home.newest", {});
  46406. *
  46407. * // Nest states as deeply as needed.
  46408. * $stateProvider.state("home.newest.abc.xyz.inception", {});
  46409. *
  46410. * // state() returns $stateProvider, so you can chain state declarations.
  46411. * $stateProvider
  46412. * .state("home", {})
  46413. * .state("about", {})
  46414. * .state("contacts", {});
  46415. * </pre>
  46416. *
  46417. */
  46418. this.state = state;
  46419. function state(name, definition) {
  46420. /*jshint validthis: true */
  46421. if (isObject(name)) definition = name;
  46422. else definition.name = name;
  46423. registerState(definition);
  46424. return this;
  46425. }
  46426. /**
  46427. * @ngdoc object
  46428. * @name ui.router.state.$state
  46429. *
  46430. * @requires $rootScope
  46431. * @requires $q
  46432. * @requires ui.router.state.$view
  46433. * @requires $injector
  46434. * @requires ui.router.util.$resolve
  46435. * @requires ui.router.state.$stateParams
  46436. * @requires ui.router.router.$urlRouter
  46437. *
  46438. * @property {object} params A param object, e.g. {sectionId: section.id)}, that
  46439. * you'd like to test against the current active state.
  46440. * @property {object} current A reference to the state's config object. However
  46441. * you passed it in. Useful for accessing custom data.
  46442. * @property {object} transition Currently pending transition. A promise that'll
  46443. * resolve or reject.
  46444. *
  46445. * @description
  46446. * `$state` service is responsible for representing states as well as transitioning
  46447. * between them. It also provides interfaces to ask for current state or even states
  46448. * you're coming from.
  46449. */
  46450. this.$get = $get;
  46451. $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
  46452. function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
  46453. var TransitionSuperseded = $q.reject(new Error('transition superseded'));
  46454. var TransitionPrevented = $q.reject(new Error('transition prevented'));
  46455. var TransitionAborted = $q.reject(new Error('transition aborted'));
  46456. var TransitionFailed = $q.reject(new Error('transition failed'));
  46457. // Handles the case where a state which is the target of a transition is not found, and the user
  46458. // can optionally retry or defer the transition
  46459. function handleRedirect(redirect, state, params, options) {
  46460. /**
  46461. * @ngdoc event
  46462. * @name ui.router.state.$state#$stateNotFound
  46463. * @eventOf ui.router.state.$state
  46464. * @eventType broadcast on root scope
  46465. * @description
  46466. * Fired when a requested state **cannot be found** using the provided state name during transition.
  46467. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
  46468. * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
  46469. * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
  46470. * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
  46471. *
  46472. * @param {Object} event Event object.
  46473. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
  46474. * @param {State} fromState Current state object.
  46475. * @param {Object} fromParams Current state params.
  46476. *
  46477. * @example
  46478. *
  46479. * <pre>
  46480. * // somewhere, assume lazy.state has not been defined
  46481. * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
  46482. *
  46483. * // somewhere else
  46484. * $scope.$on('$stateNotFound',
  46485. * function(event, unfoundState, fromState, fromParams){
  46486. * console.log(unfoundState.to); // "lazy.state"
  46487. * console.log(unfoundState.toParams); // {a:1, b:2}
  46488. * console.log(unfoundState.options); // {inherit:false} + default options
  46489. * })
  46490. * </pre>
  46491. */
  46492. var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
  46493. if (evt.defaultPrevented) {
  46494. $urlRouter.update();
  46495. return TransitionAborted;
  46496. }
  46497. if (!evt.retry) {
  46498. return null;
  46499. }
  46500. // Allow the handler to return a promise to defer state lookup retry
  46501. if (options.$retry) {
  46502. $urlRouter.update();
  46503. return TransitionFailed;
  46504. }
  46505. var retryTransition = $state.transition = $q.when(evt.retry);
  46506. retryTransition.then(function() {
  46507. if (retryTransition !== $state.transition) return TransitionSuperseded;
  46508. redirect.options.$retry = true;
  46509. return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
  46510. }, function() {
  46511. return TransitionAborted;
  46512. });
  46513. $urlRouter.update();
  46514. return retryTransition;
  46515. }
  46516. root.locals = { resolve: null, globals: { $stateParams: {} } };
  46517. $state = {
  46518. params: {},
  46519. current: root.self,
  46520. $current: root,
  46521. transition: null
  46522. };
  46523. /**
  46524. * @ngdoc function
  46525. * @name ui.router.state.$state#reload
  46526. * @methodOf ui.router.state.$state
  46527. *
  46528. * @description
  46529. * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired,
  46530. * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).
  46531. *
  46532. * @example
  46533. * <pre>
  46534. * var app angular.module('app', ['ui.router']);
  46535. *
  46536. * app.controller('ctrl', function ($scope, $state) {
  46537. * $scope.reload = function(){
  46538. * $state.reload();
  46539. * }
  46540. * });
  46541. * </pre>
  46542. *
  46543. * `reload()` is just an alias for:
  46544. * <pre>
  46545. * $state.transitionTo($state.current, $stateParams, {
  46546. * reload: true, inherit: false, notify: true
  46547. * });
  46548. * </pre>
  46549. *
  46550. * @returns {promise} A promise representing the state of the new transition. See
  46551. * {@link ui.router.state.$state#methods_go $state.go}.
  46552. */
  46553. $state.reload = function reload() {
  46554. return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });
  46555. };
  46556. /**
  46557. * @ngdoc function
  46558. * @name ui.router.state.$state#go
  46559. * @methodOf ui.router.state.$state
  46560. *
  46561. * @description
  46562. * Convenience method for transitioning to a new state. `$state.go` calls
  46563. * `$state.transitionTo` internally but automatically sets options to
  46564. * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
  46565. * This allows you to easily use an absolute or relative to path and specify
  46566. * only the parameters you'd like to update (while letting unspecified parameters
  46567. * inherit from the currently active ancestor states).
  46568. *
  46569. * @example
  46570. * <pre>
  46571. * var app = angular.module('app', ['ui.router']);
  46572. *
  46573. * app.controller('ctrl', function ($scope, $state) {
  46574. * $scope.changeState = function () {
  46575. * $state.go('contact.detail');
  46576. * };
  46577. * });
  46578. * </pre>
  46579. * <img src='../ngdoc_assets/StateGoExamples.png'/>
  46580. *
  46581. * @param {string} to Absolute state name or relative state path. Some examples:
  46582. *
  46583. * - `$state.go('contact.detail')` - will go to the `contact.detail` state
  46584. * - `$state.go('^')` - will go to a parent state
  46585. * - `$state.go('^.sibling')` - will go to a sibling state
  46586. * - `$state.go('.child.grandchild')` - will go to grandchild state
  46587. *
  46588. * @param {object=} params A map of the parameters that will be sent to the state,
  46589. * will populate $stateParams. Any parameters that are not specified will be inherited from currently
  46590. * defined parameters. This allows, for example, going to a sibling state that shares parameters
  46591. * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
  46592. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
  46593. * will get you all current parameters, etc.
  46594. * @param {object=} options Options object. The options are:
  46595. *
  46596. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  46597. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  46598. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  46599. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  46600. * defines which state to be relative from.
  46601. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  46602. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  46603. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  46604. * use this when you want to force a reload when *everything* is the same, including search params.
  46605. *
  46606. * @returns {promise} A promise representing the state of the new transition.
  46607. *
  46608. * Possible success values:
  46609. *
  46610. * - $state.current
  46611. *
  46612. * <br/>Possible rejection values:
  46613. *
  46614. * - 'transition superseded' - when a newer transition has been started after this one
  46615. * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
  46616. * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
  46617. * when a `$stateNotFound` `event.retry` promise errors.
  46618. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
  46619. * - *resolve error* - when an error has occurred with a `resolve`
  46620. *
  46621. */
  46622. $state.go = function go(to, params, options) {
  46623. return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
  46624. };
  46625. /**
  46626. * @ngdoc function
  46627. * @name ui.router.state.$state#transitionTo
  46628. * @methodOf ui.router.state.$state
  46629. *
  46630. * @description
  46631. * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
  46632. * uses `transitionTo` internally. `$state.go` is recommended in most situations.
  46633. *
  46634. * @example
  46635. * <pre>
  46636. * var app = angular.module('app', ['ui.router']);
  46637. *
  46638. * app.controller('ctrl', function ($scope, $state) {
  46639. * $scope.changeState = function () {
  46640. * $state.transitionTo('contact.detail');
  46641. * };
  46642. * });
  46643. * </pre>
  46644. *
  46645. * @param {string} to State name.
  46646. * @param {object=} toParams A map of the parameters that will be sent to the state,
  46647. * will populate $stateParams.
  46648. * @param {object=} options Options object. The options are:
  46649. *
  46650. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  46651. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  46652. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
  46653. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
  46654. * defines which state to be relative from.
  46655. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  46656. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
  46657. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  46658. * use this when you want to force a reload when *everything* is the same, including search params.
  46659. *
  46660. * @returns {promise} A promise representing the state of the new transition. See
  46661. * {@link ui.router.state.$state#methods_go $state.go}.
  46662. */
  46663. $state.transitionTo = function transitionTo(to, toParams, options) {
  46664. toParams = toParams || {};
  46665. options = extend({
  46666. location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
  46667. }, options || {});
  46668. var from = $state.$current, fromParams = $state.params, fromPath = from.path;
  46669. var evt, toState = findState(to, options.relative);
  46670. if (!isDefined(toState)) {
  46671. var redirect = { to: to, toParams: toParams, options: options };
  46672. var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
  46673. if (redirectResult) {
  46674. return redirectResult;
  46675. }
  46676. // Always retry once if the $stateNotFound was not prevented
  46677. // (handles either redirect changed or state lazy-definition)
  46678. to = redirect.to;
  46679. toParams = redirect.toParams;
  46680. options = redirect.options;
  46681. toState = findState(to, options.relative);
  46682. if (!isDefined(toState)) {
  46683. if (!options.relative) throw new Error("No such state '" + to + "'");
  46684. throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
  46685. }
  46686. }
  46687. if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
  46688. if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
  46689. if (!toState.params.$$validates(toParams)) return TransitionFailed;
  46690. toParams = toState.params.$$values(toParams);
  46691. to = toState;
  46692. var toPath = to.path;
  46693. // Starting from the root of the path, keep all levels that haven't changed
  46694. var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
  46695. if (!options.reload) {
  46696. while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
  46697. locals = toLocals[keep] = state.locals;
  46698. keep++;
  46699. state = toPath[keep];
  46700. }
  46701. }
  46702. // If we're going to the same state and all locals are kept, we've got nothing to do.
  46703. // But clear 'transition', as we still want to cancel any other pending transitions.
  46704. // TODO: We may not want to bump 'transition' if we're called from a location change
  46705. // that we've initiated ourselves, because we might accidentally abort a legitimate
  46706. // transition initiated from code?
  46707. if (shouldTriggerReload(to, from, locals, options)) {
  46708. if (to.self.reloadOnSearch !== false) $urlRouter.update();
  46709. $state.transition = null;
  46710. return $q.when($state.current);
  46711. }
  46712. // Filter parameters before we pass them to event handlers etc.
  46713. toParams = filterByKeys(to.params.$$keys(), toParams || {});
  46714. // Broadcast start event and cancel the transition if requested
  46715. if (options.notify) {
  46716. /**
  46717. * @ngdoc event
  46718. * @name ui.router.state.$state#$stateChangeStart
  46719. * @eventOf ui.router.state.$state
  46720. * @eventType broadcast on root scope
  46721. * @description
  46722. * Fired when the state transition **begins**. You can use `event.preventDefault()`
  46723. * to prevent the transition from happening and then the transition promise will be
  46724. * rejected with a `'transition prevented'` value.
  46725. *
  46726. * @param {Object} event Event object.
  46727. * @param {State} toState The state being transitioned to.
  46728. * @param {Object} toParams The params supplied to the `toState`.
  46729. * @param {State} fromState The current state, pre-transition.
  46730. * @param {Object} fromParams The params supplied to the `fromState`.
  46731. *
  46732. * @example
  46733. *
  46734. * <pre>
  46735. * $rootScope.$on('$stateChangeStart',
  46736. * function(event, toState, toParams, fromState, fromParams){
  46737. * event.preventDefault();
  46738. * // transitionTo() promise will be rejected with
  46739. * // a 'transition prevented' error
  46740. * })
  46741. * </pre>
  46742. */
  46743. if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
  46744. $urlRouter.update();
  46745. return TransitionPrevented;
  46746. }
  46747. }
  46748. // Resolve locals for the remaining states, but don't update any global state just
  46749. // yet -- if anything fails to resolve the current state needs to remain untouched.
  46750. // We also set up an inheritance chain for the locals here. This allows the view directive
  46751. // to quickly look up the correct definition for each view in the current state. Even
  46752. // though we create the locals object itself outside resolveState(), it is initially
  46753. // empty and gets filled asynchronously. We need to keep track of the promise for the
  46754. // (fully resolved) current locals, and pass this down the chain.
  46755. var resolved = $q.when(locals);
  46756. for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
  46757. locals = toLocals[l] = inherit(locals);
  46758. resolved = resolveState(state, toParams, state === to, resolved, locals, options);
  46759. }
  46760. // Once everything is resolved, we are ready to perform the actual transition
  46761. // and return a promise for the new state. We also keep track of what the
  46762. // current promise is, so that we can detect overlapping transitions and
  46763. // keep only the outcome of the last transition.
  46764. var transition = $state.transition = resolved.then(function () {
  46765. var l, entering, exiting;
  46766. if ($state.transition !== transition) return TransitionSuperseded;
  46767. // Exit 'from' states not kept
  46768. for (l = fromPath.length - 1; l >= keep; l--) {
  46769. exiting = fromPath[l];
  46770. if (exiting.self.onExit) {
  46771. $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
  46772. }
  46773. exiting.locals = null;
  46774. }
  46775. // Enter 'to' states not kept
  46776. for (l = keep; l < toPath.length; l++) {
  46777. entering = toPath[l];
  46778. entering.locals = toLocals[l];
  46779. if (entering.self.onEnter) {
  46780. $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
  46781. }
  46782. }
  46783. // Run it again, to catch any transitions in callbacks
  46784. if ($state.transition !== transition) return TransitionSuperseded;
  46785. // Update globals in $state
  46786. $state.$current = to;
  46787. $state.current = to.self;
  46788. $state.params = toParams;
  46789. copy($state.params, $stateParams);
  46790. $state.transition = null;
  46791. if (options.location && to.navigable) {
  46792. $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
  46793. $$avoidResync: true, replace: options.location === 'replace'
  46794. });
  46795. }
  46796. if (options.notify) {
  46797. /**
  46798. * @ngdoc event
  46799. * @name ui.router.state.$state#$stateChangeSuccess
  46800. * @eventOf ui.router.state.$state
  46801. * @eventType broadcast on root scope
  46802. * @description
  46803. * Fired once the state transition is **complete**.
  46804. *
  46805. * @param {Object} event Event object.
  46806. * @param {State} toState The state being transitioned to.
  46807. * @param {Object} toParams The params supplied to the `toState`.
  46808. * @param {State} fromState The current state, pre-transition.
  46809. * @param {Object} fromParams The params supplied to the `fromState`.
  46810. */
  46811. $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
  46812. }
  46813. $urlRouter.update(true);
  46814. return $state.current;
  46815. }, function (error) {
  46816. if ($state.transition !== transition) return TransitionSuperseded;
  46817. $state.transition = null;
  46818. /**
  46819. * @ngdoc event
  46820. * @name ui.router.state.$state#$stateChangeError
  46821. * @eventOf ui.router.state.$state
  46822. * @eventType broadcast on root scope
  46823. * @description
  46824. * Fired when an **error occurs** during transition. It's important to note that if you
  46825. * have any errors in your resolve functions (javascript errors, non-existent services, etc)
  46826. * they will not throw traditionally. You must listen for this $stateChangeError event to
  46827. * catch **ALL** errors.
  46828. *
  46829. * @param {Object} event Event object.
  46830. * @param {State} toState The state being transitioned to.
  46831. * @param {Object} toParams The params supplied to the `toState`.
  46832. * @param {State} fromState The current state, pre-transition.
  46833. * @param {Object} fromParams The params supplied to the `fromState`.
  46834. * @param {Error} error The resolve error object.
  46835. */
  46836. evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
  46837. if (!evt.defaultPrevented) {
  46838. $urlRouter.update();
  46839. }
  46840. return $q.reject(error);
  46841. });
  46842. return transition;
  46843. };
  46844. /**
  46845. * @ngdoc function
  46846. * @name ui.router.state.$state#is
  46847. * @methodOf ui.router.state.$state
  46848. *
  46849. * @description
  46850. * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
  46851. * but only checks for the full state name. If params is supplied then it will be
  46852. * tested for strict equality against the current active params object, so all params
  46853. * must match with none missing and no extras.
  46854. *
  46855. * @example
  46856. * <pre>
  46857. * $state.$current.name = 'contacts.details.item';
  46858. *
  46859. * // absolute name
  46860. * $state.is('contact.details.item'); // returns true
  46861. * $state.is(contactDetailItemStateObject); // returns true
  46862. *
  46863. * // relative name (. and ^), typically from a template
  46864. * // E.g. from the 'contacts.details' template
  46865. * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
  46866. * </pre>
  46867. *
  46868. * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
  46869. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
  46870. * to test against the current active state.
  46871. * @param {object=} options An options object. The options are:
  46872. *
  46873. * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
  46874. * test relative to `options.relative` state (or name).
  46875. *
  46876. * @returns {boolean} Returns true if it is the state.
  46877. */
  46878. $state.is = function is(stateOrName, params, options) {
  46879. options = extend({ relative: $state.$current }, options || {});
  46880. var state = findState(stateOrName, options.relative);
  46881. if (!isDefined(state)) { return undefined; }
  46882. if ($state.$current !== state) { return false; }
  46883. return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;
  46884. };
  46885. /**
  46886. * @ngdoc function
  46887. * @name ui.router.state.$state#includes
  46888. * @methodOf ui.router.state.$state
  46889. *
  46890. * @description
  46891. * A method to determine if the current active state is equal to or is the child of the
  46892. * state stateName. If any params are passed then they will be tested for a match as well.
  46893. * Not all the parameters need to be passed, just the ones you'd like to test for equality.
  46894. *
  46895. * @example
  46896. * Partial and relative names
  46897. * <pre>
  46898. * $state.$current.name = 'contacts.details.item';
  46899. *
  46900. * // Using partial names
  46901. * $state.includes("contacts"); // returns true
  46902. * $state.includes("contacts.details"); // returns true
  46903. * $state.includes("contacts.details.item"); // returns true
  46904. * $state.includes("contacts.list"); // returns false
  46905. * $state.includes("about"); // returns false
  46906. *
  46907. * // Using relative names (. and ^), typically from a template
  46908. * // E.g. from the 'contacts.details' template
  46909. * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
  46910. * </pre>
  46911. *
  46912. * Basic globbing patterns
  46913. * <pre>
  46914. * $state.$current.name = 'contacts.details.item.url';
  46915. *
  46916. * $state.includes("*.details.*.*"); // returns true
  46917. * $state.includes("*.details.**"); // returns true
  46918. * $state.includes("**.item.**"); // returns true
  46919. * $state.includes("*.details.item.url"); // returns true
  46920. * $state.includes("*.details.*.url"); // returns true
  46921. * $state.includes("*.details.*"); // returns false
  46922. * $state.includes("item.**"); // returns false
  46923. * </pre>
  46924. *
  46925. * @param {string} stateOrName A partial name, relative name, or glob pattern
  46926. * to be searched for within the current state name.
  46927. * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
  46928. * that you'd like to test against the current active state.
  46929. * @param {object=} options An options object. The options are:
  46930. *
  46931. * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
  46932. * .includes will test relative to `options.relative` state (or name).
  46933. *
  46934. * @returns {boolean} Returns true if it does include the state
  46935. */
  46936. $state.includes = function includes(stateOrName, params, options) {
  46937. options = extend({ relative: $state.$current }, options || {});
  46938. if (isString(stateOrName) && isGlob(stateOrName)) {
  46939. if (!doesStateMatchGlob(stateOrName)) {
  46940. return false;
  46941. }
  46942. stateOrName = $state.$current.name;
  46943. }
  46944. var state = findState(stateOrName, options.relative);
  46945. if (!isDefined(state)) { return undefined; }
  46946. if (!isDefined($state.$current.includes[state.name])) { return false; }
  46947. return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;
  46948. };
  46949. /**
  46950. * @ngdoc function
  46951. * @name ui.router.state.$state#href
  46952. * @methodOf ui.router.state.$state
  46953. *
  46954. * @description
  46955. * A url generation method that returns the compiled url for the given state populated with the given params.
  46956. *
  46957. * @example
  46958. * <pre>
  46959. * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
  46960. * </pre>
  46961. *
  46962. * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
  46963. * @param {object=} params An object of parameter values to fill the state's required parameters.
  46964. * @param {object=} options Options object. The options are:
  46965. *
  46966. * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
  46967. * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
  46968. * ancestor with a valid url).
  46969. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  46970. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  46971. * defines which state to be relative from.
  46972. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  46973. *
  46974. * @returns {string} compiled state url
  46975. */
  46976. $state.href = function href(stateOrName, params, options) {
  46977. options = extend({
  46978. lossy: true,
  46979. inherit: true,
  46980. absolute: false,
  46981. relative: $state.$current
  46982. }, options || {});
  46983. var state = findState(stateOrName, options.relative);
  46984. if (!isDefined(state)) return null;
  46985. if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
  46986. var nav = (state && options.lossy) ? state.navigable : state;
  46987. if (!nav || nav.url === undefined || nav.url === null) {
  46988. return null;
  46989. }
  46990. return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), {
  46991. absolute: options.absolute
  46992. });
  46993. };
  46994. /**
  46995. * @ngdoc function
  46996. * @name ui.router.state.$state#get
  46997. * @methodOf ui.router.state.$state
  46998. *
  46999. * @description
  47000. * Returns the state configuration object for any specific state or all states.
  47001. *
  47002. * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
  47003. * the requested state. If not provided, returns an array of ALL state configs.
  47004. * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
  47005. * @returns {Object|Array} State configuration object or array of all objects.
  47006. */
  47007. $state.get = function (stateOrName, context) {
  47008. if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });
  47009. var state = findState(stateOrName, context || $state.$current);
  47010. return (state && state.self) ? state.self : null;
  47011. };
  47012. function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
  47013. // Make a restricted $stateParams with only the parameters that apply to this state if
  47014. // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
  47015. // we also need $stateParams to be available for any $injector calls we make during the
  47016. // dependency resolution process.
  47017. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  47018. var locals = { $stateParams: $stateParams };
  47019. // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  47020. // We're also including $stateParams in this; that way the parameters are restricted
  47021. // to the set that should be visible to the state, and are independent of when we update
  47022. // the global $state and $stateParams values.
  47023. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  47024. var promises = [dst.resolve.then(function (globals) {
  47025. dst.globals = globals;
  47026. })];
  47027. if (inherited) promises.push(inherited);
  47028. // Resolve template and dependencies for all views.
  47029. forEach(state.views, function (view, name) {
  47030. var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
  47031. injectables.$template = [ function () {
  47032. return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || '';
  47033. }];
  47034. promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
  47035. // References to the controller (only instantiated at link time)
  47036. if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
  47037. var injectLocals = angular.extend({}, injectables, locals);
  47038. result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
  47039. } else {
  47040. result.$$controller = view.controller;
  47041. }
  47042. // Provide access to the state itself for internal use
  47043. result.$$state = state;
  47044. result.$$controllerAs = view.controllerAs;
  47045. dst[name] = result;
  47046. }));
  47047. });
  47048. // Wait for all the promises and then return the activation object
  47049. return $q.all(promises).then(function (values) {
  47050. return dst;
  47051. });
  47052. }
  47053. return $state;
  47054. }
  47055. function shouldTriggerReload(to, from, locals, options) {
  47056. if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {
  47057. return true;
  47058. }
  47059. }
  47060. }
  47061. angular.module('ui.router.state')
  47062. .value('$stateParams', {})
  47063. .provider('$state', $StateProvider);
  47064. $ViewProvider.$inject = [];
  47065. function $ViewProvider() {
  47066. this.$get = $get;
  47067. /**
  47068. * @ngdoc object
  47069. * @name ui.router.state.$view
  47070. *
  47071. * @requires ui.router.util.$templateFactory
  47072. * @requires $rootScope
  47073. *
  47074. * @description
  47075. *
  47076. */
  47077. $get.$inject = ['$rootScope', '$templateFactory'];
  47078. function $get( $rootScope, $templateFactory) {
  47079. return {
  47080. // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
  47081. /**
  47082. * @ngdoc function
  47083. * @name ui.router.state.$view#load
  47084. * @methodOf ui.router.state.$view
  47085. *
  47086. * @description
  47087. *
  47088. * @param {string} name name
  47089. * @param {object} options option object.
  47090. */
  47091. load: function load(name, options) {
  47092. var result, defaults = {
  47093. template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}
  47094. };
  47095. options = extend(defaults, options);
  47096. if (options.view) {
  47097. result = $templateFactory.fromConfig(options.view, options.params, options.locals);
  47098. }
  47099. if (result && options.notify) {
  47100. /**
  47101. * @ngdoc event
  47102. * @name ui.router.state.$state#$viewContentLoading
  47103. * @eventOf ui.router.state.$view
  47104. * @eventType broadcast on root scope
  47105. * @description
  47106. *
  47107. * Fired once the view **begins loading**, *before* the DOM is rendered.
  47108. *
  47109. * @param {Object} event Event object.
  47110. * @param {Object} viewConfig The view config properties (template, controller, etc).
  47111. *
  47112. * @example
  47113. *
  47114. * <pre>
  47115. * $scope.$on('$viewContentLoading',
  47116. * function(event, viewConfig){
  47117. * // Access to all the view config properties.
  47118. * // and one special property 'targetView'
  47119. * // viewConfig.targetView
  47120. * });
  47121. * </pre>
  47122. */
  47123. $rootScope.$broadcast('$viewContentLoading', options);
  47124. }
  47125. return result;
  47126. }
  47127. };
  47128. }
  47129. }
  47130. angular.module('ui.router.state').provider('$view', $ViewProvider);
  47131. /**
  47132. * @ngdoc object
  47133. * @name ui.router.state.$uiViewScrollProvider
  47134. *
  47135. * @description
  47136. * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
  47137. */
  47138. function $ViewScrollProvider() {
  47139. var useAnchorScroll = false;
  47140. /**
  47141. * @ngdoc function
  47142. * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
  47143. * @methodOf ui.router.state.$uiViewScrollProvider
  47144. *
  47145. * @description
  47146. * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
  47147. * scrolling based on the url anchor.
  47148. */
  47149. this.useAnchorScroll = function () {
  47150. useAnchorScroll = true;
  47151. };
  47152. /**
  47153. * @ngdoc object
  47154. * @name ui.router.state.$uiViewScroll
  47155. *
  47156. * @requires $anchorScroll
  47157. * @requires $timeout
  47158. *
  47159. * @description
  47160. * When called with a jqLite element, it scrolls the element into view (after a
  47161. * `$timeout` so the DOM has time to refresh).
  47162. *
  47163. * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
  47164. * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
  47165. */
  47166. this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
  47167. if (useAnchorScroll) {
  47168. return $anchorScroll;
  47169. }
  47170. return function ($element) {
  47171. $timeout(function () {
  47172. $element[0].scrollIntoView();
  47173. }, 0, false);
  47174. };
  47175. }];
  47176. }
  47177. angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
  47178. /**
  47179. * @ngdoc directive
  47180. * @name ui.router.state.directive:ui-view
  47181. *
  47182. * @requires ui.router.state.$state
  47183. * @requires $compile
  47184. * @requires $controller
  47185. * @requires $injector
  47186. * @requires ui.router.state.$uiViewScroll
  47187. * @requires $document
  47188. *
  47189. * @restrict ECA
  47190. *
  47191. * @description
  47192. * The ui-view directive tells $state where to place your templates.
  47193. *
  47194. * @param {string=} name A view name. The name should be unique amongst the other views in the
  47195. * same state. You can have views of the same name that live in different states.
  47196. *
  47197. * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
  47198. * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
  47199. * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
  47200. * scroll ui-view elements into view when they are populated during a state activation.
  47201. *
  47202. * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
  47203. * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
  47204. *
  47205. * @param {string=} onload Expression to evaluate whenever the view updates.
  47206. *
  47207. * @example
  47208. * A view can be unnamed or named.
  47209. * <pre>
  47210. * <!-- Unnamed -->
  47211. * <div ui-view></div>
  47212. *
  47213. * <!-- Named -->
  47214. * <div ui-view="viewName"></div>
  47215. * </pre>
  47216. *
  47217. * You can only have one unnamed view within any template (or root html). If you are only using a
  47218. * single view and it is unnamed then you can populate it like so:
  47219. * <pre>
  47220. * <div ui-view></div>
  47221. * $stateProvider.state("home", {
  47222. * template: "<h1>HELLO!</h1>"
  47223. * })
  47224. * </pre>
  47225. *
  47226. * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}
  47227. * config property, by name, in this case an empty name:
  47228. * <pre>
  47229. * $stateProvider.state("home", {
  47230. * views: {
  47231. * "": {
  47232. * template: "<h1>HELLO!</h1>"
  47233. * }
  47234. * }
  47235. * })
  47236. * </pre>
  47237. *
  47238. * But typically you'll only use the views property if you name your view or have more than one view
  47239. * in the same template. There's not really a compelling reason to name a view if its the only one,
  47240. * but you could if you wanted, like so:
  47241. * <pre>
  47242. * <div ui-view="main"></div>
  47243. * </pre>
  47244. * <pre>
  47245. * $stateProvider.state("home", {
  47246. * views: {
  47247. * "main": {
  47248. * template: "<h1>HELLO!</h1>"
  47249. * }
  47250. * }
  47251. * })
  47252. * </pre>
  47253. *
  47254. * Really though, you'll use views to set up multiple views:
  47255. * <pre>
  47256. * <div ui-view></div>
  47257. * <div ui-view="chart"></div>
  47258. * <div ui-view="data"></div>
  47259. * </pre>
  47260. *
  47261. * <pre>
  47262. * $stateProvider.state("home", {
  47263. * views: {
  47264. * "": {
  47265. * template: "<h1>HELLO!</h1>"
  47266. * },
  47267. * "chart": {
  47268. * template: "<chart_thing/>"
  47269. * },
  47270. * "data": {
  47271. * template: "<data_thing/>"
  47272. * }
  47273. * }
  47274. * })
  47275. * </pre>
  47276. *
  47277. * Examples for `autoscroll`:
  47278. *
  47279. * <pre>
  47280. * <!-- If autoscroll present with no expression,
  47281. * then scroll ui-view into view -->
  47282. * <ui-view autoscroll/>
  47283. *
  47284. * <!-- If autoscroll present with valid expression,
  47285. * then scroll ui-view into view if expression evaluates to true -->
  47286. * <ui-view autoscroll='true'/>
  47287. * <ui-view autoscroll='false'/>
  47288. * <ui-view autoscroll='scopeVariable'/>
  47289. * </pre>
  47290. */
  47291. $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];
  47292. function $ViewDirective( $state, $injector, $uiViewScroll, $interpolate) {
  47293. function getService() {
  47294. return ($injector.has) ? function(service) {
  47295. return $injector.has(service) ? $injector.get(service) : null;
  47296. } : function(service) {
  47297. try {
  47298. return $injector.get(service);
  47299. } catch (e) {
  47300. return null;
  47301. }
  47302. };
  47303. }
  47304. var service = getService(),
  47305. $animator = service('$animator'),
  47306. $animate = service('$animate');
  47307. // Returns a set of DOM manipulation functions based on which Angular version
  47308. // it should use
  47309. function getRenderer(attrs, scope) {
  47310. var statics = function() {
  47311. return {
  47312. enter: function (element, target, cb) { target.after(element); cb(); },
  47313. leave: function (element, cb) { element.remove(); cb(); }
  47314. };
  47315. };
  47316. if ($animate) {
  47317. return {
  47318. enter: function(element, target, cb) {
  47319. var promise = $animate.enter(element, null, target, cb);
  47320. if (promise && promise.then) promise.then(cb);
  47321. },
  47322. leave: function(element, cb) {
  47323. var promise = $animate.leave(element, cb);
  47324. if (promise && promise.then) promise.then(cb);
  47325. }
  47326. };
  47327. }
  47328. if ($animator) {
  47329. var animate = $animator && $animator(scope, attrs);
  47330. return {
  47331. enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },
  47332. leave: function(element, cb) { animate.leave(element); cb(); }
  47333. };
  47334. }
  47335. return statics();
  47336. }
  47337. var directive = {
  47338. restrict: 'ECA',
  47339. terminal: true,
  47340. priority: 400,
  47341. transclude: 'element',
  47342. compile: function (tElement, tAttrs, $transclude) {
  47343. return function (scope, $element, attrs) {
  47344. var previousEl, currentEl, currentScope, latestLocals,
  47345. onloadExp = attrs.onload || '',
  47346. autoScrollExp = attrs.autoscroll,
  47347. renderer = getRenderer(attrs, scope);
  47348. scope.$on('$stateChangeSuccess', function() {
  47349. updateView(false);
  47350. });
  47351. scope.$on('$viewContentLoading', function() {
  47352. updateView(false);
  47353. });
  47354. updateView(true);
  47355. function cleanupLastView() {
  47356. if (previousEl) {
  47357. previousEl.remove();
  47358. previousEl = null;
  47359. }
  47360. if (currentScope) {
  47361. currentScope.$destroy();
  47362. currentScope = null;
  47363. }
  47364. if (currentEl) {
  47365. renderer.leave(currentEl, function() {
  47366. previousEl = null;
  47367. });
  47368. previousEl = currentEl;
  47369. currentEl = null;
  47370. }
  47371. }
  47372. function updateView(firstTime) {
  47373. var newScope,
  47374. name = getUiViewName(scope, attrs, $element, $interpolate),
  47375. previousLocals = name && $state.$current && $state.$current.locals[name];
  47376. if (!firstTime && previousLocals === latestLocals) return; // nothing to do
  47377. newScope = scope.$new();
  47378. latestLocals = $state.$current.locals[name];
  47379. var clone = $transclude(newScope, function(clone) {
  47380. renderer.enter(clone, $element, function onUiViewEnter() {
  47381. if(currentScope) {
  47382. currentScope.$emit('$viewContentAnimationEnded');
  47383. }
  47384. if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
  47385. $uiViewScroll(clone);
  47386. }
  47387. });
  47388. cleanupLastView();
  47389. });
  47390. currentEl = clone;
  47391. currentScope = newScope;
  47392. /**
  47393. * @ngdoc event
  47394. * @name ui.router.state.directive:ui-view#$viewContentLoaded
  47395. * @eventOf ui.router.state.directive:ui-view
  47396. * @eventType emits on ui-view directive scope
  47397. * @description *
  47398. * Fired once the view is **loaded**, *after* the DOM is rendered.
  47399. *
  47400. * @param {Object} event Event object.
  47401. */
  47402. currentScope.$emit('$viewContentLoaded');
  47403. currentScope.$eval(onloadExp);
  47404. }
  47405. };
  47406. }
  47407. };
  47408. return directive;
  47409. }
  47410. $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
  47411. function $ViewDirectiveFill ( $compile, $controller, $state, $interpolate) {
  47412. return {
  47413. restrict: 'ECA',
  47414. priority: -400,
  47415. compile: function (tElement) {
  47416. var initial = tElement.html();
  47417. return function (scope, $element, attrs) {
  47418. var current = $state.$current,
  47419. name = getUiViewName(scope, attrs, $element, $interpolate),
  47420. locals = current && current.locals[name];
  47421. if (! locals) {
  47422. return;
  47423. }
  47424. $element.data('$uiView', { name: name, state: locals.$$state });
  47425. $element.html(locals.$template ? locals.$template : initial);
  47426. var link = $compile($element.contents());
  47427. if (locals.$$controller) {
  47428. locals.$scope = scope;
  47429. var controller = $controller(locals.$$controller, locals);
  47430. if (locals.$$controllerAs) {
  47431. scope[locals.$$controllerAs] = controller;
  47432. }
  47433. $element.data('$ngControllerController', controller);
  47434. $element.children().data('$ngControllerController', controller);
  47435. }
  47436. link(scope);
  47437. };
  47438. }
  47439. };
  47440. }
  47441. /**
  47442. * Shared ui-view code for both directives:
  47443. * Given scope, element, and its attributes, return the view's name
  47444. */
  47445. function getUiViewName(scope, attrs, element, $interpolate) {
  47446. var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
  47447. var inherited = element.inheritedData('$uiView');
  47448. return name.indexOf('@') >= 0 ? name : (name + '@' + (inherited ? inherited.state.name : ''));
  47449. }
  47450. angular.module('ui.router.state').directive('uiView', $ViewDirective);
  47451. angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
  47452. function parseStateRef(ref, current) {
  47453. var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  47454. if (preparsed) ref = current + '(' + preparsed[1] + ')';
  47455. parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  47456. if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  47457. return { state: parsed[1], paramExpr: parsed[3] || null };
  47458. }
  47459. function stateContext(el) {
  47460. var stateData = el.parent().inheritedData('$uiView');
  47461. if (stateData && stateData.state && stateData.state.name) {
  47462. return stateData.state;
  47463. }
  47464. }
  47465. /**
  47466. * @ngdoc directive
  47467. * @name ui.router.state.directive:ui-sref
  47468. *
  47469. * @requires ui.router.state.$state
  47470. * @requires $timeout
  47471. *
  47472. * @restrict A
  47473. *
  47474. * @description
  47475. * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
  47476. * URL, the directive will automatically generate & update the `href` attribute via
  47477. * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
  47478. * the link will trigger a state transition with optional parameters.
  47479. *
  47480. * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
  47481. * handled natively by the browser.
  47482. *
  47483. * You can also use relative state paths within ui-sref, just like the relative
  47484. * paths passed to `$state.go()`. You just need to be aware that the path is relative
  47485. * to the state that the link lives in, in other words the state that loaded the
  47486. * template containing the link.
  47487. *
  47488. * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
  47489. * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
  47490. * and `reload`.
  47491. *
  47492. * @example
  47493. * Here's an example of how you'd use ui-sref and how it would compile. If you have the
  47494. * following template:
  47495. * <pre>
  47496. * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
  47497. *
  47498. * <ul>
  47499. * <li ng-repeat="contact in contacts">
  47500. * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
  47501. * </li>
  47502. * </ul>
  47503. * </pre>
  47504. *
  47505. * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
  47506. * <pre>
  47507. * <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>
  47508. *
  47509. * <ul>
  47510. * <li ng-repeat="contact in contacts">
  47511. * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
  47512. * </li>
  47513. * <li ng-repeat="contact in contacts">
  47514. * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
  47515. * </li>
  47516. * <li ng-repeat="contact in contacts">
  47517. * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
  47518. * </li>
  47519. * </ul>
  47520. *
  47521. * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
  47522. * </pre>
  47523. *
  47524. * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
  47525. * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
  47526. */
  47527. $StateRefDirective.$inject = ['$state', '$timeout'];
  47528. function $StateRefDirective($state, $timeout) {
  47529. var allowedOptions = ['location', 'inherit', 'reload'];
  47530. return {
  47531. restrict: 'A',
  47532. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  47533. link: function(scope, element, attrs, uiSrefActive) {
  47534. var ref = parseStateRef(attrs.uiSref, $state.current.name);
  47535. var params = null, url = null, base = stateContext(element) || $state.$current;
  47536. var newHref = null, isAnchor = element.prop("tagName") === "A";
  47537. var isForm = element[0].nodeName === "FORM";
  47538. var attr = isForm ? "action" : "href", nav = true;
  47539. var options = { relative: base, inherit: true };
  47540. var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
  47541. angular.forEach(allowedOptions, function(option) {
  47542. if (option in optionsOverride) {
  47543. options[option] = optionsOverride[option];
  47544. }
  47545. });
  47546. var update = function(newVal) {
  47547. if (newVal) params = angular.copy(newVal);
  47548. if (!nav) return;
  47549. newHref = $state.href(ref.state, params, options);
  47550. var activeDirective = uiSrefActive[1] || uiSrefActive[0];
  47551. if (activeDirective) {
  47552. activeDirective.$$setStateInfo(ref.state, params);
  47553. }
  47554. if (newHref === null) {
  47555. nav = false;
  47556. return false;
  47557. }
  47558. attrs.$set(attr, newHref);
  47559. };
  47560. if (ref.paramExpr) {
  47561. scope.$watch(ref.paramExpr, function(newVal, oldVal) {
  47562. if (newVal !== params) update(newVal);
  47563. }, true);
  47564. params = angular.copy(scope.$eval(ref.paramExpr));
  47565. }
  47566. update();
  47567. if (isForm) return;
  47568. element.bind("click", function(e) {
  47569. var button = e.which || e.button;
  47570. if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
  47571. // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
  47572. var transition = $timeout(function() {
  47573. $state.go(ref.state, params, options);
  47574. });
  47575. e.preventDefault();
  47576. // if the state has no URL, ignore one preventDefault from the <a> directive.
  47577. var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
  47578. e.preventDefault = function() {
  47579. if (ignorePreventDefaultCount-- <= 0)
  47580. $timeout.cancel(transition);
  47581. };
  47582. }
  47583. });
  47584. }
  47585. };
  47586. }
  47587. /**
  47588. * @ngdoc directive
  47589. * @name ui.router.state.directive:ui-sref-active
  47590. *
  47591. * @requires ui.router.state.$state
  47592. * @requires ui.router.state.$stateParams
  47593. * @requires $interpolate
  47594. *
  47595. * @restrict A
  47596. *
  47597. * @description
  47598. * A directive working alongside ui-sref to add classes to an element when the
  47599. * related ui-sref directive's state is active, and removing them when it is inactive.
  47600. * The primary use-case is to simplify the special appearance of navigation menus
  47601. * relying on `ui-sref`, by having the "active" state's menu button appear different,
  47602. * distinguishing it from the inactive menu items.
  47603. *
  47604. * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
  47605. * ui-sref-active found at the same level or above the ui-sref will be used.
  47606. *
  47607. * Will activate when the ui-sref's target state or any child state is active. If you
  47608. * need to activate only when the ui-sref target state is active and *not* any of
  47609. * it's children, then you will use
  47610. * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
  47611. *
  47612. * @example
  47613. * Given the following template:
  47614. * <pre>
  47615. * <ul>
  47616. * <li ui-sref-active="active" class="item">
  47617. * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  47618. * </li>
  47619. * </ul>
  47620. * </pre>
  47621. *
  47622. *
  47623. * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
  47624. * the resulting HTML will appear as (note the 'active' class):
  47625. * <pre>
  47626. * <ul>
  47627. * <li ui-sref-active="active" class="item active">
  47628. * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  47629. * </li>
  47630. * </ul>
  47631. * </pre>
  47632. *
  47633. * The class name is interpolated **once** during the directives link time (any further changes to the
  47634. * interpolated value are ignored).
  47635. *
  47636. * Multiple classes may be specified in a space-separated format:
  47637. * <pre>
  47638. * <ul>
  47639. * <li ui-sref-active='class1 class2 class3'>
  47640. * <a ui-sref="app.user">link</a>
  47641. * </li>
  47642. * </ul>
  47643. * </pre>
  47644. */
  47645. /**
  47646. * @ngdoc directive
  47647. * @name ui.router.state.directive:ui-sref-active-eq
  47648. *
  47649. * @requires ui.router.state.$state
  47650. * @requires ui.router.state.$stateParams
  47651. * @requires $interpolate
  47652. *
  47653. * @restrict A
  47654. *
  47655. * @description
  47656. * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
  47657. * when the exact target state used in the `ui-sref` is active; no child states.
  47658. *
  47659. */
  47660. $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
  47661. function $StateRefActiveDirective($state, $stateParams, $interpolate) {
  47662. return {
  47663. restrict: "A",
  47664. controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
  47665. var state, params, activeClass;
  47666. // There probably isn't much point in $observing this
  47667. // uiSrefActive and uiSrefActiveEq share the same directive object with some
  47668. // slight difference in logic routing
  47669. activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
  47670. // Allow uiSref to communicate with uiSrefActive[Equals]
  47671. this.$$setStateInfo = function (newState, newParams) {
  47672. state = $state.get(newState, stateContext($element));
  47673. params = newParams;
  47674. update();
  47675. };
  47676. $scope.$on('$stateChangeSuccess', update);
  47677. // Update route state
  47678. function update() {
  47679. if (isMatch()) {
  47680. $element.addClass(activeClass);
  47681. } else {
  47682. $element.removeClass(activeClass);
  47683. }
  47684. }
  47685. function isMatch() {
  47686. if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
  47687. return state && $state.is(state.name, params);
  47688. } else {
  47689. return state && $state.includes(state.name, params);
  47690. }
  47691. }
  47692. }]
  47693. };
  47694. }
  47695. angular.module('ui.router.state')
  47696. .directive('uiSref', $StateRefDirective)
  47697. .directive('uiSrefActive', $StateRefActiveDirective)
  47698. .directive('uiSrefActiveEq', $StateRefActiveDirective);
  47699. /**
  47700. * @ngdoc filter
  47701. * @name ui.router.state.filter:isState
  47702. *
  47703. * @requires ui.router.state.$state
  47704. *
  47705. * @description
  47706. * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
  47707. */
  47708. $IsStateFilter.$inject = ['$state'];
  47709. function $IsStateFilter($state) {
  47710. var isFilter = function (state) {
  47711. return $state.is(state);
  47712. };
  47713. isFilter.$stateful = true;
  47714. return isFilter;
  47715. }
  47716. /**
  47717. * @ngdoc filter
  47718. * @name ui.router.state.filter:includedByState
  47719. *
  47720. * @requires ui.router.state.$state
  47721. *
  47722. * @description
  47723. * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
  47724. */
  47725. $IncludedByStateFilter.$inject = ['$state'];
  47726. function $IncludedByStateFilter($state) {
  47727. var includesFilter = function (state) {
  47728. return $state.includes(state);
  47729. };
  47730. includesFilter.$stateful = true;
  47731. return includesFilter;
  47732. }
  47733. angular.module('ui.router.state')
  47734. .filter('isState', $IsStateFilter)
  47735. .filter('includedByState', $IncludedByStateFilter);
  47736. })(window, window.angular);
  47737. /*!
  47738. * ionic.bundle.js is a concatenation of:
  47739. * ionic.js, angular.js, angular-animate.js,
  47740. * angular-sanitize.js, angular-ui-router.js,
  47741. * and ionic-angular.js
  47742. */
  47743. /*!
  47744. * Copyright 2015 Drifty Co.
  47745. * http://drifty.com/
  47746. *
  47747. * Ionic, v1.3.4
  47748. * A powerful HTML5 mobile app framework.
  47749. * http://ionicframework.com/
  47750. *
  47751. * By @maxlynch, @benjsperry, @adamdbradley <3
  47752. *
  47753. * Licensed under the MIT license. Please see LICENSE for more information.
  47754. *
  47755. */
  47756. (function() {
  47757. /* eslint no-unused-vars:0 */
  47758. var IonicModule = angular.module('ionic', ['ngAnimate', 'ngSanitize', 'ui.router', 'ngIOS9UIWebViewPatch']),
  47759. extend = angular.extend,
  47760. forEach = angular.forEach,
  47761. isDefined = angular.isDefined,
  47762. isNumber = angular.isNumber,
  47763. isString = angular.isString,
  47764. jqLite = angular.element,
  47765. noop = angular.noop;
  47766. /**
  47767. * @ngdoc service
  47768. * @name $ionicActionSheet
  47769. * @module ionic
  47770. * @description
  47771. * The Action Sheet is a slide-up pane that lets the user choose from a set of options.
  47772. * Dangerous options are highlighted in red and made obvious.
  47773. *
  47774. * There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even
  47775. * hitting escape on the keyboard for desktop testing.
  47776. *
  47777. * ![Action Sheet](http://ionicframework.com.s3.amazonaws.com/docs/controllers/actionSheet.gif)
  47778. *
  47779. * @usage
  47780. * To trigger an Action Sheet in your code, use the $ionicActionSheet service in your angular controllers:
  47781. *
  47782. * ```js
  47783. * angular.module('mySuperApp', ['ionic'])
  47784. * .controller(function($scope, $ionicActionSheet, $timeout) {
  47785. *
  47786. * // Triggered on a button click, or some other target
  47787. * $scope.show = function() {
  47788. *
  47789. * // Show the action sheet
  47790. * var hideSheet = $ionicActionSheet.show({
  47791. * buttons: [
  47792. * { text: '<b>Share</b> This' },
  47793. * { text: 'Move' }
  47794. * ],
  47795. * destructiveText: 'Delete',
  47796. * titleText: 'Modify your album',
  47797. * cancelText: 'Cancel',
  47798. * cancel: function() {
  47799. // add cancel code..
  47800. },
  47801. * buttonClicked: function(index) {
  47802. * return true;
  47803. * }
  47804. * });
  47805. *
  47806. * // For example's sake, hide the sheet after two seconds
  47807. * $timeout(function() {
  47808. * hideSheet();
  47809. * }, 2000);
  47810. *
  47811. * };
  47812. * });
  47813. * ```
  47814. *
  47815. */
  47816. IonicModule
  47817. .factory('$ionicActionSheet', [
  47818. '$rootScope',
  47819. '$compile',
  47820. '$animate',
  47821. '$timeout',
  47822. '$ionicTemplateLoader',
  47823. '$ionicPlatform',
  47824. '$ionicBody',
  47825. 'IONIC_BACK_PRIORITY',
  47826. function($rootScope, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform, $ionicBody, IONIC_BACK_PRIORITY) {
  47827. return {
  47828. show: actionSheet
  47829. };
  47830. /**
  47831. * @ngdoc method
  47832. * @name $ionicActionSheet#show
  47833. * @description
  47834. * Load and return a new action sheet.
  47835. *
  47836. * A new isolated scope will be created for the
  47837. * action sheet and the new element will be appended into the body.
  47838. *
  47839. * @param {object} options The options for this ActionSheet. Properties:
  47840. *
  47841. * - `[Object]` `buttons` Which buttons to show. Each button is an object with a `text` field.
  47842. * - `{string}` `titleText` The title to show on the action sheet.
  47843. * - `{string=}` `cancelText` the text for a 'cancel' button on the action sheet.
  47844. * - `{string=}` `destructiveText` The text for a 'danger' on the action sheet.
  47845. * - `{function=}` `cancel` Called if the cancel button is pressed, the backdrop is tapped or
  47846. * the hardware back button is pressed.
  47847. * - `{function=}` `buttonClicked` Called when one of the non-destructive buttons is clicked,
  47848. * with the index of the button that was clicked and the button object. Return true to close
  47849. * the action sheet, or false to keep it opened.
  47850. * - `{function=}` `destructiveButtonClicked` Called when the destructive button is clicked.
  47851. * Return true to close the action sheet, or false to keep it opened.
  47852. * - `{boolean=}` `cancelOnStateChange` Whether to cancel the actionSheet when navigating
  47853. * to a new state. Default true.
  47854. * - `{string}` `cssClass` The custom CSS class name.
  47855. *
  47856. * @returns {function} `hideSheet` A function which, when called, hides & cancels the action sheet.
  47857. */
  47858. function actionSheet(opts) {
  47859. var scope = $rootScope.$new(true);
  47860. extend(scope, {
  47861. cancel: noop,
  47862. destructiveButtonClicked: noop,
  47863. buttonClicked: noop,
  47864. $deregisterBackButton: noop,
  47865. buttons: [],
  47866. cancelOnStateChange: true
  47867. }, opts || {});
  47868. function textForIcon(text) {
  47869. if (text && /icon/.test(text)) {
  47870. scope.$actionSheetHasIcon = true;
  47871. }
  47872. }
  47873. for (var x = 0; x < scope.buttons.length; x++) {
  47874. textForIcon(scope.buttons[x].text);
  47875. }
  47876. textForIcon(scope.cancelText);
  47877. textForIcon(scope.destructiveText);
  47878. // Compile the template
  47879. var element = scope.element = $compile('<ion-action-sheet ng-class="cssClass" buttons="buttons"></ion-action-sheet>')(scope);
  47880. // Grab the sheet element for animation
  47881. var sheetEl = jqLite(element[0].querySelector('.action-sheet-wrapper'));
  47882. var stateChangeListenDone = scope.cancelOnStateChange ?
  47883. $rootScope.$on('$stateChangeSuccess', function() { scope.cancel(); }) :
  47884. noop;
  47885. // removes the actionSheet from the screen
  47886. scope.removeSheet = function(done) {
  47887. if (scope.removed) return;
  47888. scope.removed = true;
  47889. sheetEl.removeClass('action-sheet-up');
  47890. $timeout(function() {
  47891. // wait to remove this due to a 300ms delay native
  47892. // click which would trigging whatever was underneath this
  47893. $ionicBody.removeClass('action-sheet-open');
  47894. }, 400);
  47895. scope.$deregisterBackButton();
  47896. stateChangeListenDone();
  47897. $animate.removeClass(element, 'active').then(function() {
  47898. scope.$destroy();
  47899. element.remove();
  47900. // scope.cancel.$scope is defined near the bottom
  47901. scope.cancel.$scope = sheetEl = null;
  47902. (done || noop)(opts.buttons);
  47903. });
  47904. };
  47905. scope.showSheet = function(done) {
  47906. if (scope.removed) return;
  47907. $ionicBody.append(element)
  47908. .addClass('action-sheet-open');
  47909. $animate.addClass(element, 'active').then(function() {
  47910. if (scope.removed) return;
  47911. (done || noop)();
  47912. });
  47913. $timeout(function() {
  47914. if (scope.removed) return;
  47915. sheetEl.addClass('action-sheet-up');
  47916. }, 20, false);
  47917. };
  47918. // registerBackButtonAction returns a callback to deregister the action
  47919. scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(
  47920. function() {
  47921. $timeout(scope.cancel);
  47922. },
  47923. IONIC_BACK_PRIORITY.actionSheet
  47924. );
  47925. // called when the user presses the cancel button
  47926. scope.cancel = function() {
  47927. // after the animation is out, call the cancel callback
  47928. scope.removeSheet(opts.cancel);
  47929. };
  47930. scope.buttonClicked = function(index) {
  47931. // Check if the button click event returned true, which means
  47932. // we can close the action sheet
  47933. if (opts.buttonClicked(index, opts.buttons[index]) === true) {
  47934. scope.removeSheet();
  47935. }
  47936. };
  47937. scope.destructiveButtonClicked = function() {
  47938. // Check if the destructive button click event returned true, which means
  47939. // we can close the action sheet
  47940. if (opts.destructiveButtonClicked() === true) {
  47941. scope.removeSheet();
  47942. }
  47943. };
  47944. scope.showSheet();
  47945. // Expose the scope on $ionicActionSheet's return value for the sake
  47946. // of testing it.
  47947. scope.cancel.$scope = scope;
  47948. return scope.cancel;
  47949. }
  47950. }]);
  47951. jqLite.prototype.addClass = function(cssClasses) {
  47952. var x, y, cssClass, el, splitClasses, existingClasses;
  47953. if (cssClasses && cssClasses != 'ng-scope' && cssClasses != 'ng-isolate-scope') {
  47954. for (x = 0; x < this.length; x++) {
  47955. el = this[x];
  47956. if (el.setAttribute) {
  47957. if (cssClasses.indexOf(' ') < 0 && el.classList.add) {
  47958. el.classList.add(cssClasses);
  47959. } else {
  47960. existingClasses = (' ' + (el.getAttribute('class') || '') + ' ')
  47961. .replace(/[\n\t]/g, " ");
  47962. splitClasses = cssClasses.split(' ');
  47963. for (y = 0; y < splitClasses.length; y++) {
  47964. cssClass = splitClasses[y].trim();
  47965. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  47966. existingClasses += cssClass + ' ';
  47967. }
  47968. }
  47969. el.setAttribute('class', existingClasses.trim());
  47970. }
  47971. }
  47972. }
  47973. }
  47974. return this;
  47975. };
  47976. jqLite.prototype.removeClass = function(cssClasses) {
  47977. var x, y, splitClasses, cssClass, el;
  47978. if (cssClasses) {
  47979. for (x = 0; x < this.length; x++) {
  47980. el = this[x];
  47981. if (el.getAttribute) {
  47982. if (cssClasses.indexOf(' ') < 0 && el.classList.remove) {
  47983. el.classList.remove(cssClasses);
  47984. } else {
  47985. splitClasses = cssClasses.split(' ');
  47986. for (y = 0; y < splitClasses.length; y++) {
  47987. cssClass = splitClasses[y];
  47988. el.setAttribute('class', (
  47989. (" " + (el.getAttribute('class') || '') + " ")
  47990. .replace(/[\n\t]/g, " ")
  47991. .replace(" " + cssClass.trim() + " ", " ")).trim()
  47992. );
  47993. }
  47994. }
  47995. }
  47996. }
  47997. }
  47998. return this;
  47999. };
  48000. /**
  48001. * @ngdoc service
  48002. * @name $ionicBackdrop
  48003. * @module ionic
  48004. * @description
  48005. * Shows and hides a backdrop over the UI. Appears behind popups, loading,
  48006. * and other overlays.
  48007. *
  48008. * Often, multiple UI components require a backdrop, but only one backdrop is
  48009. * ever needed in the DOM at a time.
  48010. *
  48011. * Therefore, each component that requires the backdrop to be shown calls
  48012. * `$ionicBackdrop.retain()` when it wants the backdrop, then `$ionicBackdrop.release()`
  48013. * when it is done with the backdrop.
  48014. *
  48015. * For each time `retain` is called, the backdrop will be shown until `release` is called.
  48016. *
  48017. * For example, if `retain` is called three times, the backdrop will be shown until `release`
  48018. * is called three times.
  48019. *
  48020. * **Notes:**
  48021. * - The backdrop service will broadcast 'backdrop.shown' and 'backdrop.hidden' events from the root scope,
  48022. * this is useful for alerting native components not in html.
  48023. *
  48024. * @usage
  48025. *
  48026. * ```js
  48027. * function MyController($scope, $ionicBackdrop, $timeout, $rootScope) {
  48028. * //Show a backdrop for one second
  48029. * $scope.action = function() {
  48030. * $ionicBackdrop.retain();
  48031. * $timeout(function() {
  48032. * $ionicBackdrop.release();
  48033. * }, 1000);
  48034. * };
  48035. *
  48036. * // Execute action on backdrop disappearing
  48037. * $scope.$on('backdrop.hidden', function() {
  48038. * // Execute action
  48039. * });
  48040. *
  48041. * // Execute action on backdrop appearing
  48042. * $scope.$on('backdrop.shown', function() {
  48043. * // Execute action
  48044. * });
  48045. *
  48046. * }
  48047. * ```
  48048. */
  48049. IonicModule
  48050. .factory('$ionicBackdrop', [
  48051. '$document', '$timeout', '$$rAF', '$rootScope',
  48052. function($document, $timeout, $$rAF, $rootScope) {
  48053. var el = jqLite('<div class="backdrop">');
  48054. var backdropHolds = 0;
  48055. $document[0].body.appendChild(el[0]);
  48056. return {
  48057. /**
  48058. * @ngdoc method
  48059. * @name $ionicBackdrop#retain
  48060. * @description Retains the backdrop.
  48061. */
  48062. retain: retain,
  48063. /**
  48064. * @ngdoc method
  48065. * @name $ionicBackdrop#release
  48066. * @description
  48067. * Releases the backdrop.
  48068. */
  48069. release: release,
  48070. getElement: getElement,
  48071. // exposed for testing
  48072. _element: el
  48073. };
  48074. function retain() {
  48075. backdropHolds++;
  48076. if (backdropHolds === 1) {
  48077. el.addClass('visible');
  48078. $rootScope.$broadcast('backdrop.shown');
  48079. $$rAF(function() {
  48080. // If we're still at >0 backdropHolds after async...
  48081. if (backdropHolds >= 1) el.addClass('active');
  48082. });
  48083. }
  48084. }
  48085. function release() {
  48086. if (backdropHolds === 1) {
  48087. el.removeClass('active');
  48088. $rootScope.$broadcast('backdrop.hidden');
  48089. $timeout(function() {
  48090. // If we're still at 0 backdropHolds after async...
  48091. if (backdropHolds === 0) el.removeClass('visible');
  48092. }, 400, false);
  48093. }
  48094. backdropHolds = Math.max(0, backdropHolds - 1);
  48095. }
  48096. function getElement() {
  48097. return el;
  48098. }
  48099. }]);
  48100. /**
  48101. * @private
  48102. */
  48103. IonicModule
  48104. .factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {
  48105. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  48106. return function(scope, attrs, bindDefinition) {
  48107. forEach(bindDefinition || {}, function(definition, scopeName) {
  48108. //Adapted from angular.js $compile
  48109. var match = definition.match(LOCAL_REGEXP) || [],
  48110. attrName = match[3] || scopeName,
  48111. mode = match[1], // @, =, or &
  48112. parentGet,
  48113. unwatch;
  48114. switch (mode) {
  48115. case '@':
  48116. if (!attrs[attrName]) {
  48117. return;
  48118. }
  48119. attrs.$observe(attrName, function(value) {
  48120. scope[scopeName] = value;
  48121. });
  48122. // we trigger an interpolation to ensure
  48123. // the value is there for use immediately
  48124. if (attrs[attrName]) {
  48125. scope[scopeName] = $interpolate(attrs[attrName])(scope);
  48126. }
  48127. break;
  48128. case '=':
  48129. if (!attrs[attrName]) {
  48130. return;
  48131. }
  48132. unwatch = scope.$watch(attrs[attrName], function(value) {
  48133. scope[scopeName] = value;
  48134. });
  48135. //Destroy parent scope watcher when this scope is destroyed
  48136. scope.$on('$destroy', unwatch);
  48137. break;
  48138. case '&':
  48139. /* jshint -W044 */
  48140. if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\(.*?\)'))) {
  48141. throw new Error('& expression binding "' + scopeName + '" looks like it will recursively call "' +
  48142. attrs[attrName] + '" and cause a stack overflow! Please choose a different scopeName.');
  48143. }
  48144. parentGet = $parse(attrs[attrName]);
  48145. scope[scopeName] = function(locals) {
  48146. return parentGet(scope, locals);
  48147. };
  48148. break;
  48149. }
  48150. });
  48151. };
  48152. }]);
  48153. /**
  48154. * @ngdoc service
  48155. * @name $ionicBody
  48156. * @module ionic
  48157. * @description An angular utility service to easily and efficiently
  48158. * add and remove CSS classes from the document's body element.
  48159. */
  48160. IonicModule
  48161. .factory('$ionicBody', ['$document', function($document) {
  48162. return {
  48163. /**
  48164. * @ngdoc method
  48165. * @name $ionicBody#addClass
  48166. * @description Add a class to the document's body element.
  48167. * @param {string} class Each argument will be added to the body element.
  48168. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48169. */
  48170. addClass: function() {
  48171. for (var x = 0; x < arguments.length; x++) {
  48172. $document[0].body.classList.add(arguments[x]);
  48173. }
  48174. return this;
  48175. },
  48176. /**
  48177. * @ngdoc method
  48178. * @name $ionicBody#removeClass
  48179. * @description Remove a class from the document's body element.
  48180. * @param {string} class Each argument will be removed from the body element.
  48181. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48182. */
  48183. removeClass: function() {
  48184. for (var x = 0; x < arguments.length; x++) {
  48185. $document[0].body.classList.remove(arguments[x]);
  48186. }
  48187. return this;
  48188. },
  48189. /**
  48190. * @ngdoc method
  48191. * @name $ionicBody#enableClass
  48192. * @description Similar to the `add` method, except the first parameter accepts a boolean
  48193. * value determining if the class should be added or removed. Rather than writing user code,
  48194. * such as "if true then add the class, else then remove the class", this method can be
  48195. * given a true or false value which reduces redundant code.
  48196. * @param {boolean} shouldEnableClass A true/false value if the class should be added or removed.
  48197. * @param {string} class Each remaining argument would be added or removed depending on
  48198. * the first argument.
  48199. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48200. */
  48201. enableClass: function(shouldEnableClass) {
  48202. var args = Array.prototype.slice.call(arguments).slice(1);
  48203. if (shouldEnableClass) {
  48204. this.addClass.apply(this, args);
  48205. } else {
  48206. this.removeClass.apply(this, args);
  48207. }
  48208. return this;
  48209. },
  48210. /**
  48211. * @ngdoc method
  48212. * @name $ionicBody#append
  48213. * @description Append a child to the document's body.
  48214. * @param {element} element The element to be appended to the body. The passed in element
  48215. * can be either a jqLite element, or a DOM element.
  48216. * @returns {$ionicBody} The $ionicBody service so methods can be chained.
  48217. */
  48218. append: function(ele) {
  48219. $document[0].body.appendChild(ele.length ? ele[0] : ele);
  48220. return this;
  48221. },
  48222. /**
  48223. * @ngdoc method
  48224. * @name $ionicBody#get
  48225. * @description Get the document's body element.
  48226. * @returns {element} Returns the document's body element.
  48227. */
  48228. get: function() {
  48229. return $document[0].body;
  48230. }
  48231. };
  48232. }]);
  48233. IonicModule
  48234. .factory('$ionicClickBlock', [
  48235. '$document',
  48236. '$ionicBody',
  48237. '$timeout',
  48238. function($document, $ionicBody, $timeout) {
  48239. var CSS_HIDE = 'click-block-hide';
  48240. var cbEle, fallbackTimer, pendingShow;
  48241. function preventClick(ev) {
  48242. ev.preventDefault();
  48243. ev.stopPropagation();
  48244. }
  48245. function addClickBlock() {
  48246. if (pendingShow) {
  48247. if (cbEle) {
  48248. cbEle.classList.remove(CSS_HIDE);
  48249. } else {
  48250. cbEle = $document[0].createElement('div');
  48251. cbEle.className = 'click-block';
  48252. $ionicBody.append(cbEle);
  48253. cbEle.addEventListener('touchstart', preventClick);
  48254. cbEle.addEventListener('mousedown', preventClick);
  48255. }
  48256. pendingShow = false;
  48257. }
  48258. }
  48259. function removeClickBlock() {
  48260. cbEle && cbEle.classList.add(CSS_HIDE);
  48261. }
  48262. return {
  48263. show: function(autoExpire) {
  48264. pendingShow = true;
  48265. $timeout.cancel(fallbackTimer);
  48266. fallbackTimer = $timeout(this.hide, autoExpire || 310, false);
  48267. addClickBlock();
  48268. },
  48269. hide: function() {
  48270. pendingShow = false;
  48271. $timeout.cancel(fallbackTimer);
  48272. removeClickBlock();
  48273. }
  48274. };
  48275. }]);
  48276. /**
  48277. * @ngdoc service
  48278. * @name $ionicGesture
  48279. * @module ionic
  48280. * @description An angular service exposing ionic
  48281. * {@link ionic.utility:ionic.EventController}'s gestures.
  48282. */
  48283. IonicModule
  48284. .factory('$ionicGesture', [function() {
  48285. return {
  48286. /**
  48287. * @ngdoc method
  48288. * @name $ionicGesture#on
  48289. * @description Add an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#onGesture}.
  48290. * @param {string} eventType The gesture event to listen for.
  48291. * @param {function(e)} callback The function to call when the gesture
  48292. * happens.
  48293. * @param {element} $element The angular element to listen for the event on.
  48294. * @param {object} options object.
  48295. * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).
  48296. */
  48297. on: function(eventType, cb, $element, options) {
  48298. return window.ionic.onGesture(eventType, cb, $element[0], options);
  48299. },
  48300. /**
  48301. * @ngdoc method
  48302. * @name $ionicGesture#off
  48303. * @description Remove an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#offGesture}.
  48304. * @param {ionic.Gesture} gesture The gesture that should be removed.
  48305. * @param {string} eventType The gesture event to remove the listener for.
  48306. * @param {function(e)} callback The listener to remove.
  48307. */
  48308. off: function(gesture, eventType, cb) {
  48309. return window.ionic.offGesture(gesture, eventType, cb);
  48310. }
  48311. };
  48312. }]);
  48313. /**
  48314. * @ngdoc service
  48315. * @name $ionicHistory
  48316. * @module ionic
  48317. * @description
  48318. * $ionicHistory keeps track of views as the user navigates through an app. Similar to the way a
  48319. * browser behaves, an Ionic app is able to keep track of the previous view, the current view, and
  48320. * the forward view (if there is one). However, a typical web browser only keeps track of one
  48321. * history stack in a linear fashion.
  48322. *
  48323. * Unlike a traditional browser environment, apps and webapps have parallel independent histories,
  48324. * such as with tabs. Should a user navigate few pages deep on one tab, and then switch to a new
  48325. * tab and back, the back button relates not to the previous tab, but to the previous pages
  48326. * visited within _that_ tab.
  48327. *
  48328. * `$ionicHistory` facilitates this parallel history architecture.
  48329. */
  48330. IonicModule
  48331. .factory('$ionicHistory', [
  48332. '$rootScope',
  48333. '$state',
  48334. '$location',
  48335. '$window',
  48336. '$timeout',
  48337. '$ionicViewSwitcher',
  48338. '$ionicNavViewDelegate',
  48339. function($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {
  48340. // history actions while navigating views
  48341. var ACTION_INITIAL_VIEW = 'initialView';
  48342. var ACTION_NEW_VIEW = 'newView';
  48343. var ACTION_MOVE_BACK = 'moveBack';
  48344. var ACTION_MOVE_FORWARD = 'moveForward';
  48345. // direction of navigation
  48346. var DIRECTION_BACK = 'back';
  48347. var DIRECTION_FORWARD = 'forward';
  48348. var DIRECTION_ENTER = 'enter';
  48349. var DIRECTION_EXIT = 'exit';
  48350. var DIRECTION_SWAP = 'swap';
  48351. var DIRECTION_NONE = 'none';
  48352. var stateChangeCounter = 0;
  48353. var lastStateId, nextViewOptions, deregisterStateChangeListener, nextViewExpireTimer, forcedNav;
  48354. var viewHistory = {
  48355. histories: { root: { historyId: 'root', parentHistoryId: null, stack: [], cursor: -1 } },
  48356. views: {},
  48357. backView: null,
  48358. forwardView: null,
  48359. currentView: null
  48360. };
  48361. var View = function() {};
  48362. View.prototype.initialize = function(data) {
  48363. if (data) {
  48364. for (var name in data) this[name] = data[name];
  48365. return this;
  48366. }
  48367. return null;
  48368. };
  48369. View.prototype.go = function() {
  48370. if (this.stateName) {
  48371. return $state.go(this.stateName, this.stateParams);
  48372. }
  48373. if (this.url && this.url !== $location.url()) {
  48374. if (viewHistory.backView === this) {
  48375. return $window.history.go(-1);
  48376. } else if (viewHistory.forwardView === this) {
  48377. return $window.history.go(1);
  48378. }
  48379. $location.url(this.url);
  48380. }
  48381. return null;
  48382. };
  48383. View.prototype.destroy = function() {
  48384. if (this.scope) {
  48385. this.scope.$destroy && this.scope.$destroy();
  48386. this.scope = null;
  48387. }
  48388. };
  48389. function getViewById(viewId) {
  48390. return (viewId ? viewHistory.views[ viewId ] : null);
  48391. }
  48392. function getBackView(view) {
  48393. return (view ? getViewById(view.backViewId) : null);
  48394. }
  48395. function getForwardView(view) {
  48396. return (view ? getViewById(view.forwardViewId) : null);
  48397. }
  48398. function getHistoryById(historyId) {
  48399. return (historyId ? viewHistory.histories[ historyId ] : null);
  48400. }
  48401. function getHistory(scope) {
  48402. var histObj = getParentHistoryObj(scope);
  48403. if (!viewHistory.histories[ histObj.historyId ]) {
  48404. // this history object exists in parent scope, but doesn't
  48405. // exist in the history data yet
  48406. viewHistory.histories[ histObj.historyId ] = {
  48407. historyId: histObj.historyId,
  48408. parentHistoryId: getParentHistoryObj(histObj.scope.$parent).historyId,
  48409. stack: [],
  48410. cursor: -1
  48411. };
  48412. }
  48413. return getHistoryById(histObj.historyId);
  48414. }
  48415. function getParentHistoryObj(scope) {
  48416. var parentScope = scope;
  48417. while (parentScope) {
  48418. if (parentScope.hasOwnProperty('$historyId')) {
  48419. // this parent scope has a historyId
  48420. return { historyId: parentScope.$historyId, scope: parentScope };
  48421. }
  48422. // nothing found keep climbing up
  48423. parentScope = parentScope.$parent;
  48424. }
  48425. // no history for the parent, use the root
  48426. return { historyId: 'root', scope: $rootScope };
  48427. }
  48428. function setNavViews(viewId) {
  48429. viewHistory.currentView = getViewById(viewId);
  48430. viewHistory.backView = getBackView(viewHistory.currentView);
  48431. viewHistory.forwardView = getForwardView(viewHistory.currentView);
  48432. }
  48433. function getCurrentStateId() {
  48434. var id;
  48435. if ($state && $state.current && $state.current.name) {
  48436. id = $state.current.name;
  48437. if ($state.params) {
  48438. for (var key in $state.params) {
  48439. if ($state.params.hasOwnProperty(key) && $state.params[key]) {
  48440. id += "_" + key + "=" + $state.params[key];
  48441. }
  48442. }
  48443. }
  48444. return id;
  48445. }
  48446. // if something goes wrong make sure its got a unique stateId
  48447. return ionic.Utils.nextUid();
  48448. }
  48449. function getCurrentStateParams() {
  48450. var rtn;
  48451. if ($state && $state.params) {
  48452. for (var key in $state.params) {
  48453. if ($state.params.hasOwnProperty(key)) {
  48454. rtn = rtn || {};
  48455. rtn[key] = $state.params[key];
  48456. }
  48457. }
  48458. }
  48459. return rtn;
  48460. }
  48461. return {
  48462. register: function(parentScope, viewLocals) {
  48463. var currentStateId = getCurrentStateId(),
  48464. hist = getHistory(parentScope),
  48465. currentView = viewHistory.currentView,
  48466. backView = viewHistory.backView,
  48467. forwardView = viewHistory.forwardView,
  48468. viewId = null,
  48469. action = null,
  48470. direction = DIRECTION_NONE,
  48471. historyId = hist.historyId,
  48472. url = $location.url(),
  48473. tmp, x, ele;
  48474. if (lastStateId !== currentStateId) {
  48475. lastStateId = currentStateId;
  48476. stateChangeCounter++;
  48477. }
  48478. if (forcedNav) {
  48479. // we've previously set exactly what to do
  48480. viewId = forcedNav.viewId;
  48481. action = forcedNav.action;
  48482. direction = forcedNav.direction;
  48483. forcedNav = null;
  48484. } else if (backView && backView.stateId === currentStateId) {
  48485. // they went back one, set the old current view as a forward view
  48486. viewId = backView.viewId;
  48487. historyId = backView.historyId;
  48488. action = ACTION_MOVE_BACK;
  48489. if (backView.historyId === currentView.historyId) {
  48490. // went back in the same history
  48491. direction = DIRECTION_BACK;
  48492. } else if (currentView) {
  48493. direction = DIRECTION_EXIT;
  48494. tmp = getHistoryById(backView.historyId);
  48495. if (tmp && tmp.parentHistoryId === currentView.historyId) {
  48496. direction = DIRECTION_ENTER;
  48497. } else {
  48498. tmp = getHistoryById(currentView.historyId);
  48499. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48500. direction = DIRECTION_SWAP;
  48501. }
  48502. }
  48503. }
  48504. } else if (forwardView && forwardView.stateId === currentStateId) {
  48505. // they went to the forward one, set the forward view to no longer a forward view
  48506. viewId = forwardView.viewId;
  48507. historyId = forwardView.historyId;
  48508. action = ACTION_MOVE_FORWARD;
  48509. if (forwardView.historyId === currentView.historyId) {
  48510. direction = DIRECTION_FORWARD;
  48511. } else if (currentView) {
  48512. direction = DIRECTION_EXIT;
  48513. if (currentView.historyId === hist.parentHistoryId) {
  48514. direction = DIRECTION_ENTER;
  48515. } else {
  48516. tmp = getHistoryById(currentView.historyId);
  48517. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48518. direction = DIRECTION_SWAP;
  48519. }
  48520. }
  48521. }
  48522. tmp = getParentHistoryObj(parentScope);
  48523. if (forwardView.historyId && tmp.scope) {
  48524. // if a history has already been created by the forward view then make sure it stays the same
  48525. tmp.scope.$historyId = forwardView.historyId;
  48526. historyId = forwardView.historyId;
  48527. }
  48528. } else if (currentView && currentView.historyId !== historyId &&
  48529. hist.cursor > -1 && hist.stack.length > 0 && hist.cursor < hist.stack.length &&
  48530. hist.stack[hist.cursor].stateId === currentStateId) {
  48531. // they just changed to a different history and the history already has views in it
  48532. var switchToView = hist.stack[hist.cursor];
  48533. viewId = switchToView.viewId;
  48534. historyId = switchToView.historyId;
  48535. action = ACTION_MOVE_BACK;
  48536. direction = DIRECTION_SWAP;
  48537. tmp = getHistoryById(currentView.historyId);
  48538. if (tmp && tmp.parentHistoryId === historyId) {
  48539. direction = DIRECTION_EXIT;
  48540. } else {
  48541. tmp = getHistoryById(historyId);
  48542. if (tmp && tmp.parentHistoryId === currentView.historyId) {
  48543. direction = DIRECTION_ENTER;
  48544. }
  48545. }
  48546. // if switching to a different history, and the history of the view we're switching
  48547. // to has an existing back view from a different history than itself, then
  48548. // it's back view would be better represented using the current view as its back view
  48549. tmp = getViewById(switchToView.backViewId);
  48550. if (tmp && switchToView.historyId !== tmp.historyId) {
  48551. // the new view is being removed from it's old position in the history and being placed at the top,
  48552. // so we need to update any views that reference it as a backview, otherwise there will be infinitely loops
  48553. var viewIds = Object.keys(viewHistory.views);
  48554. viewIds.forEach(function(viewId) {
  48555. var view = viewHistory.views[viewId];
  48556. if ((view.backViewId === switchToView.viewId) && (view.historyId !== switchToView.historyId)) {
  48557. view.backViewId = null;
  48558. }
  48559. });
  48560. hist.stack[hist.cursor].backViewId = currentView.viewId;
  48561. }
  48562. } else {
  48563. // create an element from the viewLocals template
  48564. ele = $ionicViewSwitcher.createViewEle(viewLocals);
  48565. if (this.isAbstractEle(ele, viewLocals)) {
  48566. return {
  48567. action: 'abstractView',
  48568. direction: DIRECTION_NONE,
  48569. ele: ele
  48570. };
  48571. }
  48572. // set a new unique viewId
  48573. viewId = ionic.Utils.nextUid();
  48574. if (currentView) {
  48575. // set the forward view if there is a current view (ie: if its not the first view)
  48576. currentView.forwardViewId = viewId;
  48577. action = ACTION_NEW_VIEW;
  48578. // check if there is a new forward view within the same history
  48579. if (forwardView && currentView.stateId !== forwardView.stateId &&
  48580. currentView.historyId === forwardView.historyId) {
  48581. // they navigated to a new view but the stack already has a forward view
  48582. // since its a new view remove any forwards that existed
  48583. tmp = getHistoryById(forwardView.historyId);
  48584. if (tmp) {
  48585. // the forward has a history
  48586. for (x = tmp.stack.length - 1; x >= forwardView.index; x--) {
  48587. // starting from the end destroy all forwards in this history from this point
  48588. var stackItem = tmp.stack[x];
  48589. stackItem && stackItem.destroy && stackItem.destroy();
  48590. tmp.stack.splice(x);
  48591. }
  48592. historyId = forwardView.historyId;
  48593. }
  48594. }
  48595. // its only moving forward if its in the same history
  48596. if (hist.historyId === currentView.historyId) {
  48597. direction = DIRECTION_FORWARD;
  48598. } else if (currentView.historyId !== hist.historyId) {
  48599. // DB: this is a new view in a different tab
  48600. direction = DIRECTION_ENTER;
  48601. tmp = getHistoryById(currentView.historyId);
  48602. if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {
  48603. direction = DIRECTION_SWAP;
  48604. } else {
  48605. tmp = getHistoryById(tmp.parentHistoryId);
  48606. if (tmp && tmp.historyId === hist.historyId) {
  48607. direction = DIRECTION_EXIT;
  48608. }
  48609. }
  48610. }
  48611. } else {
  48612. // there's no current view, so this must be the initial view
  48613. action = ACTION_INITIAL_VIEW;
  48614. }
  48615. if (stateChangeCounter < 2) {
  48616. // views that were spun up on the first load should not animate
  48617. direction = DIRECTION_NONE;
  48618. }
  48619. // add the new view
  48620. viewHistory.views[viewId] = this.createView({
  48621. viewId: viewId,
  48622. index: hist.stack.length,
  48623. historyId: hist.historyId,
  48624. backViewId: (currentView && currentView.viewId ? currentView.viewId : null),
  48625. forwardViewId: null,
  48626. stateId: currentStateId,
  48627. stateName: this.currentStateName(),
  48628. stateParams: getCurrentStateParams(),
  48629. url: url,
  48630. canSwipeBack: canSwipeBack(ele, viewLocals)
  48631. });
  48632. // add the new view to this history's stack
  48633. hist.stack.push(viewHistory.views[viewId]);
  48634. }
  48635. deregisterStateChangeListener && deregisterStateChangeListener();
  48636. $timeout.cancel(nextViewExpireTimer);
  48637. if (nextViewOptions) {
  48638. if (nextViewOptions.disableAnimate) direction = DIRECTION_NONE;
  48639. if (nextViewOptions.disableBack) viewHistory.views[viewId].backViewId = null;
  48640. if (nextViewOptions.historyRoot) {
  48641. for (x = 0; x < hist.stack.length; x++) {
  48642. if (hist.stack[x].viewId === viewId) {
  48643. hist.stack[x].index = 0;
  48644. hist.stack[x].backViewId = hist.stack[x].forwardViewId = null;
  48645. } else {
  48646. delete viewHistory.views[hist.stack[x].viewId];
  48647. }
  48648. }
  48649. hist.stack = [viewHistory.views[viewId]];
  48650. }
  48651. nextViewOptions = null;
  48652. }
  48653. setNavViews(viewId);
  48654. if (viewHistory.backView && historyId == viewHistory.backView.historyId && currentStateId == viewHistory.backView.stateId && url == viewHistory.backView.url) {
  48655. for (x = 0; x < hist.stack.length; x++) {
  48656. if (hist.stack[x].viewId == viewId) {
  48657. action = 'dupNav';
  48658. direction = DIRECTION_NONE;
  48659. if (x > 0) {
  48660. hist.stack[x - 1].forwardViewId = null;
  48661. }
  48662. viewHistory.forwardView = null;
  48663. viewHistory.currentView.index = viewHistory.backView.index;
  48664. viewHistory.currentView.backViewId = viewHistory.backView.backViewId;
  48665. viewHistory.backView = getBackView(viewHistory.backView);
  48666. hist.stack.splice(x, 1);
  48667. break;
  48668. }
  48669. }
  48670. }
  48671. hist.cursor = viewHistory.currentView.index;
  48672. return {
  48673. viewId: viewId,
  48674. action: action,
  48675. direction: direction,
  48676. historyId: historyId,
  48677. enableBack: this.enabledBack(viewHistory.currentView),
  48678. isHistoryRoot: (viewHistory.currentView.index === 0),
  48679. ele: ele
  48680. };
  48681. },
  48682. registerHistory: function(scope) {
  48683. scope.$historyId = ionic.Utils.nextUid();
  48684. },
  48685. createView: function(data) {
  48686. var newView = new View();
  48687. return newView.initialize(data);
  48688. },
  48689. getViewById: getViewById,
  48690. /**
  48691. * @ngdoc method
  48692. * @name $ionicHistory#viewHistory
  48693. * @description The app's view history data, such as all the views and histories, along
  48694. * with how they are ordered and linked together within the navigation stack.
  48695. * @returns {object} Returns an object containing the apps view history data.
  48696. */
  48697. viewHistory: function() {
  48698. return viewHistory;
  48699. },
  48700. /**
  48701. * @ngdoc method
  48702. * @name $ionicHistory#currentView
  48703. * @description The app's current view.
  48704. * @returns {object} Returns the current view.
  48705. */
  48706. currentView: function(view) {
  48707. if (arguments.length) {
  48708. viewHistory.currentView = view;
  48709. }
  48710. return viewHistory.currentView;
  48711. },
  48712. /**
  48713. * @ngdoc method
  48714. * @name $ionicHistory#currentHistoryId
  48715. * @description The ID of the history stack which is the parent container of the current view.
  48716. * @returns {string} Returns the current history ID.
  48717. */
  48718. currentHistoryId: function() {
  48719. return viewHistory.currentView ? viewHistory.currentView.historyId : null;
  48720. },
  48721. /**
  48722. * @ngdoc method
  48723. * @name $ionicHistory#currentTitle
  48724. * @description Gets and sets the current view's title.
  48725. * @param {string=} val The title to update the current view with.
  48726. * @returns {string} Returns the current view's title.
  48727. */
  48728. currentTitle: function(val) {
  48729. if (viewHistory.currentView) {
  48730. if (arguments.length) {
  48731. viewHistory.currentView.title = val;
  48732. }
  48733. return viewHistory.currentView.title;
  48734. }
  48735. },
  48736. /**
  48737. * @ngdoc method
  48738. * @name $ionicHistory#backView
  48739. * @description Returns the view that was before the current view in the history stack.
  48740. * If the user navigated from View A to View B, then View A would be the back view, and
  48741. * View B would be the current view.
  48742. * @returns {object} Returns the back view.
  48743. */
  48744. backView: function(view) {
  48745. if (arguments.length) {
  48746. viewHistory.backView = view;
  48747. }
  48748. return viewHistory.backView;
  48749. },
  48750. /**
  48751. * @ngdoc method
  48752. * @name $ionicHistory#backTitle
  48753. * @description Gets the back view's title.
  48754. * @returns {string} Returns the back view's title.
  48755. */
  48756. backTitle: function(view) {
  48757. var backView = (view && getViewById(view.backViewId)) || viewHistory.backView;
  48758. return backView && backView.title;
  48759. },
  48760. /**
  48761. * @ngdoc method
  48762. * @name $ionicHistory#forwardView
  48763. * @description Returns the view that was in front of the current view in the history stack.
  48764. * A forward view would exist if the user navigated from View A to View B, then
  48765. * navigated back to View A. At this point then View B would be the forward view, and View
  48766. * A would be the current view.
  48767. * @returns {object} Returns the forward view.
  48768. */
  48769. forwardView: function(view) {
  48770. if (arguments.length) {
  48771. viewHistory.forwardView = view;
  48772. }
  48773. return viewHistory.forwardView;
  48774. },
  48775. /**
  48776. * @ngdoc method
  48777. * @name $ionicHistory#currentStateName
  48778. * @description Returns the current state name.
  48779. * @returns {string}
  48780. */
  48781. currentStateName: function() {
  48782. return ($state && $state.current ? $state.current.name : null);
  48783. },
  48784. isCurrentStateNavView: function(navView) {
  48785. return !!($state && $state.current && $state.current.views && $state.current.views[navView]);
  48786. },
  48787. goToHistoryRoot: function(historyId) {
  48788. if (historyId) {
  48789. var hist = getHistoryById(historyId);
  48790. if (hist && hist.stack.length) {
  48791. if (viewHistory.currentView && viewHistory.currentView.viewId === hist.stack[0].viewId) {
  48792. return;
  48793. }
  48794. forcedNav = {
  48795. viewId: hist.stack[0].viewId,
  48796. action: ACTION_MOVE_BACK,
  48797. direction: DIRECTION_BACK
  48798. };
  48799. hist.stack[0].go();
  48800. }
  48801. }
  48802. },
  48803. /**
  48804. * @ngdoc method
  48805. * @name $ionicHistory#goBack
  48806. * @param {number=} backCount Optional negative integer setting how many views to go
  48807. * back. By default it'll go back one view by using the value `-1`. To go back two
  48808. * views you would use `-2`. If the number goes farther back than the number of views
  48809. * in the current history's stack then it'll go to the first view in the current history's
  48810. * stack. If the number is zero or greater then it'll do nothing. It also does not
  48811. * cross history stacks, meaning it can only go as far back as the current history.
  48812. * @description Navigates the app to the back view, if a back view exists.
  48813. */
  48814. goBack: function(backCount) {
  48815. if (isDefined(backCount) && backCount !== -1) {
  48816. if (backCount > -1) return;
  48817. var currentHistory = viewHistory.histories[this.currentHistoryId()];
  48818. var newCursor = currentHistory.cursor + backCount + 1;
  48819. if (newCursor < 1) {
  48820. newCursor = 1;
  48821. }
  48822. currentHistory.cursor = newCursor;
  48823. setNavViews(currentHistory.stack[newCursor].viewId);
  48824. var cursor = newCursor - 1;
  48825. var clearStateIds = [];
  48826. var fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);
  48827. while (fwdView) {
  48828. clearStateIds.push(fwdView.stateId || fwdView.viewId);
  48829. cursor++;
  48830. if (cursor >= currentHistory.stack.length) break;
  48831. fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);
  48832. }
  48833. var self = this;
  48834. if (clearStateIds.length) {
  48835. $timeout(function() {
  48836. self.clearCache(clearStateIds);
  48837. }, 300);
  48838. }
  48839. }
  48840. viewHistory.backView && viewHistory.backView.go();
  48841. },
  48842. /**
  48843. * @ngdoc method
  48844. * @name $ionicHistory#removeBackView
  48845. * @description Remove the previous view from the history completely, including the
  48846. * cached element and scope (if they exist).
  48847. */
  48848. removeBackView: function() {
  48849. var self = this;
  48850. var currentHistory = viewHistory.histories[this.currentHistoryId()];
  48851. var currentCursor = currentHistory.cursor;
  48852. var currentView = currentHistory.stack[currentCursor];
  48853. var backView = currentHistory.stack[currentCursor - 1];
  48854. var replacementView = currentHistory.stack[currentCursor - 2];
  48855. // fail if we dont have enough views in the history
  48856. if (!backView || !replacementView) {
  48857. return;
  48858. }
  48859. // remove the old backView and the cached element/scope
  48860. currentHistory.stack.splice(currentCursor - 1, 1);
  48861. self.clearCache([backView.viewId]);
  48862. // make the replacementView and currentView point to each other (bypass the old backView)
  48863. currentView.backViewId = replacementView.viewId;
  48864. currentView.index = currentView.index - 1;
  48865. replacementView.forwardViewId = currentView.viewId;
  48866. // update the cursor and set new backView
  48867. viewHistory.backView = replacementView;
  48868. currentHistory.currentCursor += -1;
  48869. },
  48870. enabledBack: function(view) {
  48871. var backView = getBackView(view);
  48872. return !!(backView && backView.historyId === view.historyId);
  48873. },
  48874. /**
  48875. * @ngdoc method
  48876. * @name $ionicHistory#clearHistory
  48877. * @description Clears out the app's entire history, except for the current view.
  48878. */
  48879. clearHistory: function() {
  48880. var
  48881. histories = viewHistory.histories,
  48882. currentView = viewHistory.currentView;
  48883. if (histories) {
  48884. for (var historyId in histories) {
  48885. if (histories[historyId].stack) {
  48886. histories[historyId].stack = [];
  48887. histories[historyId].cursor = -1;
  48888. }
  48889. if (currentView && currentView.historyId === historyId) {
  48890. currentView.backViewId = currentView.forwardViewId = null;
  48891. histories[historyId].stack.push(currentView);
  48892. } else if (histories[historyId].destroy) {
  48893. histories[historyId].destroy();
  48894. }
  48895. }
  48896. }
  48897. for (var viewId in viewHistory.views) {
  48898. if (viewId !== currentView.viewId) {
  48899. delete viewHistory.views[viewId];
  48900. }
  48901. }
  48902. if (currentView) {
  48903. setNavViews(currentView.viewId);
  48904. }
  48905. },
  48906. /**
  48907. * @ngdoc method
  48908. * @name $ionicHistory#clearCache
  48909. * @return promise
  48910. * @description Removes all cached views within every {@link ionic.directive:ionNavView}.
  48911. * This both removes the view element from the DOM, and destroy it's scope.
  48912. */
  48913. clearCache: function(stateIds) {
  48914. return $timeout(function() {
  48915. $ionicNavViewDelegate._instances.forEach(function(instance) {
  48916. instance.clearCache(stateIds);
  48917. });
  48918. });
  48919. },
  48920. /**
  48921. * @ngdoc method
  48922. * @name $ionicHistory#nextViewOptions
  48923. * @description Sets options for the next view. This method can be useful to override
  48924. * certain view/transition defaults right before a view transition happens. For example,
  48925. * the {@link ionic.directive:menuClose} directive uses this method internally to ensure
  48926. * an animated view transition does not happen when a side menu is open, and also sets
  48927. * the next view as the root of its history stack. After the transition these options
  48928. * are set back to null.
  48929. *
  48930. * Available options:
  48931. *
  48932. * * `disableAnimate`: Do not animate the next transition.
  48933. * * `disableBack`: The next view should forget its back view, and set it to null.
  48934. * * `historyRoot`: The next view should become the root view in its history stack.
  48935. *
  48936. * ```js
  48937. * $ionicHistory.nextViewOptions({
  48938. * disableAnimate: true,
  48939. * disableBack: true
  48940. * });
  48941. * ```
  48942. */
  48943. nextViewOptions: function(opts) {
  48944. deregisterStateChangeListener && deregisterStateChangeListener();
  48945. if (arguments.length) {
  48946. $timeout.cancel(nextViewExpireTimer);
  48947. if (opts === null) {
  48948. nextViewOptions = opts;
  48949. } else {
  48950. nextViewOptions = nextViewOptions || {};
  48951. extend(nextViewOptions, opts);
  48952. if (nextViewOptions.expire) {
  48953. deregisterStateChangeListener = $rootScope.$on('$stateChangeSuccess', function() {
  48954. nextViewExpireTimer = $timeout(function() {
  48955. nextViewOptions = null;
  48956. }, nextViewOptions.expire);
  48957. });
  48958. }
  48959. }
  48960. }
  48961. return nextViewOptions;
  48962. },
  48963. isAbstractEle: function(ele, viewLocals) {
  48964. if (viewLocals && viewLocals.$$state && viewLocals.$$state.self['abstract']) {
  48965. return true;
  48966. }
  48967. return !!(ele && (isAbstractTag(ele) || isAbstractTag(ele.children())));
  48968. },
  48969. isActiveScope: function(scope) {
  48970. if (!scope) return false;
  48971. var climbScope = scope;
  48972. var currentHistoryId = this.currentHistoryId();
  48973. var foundHistoryId;
  48974. while (climbScope) {
  48975. if (climbScope.$$disconnected) {
  48976. return false;
  48977. }
  48978. if (!foundHistoryId && climbScope.hasOwnProperty('$historyId')) {
  48979. foundHistoryId = true;
  48980. }
  48981. if (currentHistoryId) {
  48982. if (climbScope.hasOwnProperty('$historyId') && currentHistoryId == climbScope.$historyId) {
  48983. return true;
  48984. }
  48985. if (climbScope.hasOwnProperty('$activeHistoryId')) {
  48986. if (currentHistoryId == climbScope.$activeHistoryId) {
  48987. if (climbScope.hasOwnProperty('$historyId')) {
  48988. return true;
  48989. }
  48990. if (!foundHistoryId) {
  48991. return true;
  48992. }
  48993. }
  48994. }
  48995. }
  48996. if (foundHistoryId && climbScope.hasOwnProperty('$activeHistoryId')) {
  48997. foundHistoryId = false;
  48998. }
  48999. climbScope = climbScope.$parent;
  49000. }
  49001. return currentHistoryId ? currentHistoryId == 'root' : true;
  49002. }
  49003. };
  49004. function isAbstractTag(ele) {
  49005. return ele && ele.length && /ion-side-menus|ion-tabs/i.test(ele[0].tagName);
  49006. }
  49007. function canSwipeBack(ele, viewLocals) {
  49008. if (viewLocals && viewLocals.$$state && viewLocals.$$state.self.canSwipeBack === false) {
  49009. return false;
  49010. }
  49011. if (ele && ele.attr('can-swipe-back') === 'false') {
  49012. return false;
  49013. }
  49014. var eleChild = ele.find('ion-view');
  49015. if (eleChild && eleChild.attr('can-swipe-back') === 'false') {
  49016. return false;
  49017. }
  49018. return true;
  49019. }
  49020. }])
  49021. .run([
  49022. '$rootScope',
  49023. '$state',
  49024. '$location',
  49025. '$document',
  49026. '$ionicPlatform',
  49027. '$ionicHistory',
  49028. 'IONIC_BACK_PRIORITY',
  49029. function($rootScope, $state, $location, $document, $ionicPlatform, $ionicHistory, IONIC_BACK_PRIORITY) {
  49030. // always reset the keyboard state when change stage
  49031. $rootScope.$on('$ionicView.beforeEnter', function() {
  49032. ionic.keyboard && ionic.keyboard.hide && ionic.keyboard.hide();
  49033. });
  49034. $rootScope.$on('$ionicHistory.change', function(e, data) {
  49035. if (!data) return null;
  49036. var viewHistory = $ionicHistory.viewHistory();
  49037. var hist = (data.historyId ? viewHistory.histories[ data.historyId ] : null);
  49038. if (hist && hist.cursor > -1 && hist.cursor < hist.stack.length) {
  49039. // the history they're going to already exists
  49040. // go to it's last view in its stack
  49041. var view = hist.stack[ hist.cursor ];
  49042. return view.go(data);
  49043. }
  49044. // this history does not have a URL, but it does have a uiSref
  49045. // figure out its URL from the uiSref
  49046. if (!data.url && data.uiSref) {
  49047. data.url = $state.href(data.uiSref);
  49048. }
  49049. if (data.url) {
  49050. // don't let it start with a #, messes with $location.url()
  49051. if (data.url.indexOf('#') === 0) {
  49052. data.url = data.url.replace('#', '');
  49053. }
  49054. if (data.url !== $location.url()) {
  49055. // we've got a good URL, ready GO!
  49056. $location.url(data.url);
  49057. }
  49058. }
  49059. });
  49060. $rootScope.$ionicGoBack = function(backCount) {
  49061. $ionicHistory.goBack(backCount);
  49062. };
  49063. // Set the document title when a new view is shown
  49064. $rootScope.$on('$ionicView.afterEnter', function(ev, data) {
  49065. if (data && data.title) {
  49066. $document[0].title = data.title;
  49067. }
  49068. });
  49069. // Triggered when devices with a hardware back button (Android) is clicked by the user
  49070. // This is a Cordova/Phonegap platform specifc method
  49071. function onHardwareBackButton(e) {
  49072. var backView = $ionicHistory.backView();
  49073. if (backView) {
  49074. // there is a back view, go to it
  49075. backView.go();
  49076. } else {
  49077. // there is no back view, so close the app instead
  49078. ionic.Platform.exitApp();
  49079. }
  49080. e.preventDefault();
  49081. return false;
  49082. }
  49083. $ionicPlatform.registerBackButtonAction(
  49084. onHardwareBackButton,
  49085. IONIC_BACK_PRIORITY.view
  49086. );
  49087. }]);
  49088. /**
  49089. * @ngdoc provider
  49090. * @name $ionicConfigProvider
  49091. * @module ionic
  49092. * @description
  49093. * Ionic automatically takes platform configurations into account to adjust things like what
  49094. * transition style to use and whether tab icons should show on the top or bottom. For example,
  49095. * iOS will move forward by transitioning the entering view from right to center and the leaving
  49096. * view from center to left. However, Android will transition with the entering view going from
  49097. * bottom to center, covering the previous view, which remains stationary. It should be noted
  49098. * that when a platform is not iOS or Android, then it'll default to iOS. So if you are
  49099. * developing on a desktop browser, it's going to take on iOS default configs.
  49100. *
  49101. * These configs can be changed using the `$ionicConfigProvider` during the configuration phase
  49102. * of your app. Additionally, `$ionicConfig` can also set and get config values during the run
  49103. * phase and within the app itself.
  49104. *
  49105. * By default, all base config variables are set to `'platform'`, which means it'll take on the
  49106. * default config of the platform on which it's running. Config variables can be set at this
  49107. * level so all platforms follow the same setting, rather than its platform config.
  49108. * The following code would set the same config variable for all platforms:
  49109. *
  49110. * ```js
  49111. * $ionicConfigProvider.views.maxCache(10);
  49112. * ```
  49113. *
  49114. * Additionally, each platform can have its own config within the `$ionicConfigProvider.platform`
  49115. * property. The config below would only apply to Android devices.
  49116. *
  49117. * ```js
  49118. * $ionicConfigProvider.platform.android.views.maxCache(5);
  49119. * ```
  49120. *
  49121. * @usage
  49122. * ```js
  49123. * var myApp = angular.module('reallyCoolApp', ['ionic']);
  49124. *
  49125. * myApp.config(function($ionicConfigProvider) {
  49126. * $ionicConfigProvider.views.maxCache(5);
  49127. *
  49128. * // note that you can also chain configs
  49129. * $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left');
  49130. * });
  49131. * ```
  49132. */
  49133. /**
  49134. * @ngdoc method
  49135. * @name $ionicConfigProvider#views.transition
  49136. * @description Animation style when transitioning between views. Default `platform`.
  49137. *
  49138. * @param {string} transition Which style of view transitioning to use.
  49139. *
  49140. * * `platform`: Dynamically choose the correct transition style depending on the platform
  49141. * the app is running from. If the platform is not `ios` or `android` then it will default
  49142. * to `ios`.
  49143. * * `ios`: iOS style transition.
  49144. * * `android`: Android style transition.
  49145. * * `none`: Do not perform animated transitions.
  49146. *
  49147. * @returns {string} value
  49148. */
  49149. /**
  49150. * @ngdoc method
  49151. * @name $ionicConfigProvider#views.maxCache
  49152. * @description Maximum number of view elements to cache in the DOM. When the max number is
  49153. * exceeded, the view with the longest time period since it was accessed is removed. Views that
  49154. * stay in the DOM cache the view's scope, current state, and scroll position. The scope is
  49155. * disconnected from the `$watch` cycle when it is cached and reconnected when it enters again.
  49156. * When the maximum cache is `0`, the leaving view's element will be removed from the DOM after
  49157. * each view transition, and the next time the same view is shown, it will have to re-compile,
  49158. * attach to the DOM, and link the element again. This disables caching, in effect.
  49159. * @param {number} maxNumber Maximum number of views to retain. Default `10`.
  49160. * @returns {number} How many views Ionic will hold onto until the a view is removed.
  49161. */
  49162. /**
  49163. * @ngdoc method
  49164. * @name $ionicConfigProvider#views.forwardCache
  49165. * @description By default, when navigating, views that were recently visited are cached, and
  49166. * the same instance data and DOM elements are referenced when navigating back. However, when
  49167. * navigating back in the history, the "forward" views are removed from the cache. If you
  49168. * navigate forward to the same view again, it'll create a new DOM element and controller
  49169. * instance. Basically, any forward views are reset each time. Set this config to `true` to have
  49170. * forward views cached and not reset on each load.
  49171. * @param {boolean} value
  49172. * @returns {boolean}
  49173. */
  49174. /**
  49175. * @ngdoc method
  49176. * @name $ionicConfigProvider#views.swipeBackEnabled
  49177. * @description By default on iOS devices, swipe to go back functionality is enabled by default.
  49178. * This method can be used to disable it globally, or on a per-view basis.
  49179. * Note: This functionality is only supported on iOS.
  49180. * @param {boolean} value
  49181. * @returns {boolean}
  49182. */
  49183. /**
  49184. * @ngdoc method
  49185. * @name $ionicConfigProvider#scrolling.jsScrolling
  49186. * @description Whether to use JS or Native scrolling. Defaults to native scrolling. Setting this to
  49187. * `true` has the same effect as setting each `ion-content` to have `overflow-scroll='false'`.
  49188. * @param {boolean} value Defaults to `false` as of Ionic 1.2
  49189. * @returns {boolean}
  49190. */
  49191. /**
  49192. * @ngdoc method
  49193. * @name $ionicConfigProvider#backButton.icon
  49194. * @description Back button icon.
  49195. * @param {string} value
  49196. * @returns {string}
  49197. */
  49198. /**
  49199. * @ngdoc method
  49200. * @name $ionicConfigProvider#backButton.text
  49201. * @description Back button text.
  49202. * @param {string} value Defaults to `Back`.
  49203. * @returns {string}
  49204. */
  49205. /**
  49206. * @ngdoc method
  49207. * @name $ionicConfigProvider#backButton.previousTitleText
  49208. * @description If the previous title text should become the back button text. This
  49209. * is the default for iOS.
  49210. * @param {boolean} value
  49211. * @returns {boolean}
  49212. */
  49213. /**
  49214. * @ngdoc method
  49215. * @name $ionicConfigProvider#form.checkbox
  49216. * @description Checkbox style. Android defaults to `square` and iOS defaults to `circle`.
  49217. * @param {string} value
  49218. * @returns {string}
  49219. */
  49220. /**
  49221. * @ngdoc method
  49222. * @name $ionicConfigProvider#form.toggle
  49223. * @description Toggle item style. Android defaults to `small` and iOS defaults to `large`.
  49224. * @param {string} value
  49225. * @returns {string}
  49226. */
  49227. /**
  49228. * @ngdoc method
  49229. * @name $ionicConfigProvider#spinner.icon
  49230. * @description Default spinner icon to use.
  49231. * @param {string} value Can be: `android`, `ios`, `ios-small`, `bubbles`, `circles`, `crescent`,
  49232. * `dots`, `lines`, `ripple`, or `spiral`.
  49233. * @returns {string}
  49234. */
  49235. /**
  49236. * @ngdoc method
  49237. * @name $ionicConfigProvider#tabs.style
  49238. * @description Tab style. Android defaults to `striped` and iOS defaults to `standard`.
  49239. * @param {string} value Available values include `striped` and `standard`.
  49240. * @returns {string}
  49241. */
  49242. /**
  49243. * @ngdoc method
  49244. * @name $ionicConfigProvider#tabs.position
  49245. * @description Tab position. Android defaults to `top` and iOS defaults to `bottom`.
  49246. * @param {string} value Available values include `top` and `bottom`.
  49247. * @returns {string}
  49248. */
  49249. /**
  49250. * @ngdoc method
  49251. * @name $ionicConfigProvider#templates.maxPrefetch
  49252. * @description Sets the maximum number of templates to prefetch from the templateUrls defined in
  49253. * $stateProvider.state. If set to `0`, the user will have to wait
  49254. * for a template to be fetched the first time when navigating to a new page. Default `30`.
  49255. * @param {integer} value Max number of template to prefetch from the templateUrls defined in
  49256. * `$stateProvider.state()`.
  49257. * @returns {integer}
  49258. */
  49259. /**
  49260. * @ngdoc method
  49261. * @name $ionicConfigProvider#navBar.alignTitle
  49262. * @description Which side of the navBar to align the title. Default `center`.
  49263. *
  49264. * @param {string} value side of the navBar to align the title.
  49265. *
  49266. * * `platform`: Dynamically choose the correct title style depending on the platform
  49267. * the app is running from. If the platform is `ios`, it will default to `center`.
  49268. * If the platform is `android`, it will default to `left`. If the platform is not
  49269. * `ios` or `android`, it will default to `center`.
  49270. *
  49271. * * `left`: Left align the title in the navBar
  49272. * * `center`: Center align the title in the navBar
  49273. * * `right`: Right align the title in the navBar.
  49274. *
  49275. * @returns {string} value
  49276. */
  49277. /**
  49278. * @ngdoc method
  49279. * @name $ionicConfigProvider#navBar.positionPrimaryButtons
  49280. * @description Which side of the navBar to align the primary navBar buttons. Default `left`.
  49281. *
  49282. * @param {string} value side of the navBar to align the primary navBar buttons.
  49283. *
  49284. * * `platform`: Dynamically choose the correct title style depending on the platform
  49285. * the app is running from. If the platform is `ios`, it will default to `left`.
  49286. * If the platform is `android`, it will default to `right`. If the platform is not
  49287. * `ios` or `android`, it will default to `left`.
  49288. *
  49289. * * `left`: Left align the primary navBar buttons in the navBar
  49290. * * `right`: Right align the primary navBar buttons in the navBar.
  49291. *
  49292. * @returns {string} value
  49293. */
  49294. /**
  49295. * @ngdoc method
  49296. * @name $ionicConfigProvider#navBar.positionSecondaryButtons
  49297. * @description Which side of the navBar to align the secondary navBar buttons. Default `right`.
  49298. *
  49299. * @param {string} value side of the navBar to align the secondary navBar buttons.
  49300. *
  49301. * * `platform`: Dynamically choose the correct title style depending on the platform
  49302. * the app is running from. If the platform is `ios`, it will default to `right`.
  49303. * If the platform is `android`, it will default to `right`. If the platform is not
  49304. * `ios` or `android`, it will default to `right`.
  49305. *
  49306. * * `left`: Left align the secondary navBar buttons in the navBar
  49307. * * `right`: Right align the secondary navBar buttons in the navBar.
  49308. *
  49309. * @returns {string} value
  49310. */
  49311. IonicModule
  49312. .provider('$ionicConfig', function() {
  49313. var provider = this;
  49314. provider.platform = {};
  49315. var PLATFORM = 'platform';
  49316. var configProperties = {
  49317. views: {
  49318. maxCache: PLATFORM,
  49319. forwardCache: PLATFORM,
  49320. transition: PLATFORM,
  49321. swipeBackEnabled: PLATFORM,
  49322. swipeBackHitWidth: PLATFORM
  49323. },
  49324. navBar: {
  49325. alignTitle: PLATFORM,
  49326. positionPrimaryButtons: PLATFORM,
  49327. positionSecondaryButtons: PLATFORM,
  49328. transition: PLATFORM
  49329. },
  49330. backButton: {
  49331. icon: PLATFORM,
  49332. text: PLATFORM,
  49333. previousTitleText: PLATFORM
  49334. },
  49335. form: {
  49336. checkbox: PLATFORM,
  49337. toggle: PLATFORM
  49338. },
  49339. scrolling: {
  49340. jsScrolling: PLATFORM
  49341. },
  49342. spinner: {
  49343. icon: PLATFORM
  49344. },
  49345. tabs: {
  49346. style: PLATFORM,
  49347. position: PLATFORM
  49348. },
  49349. templates: {
  49350. maxPrefetch: PLATFORM
  49351. },
  49352. platform: {}
  49353. };
  49354. createConfig(configProperties, provider, '');
  49355. // Default
  49356. // -------------------------
  49357. setPlatformConfig('default', {
  49358. views: {
  49359. maxCache: 10,
  49360. forwardCache: false,
  49361. transition: 'ios',
  49362. swipeBackEnabled: true,
  49363. swipeBackHitWidth: 45
  49364. },
  49365. navBar: {
  49366. alignTitle: 'center',
  49367. positionPrimaryButtons: 'left',
  49368. positionSecondaryButtons: 'right',
  49369. transition: 'view'
  49370. },
  49371. backButton: {
  49372. icon: 'ion-ios-arrow-back',
  49373. text: 'Back',
  49374. previousTitleText: true
  49375. },
  49376. form: {
  49377. checkbox: 'circle',
  49378. toggle: 'large'
  49379. },
  49380. scrolling: {
  49381. jsScrolling: true
  49382. },
  49383. spinner: {
  49384. icon: 'ios'
  49385. },
  49386. tabs: {
  49387. style: 'standard',
  49388. position: 'bottom'
  49389. },
  49390. templates: {
  49391. maxPrefetch: 30
  49392. }
  49393. });
  49394. // iOS (it is the default already)
  49395. // -------------------------
  49396. setPlatformConfig('ios', {});
  49397. // Android
  49398. // -------------------------
  49399. setPlatformConfig('android', {
  49400. views: {
  49401. transition: 'android',
  49402. swipeBackEnabled: false
  49403. },
  49404. navBar: {
  49405. alignTitle: 'left',
  49406. positionPrimaryButtons: 'right',
  49407. positionSecondaryButtons: 'right'
  49408. },
  49409. backButton: {
  49410. icon: 'ion-android-arrow-back',
  49411. text: false,
  49412. previousTitleText: false
  49413. },
  49414. form: {
  49415. checkbox: 'square',
  49416. toggle: 'small'
  49417. },
  49418. spinner: {
  49419. icon: 'android'
  49420. },
  49421. tabs: {
  49422. style: 'striped',
  49423. position: 'top'
  49424. },
  49425. scrolling: {
  49426. jsScrolling: false
  49427. }
  49428. });
  49429. // Windows Phone
  49430. // -------------------------
  49431. setPlatformConfig('windowsphone', {
  49432. //scrolling: {
  49433. // jsScrolling: false
  49434. //}
  49435. spinner: {
  49436. icon: 'android'
  49437. }
  49438. });
  49439. provider.transitions = {
  49440. views: {},
  49441. navBar: {}
  49442. };
  49443. // iOS Transitions
  49444. // -----------------------
  49445. provider.transitions.views.ios = function(enteringEle, leavingEle, direction, shouldAnimate) {
  49446. function setStyles(ele, opacity, x, boxShadowOpacity) {
  49447. var css = {};
  49448. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;
  49449. css.opacity = opacity;
  49450. if (boxShadowOpacity > -1) {
  49451. css.boxShadow = '0 0 10px rgba(0,0,0,' + (d.shouldAnimate ? boxShadowOpacity * 0.45 : 0.3) + ')';
  49452. }
  49453. css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';
  49454. ionic.DomUtil.cachedStyles(ele, css);
  49455. }
  49456. var d = {
  49457. run: function(step) {
  49458. if (direction == 'forward') {
  49459. setStyles(enteringEle, 1, (1 - step) * 99, 1 - step); // starting at 98% prevents a flicker
  49460. setStyles(leavingEle, (1 - 0.1 * step), step * -33, -1);
  49461. } else if (direction == 'back') {
  49462. setStyles(enteringEle, (1 - 0.1 * (1 - step)), (1 - step) * -33, -1);
  49463. setStyles(leavingEle, 1, step * 100, 1 - step);
  49464. } else {
  49465. // swap, enter, exit
  49466. setStyles(enteringEle, 1, 0, -1);
  49467. setStyles(leavingEle, 0, 0, -1);
  49468. }
  49469. },
  49470. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49471. };
  49472. return d;
  49473. };
  49474. provider.transitions.navBar.ios = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {
  49475. function setStyles(ctrl, opacity, titleX, backTextX) {
  49476. var css = {};
  49477. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : '0ms';
  49478. css.opacity = opacity === 1 ? '' : opacity;
  49479. ctrl.setCss('buttons-left', css);
  49480. ctrl.setCss('buttons-right', css);
  49481. ctrl.setCss('back-button', css);
  49482. css[ionic.CSS.TRANSFORM] = 'translate3d(' + backTextX + 'px,0,0)';
  49483. ctrl.setCss('back-text', css);
  49484. css[ionic.CSS.TRANSFORM] = 'translate3d(' + titleX + 'px,0,0)';
  49485. ctrl.setCss('title', css);
  49486. }
  49487. function enter(ctrlA, ctrlB, step) {
  49488. if (!ctrlA || !ctrlB) return;
  49489. var titleX = (ctrlA.titleTextX() + ctrlA.titleWidth()) * (1 - step);
  49490. var backTextX = (ctrlB && (ctrlB.titleTextX() - ctrlA.backButtonTextLeft()) * (1 - step)) || 0;
  49491. setStyles(ctrlA, step, titleX, backTextX);
  49492. }
  49493. function leave(ctrlA, ctrlB, step) {
  49494. if (!ctrlA || !ctrlB) return;
  49495. var titleX = (-(ctrlA.titleTextX() - ctrlB.backButtonTextLeft()) - (ctrlA.titleLeftRight())) * step;
  49496. setStyles(ctrlA, 1 - step, titleX, 0);
  49497. }
  49498. var d = {
  49499. run: function(step) {
  49500. var enteringHeaderCtrl = enteringHeaderBar.controller();
  49501. var leavingHeaderCtrl = leavingHeaderBar && leavingHeaderBar.controller();
  49502. if (d.direction == 'back') {
  49503. leave(enteringHeaderCtrl, leavingHeaderCtrl, 1 - step);
  49504. enter(leavingHeaderCtrl, enteringHeaderCtrl, 1 - step);
  49505. } else {
  49506. enter(enteringHeaderCtrl, leavingHeaderCtrl, step);
  49507. leave(leavingHeaderCtrl, enteringHeaderCtrl, step);
  49508. }
  49509. },
  49510. direction: direction,
  49511. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49512. };
  49513. return d;
  49514. };
  49515. // Android Transitions
  49516. // -----------------------
  49517. provider.transitions.views.android = function(enteringEle, leavingEle, direction, shouldAnimate) {
  49518. shouldAnimate = shouldAnimate && (direction == 'forward' || direction == 'back');
  49519. function setStyles(ele, x, opacity) {
  49520. var css = {};
  49521. css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;
  49522. css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';
  49523. css.opacity = opacity;
  49524. ionic.DomUtil.cachedStyles(ele, css);
  49525. }
  49526. var d = {
  49527. run: function(step) {
  49528. if (direction == 'forward') {
  49529. setStyles(enteringEle, (1 - step) * 99, 1); // starting at 98% prevents a flicker
  49530. setStyles(leavingEle, step * -100, 1);
  49531. } else if (direction == 'back') {
  49532. setStyles(enteringEle, (1 - step) * -100, 1);
  49533. setStyles(leavingEle, step * 100, 1);
  49534. } else {
  49535. // swap, enter, exit
  49536. setStyles(enteringEle, 0, 1);
  49537. setStyles(leavingEle, 0, 0);
  49538. }
  49539. },
  49540. shouldAnimate: shouldAnimate
  49541. };
  49542. return d;
  49543. };
  49544. provider.transitions.navBar.android = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {
  49545. function setStyles(ctrl, opacity) {
  49546. if (!ctrl) return;
  49547. var css = {};
  49548. css.opacity = opacity === 1 ? '' : opacity;
  49549. ctrl.setCss('buttons-left', css);
  49550. ctrl.setCss('buttons-right', css);
  49551. ctrl.setCss('back-button', css);
  49552. ctrl.setCss('back-text', css);
  49553. ctrl.setCss('title', css);
  49554. }
  49555. return {
  49556. run: function(step) {
  49557. setStyles(enteringHeaderBar.controller(), step);
  49558. setStyles(leavingHeaderBar && leavingHeaderBar.controller(), 1 - step);
  49559. },
  49560. shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')
  49561. };
  49562. };
  49563. // No Transition
  49564. // -----------------------
  49565. provider.transitions.views.none = function(enteringEle, leavingEle) {
  49566. return {
  49567. run: function(step) {
  49568. provider.transitions.views.android(enteringEle, leavingEle, false, false).run(step);
  49569. },
  49570. shouldAnimate: false
  49571. };
  49572. };
  49573. provider.transitions.navBar.none = function(enteringHeaderBar, leavingHeaderBar) {
  49574. return {
  49575. run: function(step) {
  49576. provider.transitions.navBar.ios(enteringHeaderBar, leavingHeaderBar, false, false).run(step);
  49577. provider.transitions.navBar.android(enteringHeaderBar, leavingHeaderBar, false, false).run(step);
  49578. },
  49579. shouldAnimate: false
  49580. };
  49581. };
  49582. // private: used to set platform configs
  49583. function setPlatformConfig(platformName, platformConfigs) {
  49584. configProperties.platform[platformName] = platformConfigs;
  49585. provider.platform[platformName] = {};
  49586. addConfig(configProperties, configProperties.platform[platformName]);
  49587. createConfig(configProperties.platform[platformName], provider.platform[platformName], '');
  49588. }
  49589. // private: used to recursively add new platform configs
  49590. function addConfig(configObj, platformObj) {
  49591. for (var n in configObj) {
  49592. if (n != PLATFORM && configObj.hasOwnProperty(n)) {
  49593. if (angular.isObject(configObj[n])) {
  49594. if (!isDefined(platformObj[n])) {
  49595. platformObj[n] = {};
  49596. }
  49597. addConfig(configObj[n], platformObj[n]);
  49598. } else if (!isDefined(platformObj[n])) {
  49599. platformObj[n] = null;
  49600. }
  49601. }
  49602. }
  49603. }
  49604. // private: create methods for each config to get/set
  49605. function createConfig(configObj, providerObj, platformPath) {
  49606. forEach(configObj, function(value, namespace) {
  49607. if (angular.isObject(configObj[namespace])) {
  49608. // recursively drill down the config object so we can create a method for each one
  49609. providerObj[namespace] = {};
  49610. createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);
  49611. } else {
  49612. // create a method for the provider/config methods that will be exposed
  49613. providerObj[namespace] = function(newValue) {
  49614. if (arguments.length) {
  49615. configObj[namespace] = newValue;
  49616. return providerObj;
  49617. }
  49618. if (configObj[namespace] == PLATFORM) {
  49619. // if the config is set to 'platform', then get this config's platform value
  49620. var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);
  49621. if (platformConfig || platformConfig === false) {
  49622. return platformConfig;
  49623. }
  49624. // didnt find a specific platform config, now try the default
  49625. return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);
  49626. }
  49627. return configObj[namespace];
  49628. };
  49629. }
  49630. });
  49631. }
  49632. function stringObj(obj, str) {
  49633. str = str.split(".");
  49634. for (var i = 0; i < str.length; i++) {
  49635. if (obj && isDefined(obj[str[i]])) {
  49636. obj = obj[str[i]];
  49637. } else {
  49638. return null;
  49639. }
  49640. }
  49641. return obj;
  49642. }
  49643. provider.setPlatformConfig = setPlatformConfig;
  49644. // private: Service definition for internal Ionic use
  49645. /**
  49646. * @ngdoc service
  49647. * @name $ionicConfig
  49648. * @module ionic
  49649. * @private
  49650. */
  49651. provider.$get = function() {
  49652. return provider;
  49653. };
  49654. })
  49655. // Fix for URLs in Cordova apps on Windows Phone
  49656. // http://blogs.msdn.com/b/msdn_answers/archive/2015/02/10/
  49657. // running-cordova-apps-on-windows-and-windows-phone-8-1-using-ionic-angularjs-and-other-frameworks.aspx
  49658. .config(['$compileProvider', function($compileProvider) {
  49659. $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|sms|tel|geo|ftp|mailto|file|ghttps?|ms-appx-web|ms-appx|x-wmapp0):/);
  49660. $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|ftp|file|content|blob|ms-appx|ms-appx-web|x-wmapp0):|data:image\//);
  49661. }]);
  49662. var LOADING_TPL =
  49663. '<div class="loading-container">' +
  49664. '<div class="loading">' +
  49665. '</div>' +
  49666. '</div>';
  49667. /**
  49668. * @ngdoc service
  49669. * @name $ionicLoading
  49670. * @module ionic
  49671. * @description
  49672. * An overlay that can be used to indicate activity while blocking user
  49673. * interaction.
  49674. *
  49675. * @usage
  49676. * ```js
  49677. * angular.module('LoadingApp', ['ionic'])
  49678. * .controller('LoadingCtrl', function($scope, $ionicLoading) {
  49679. * $scope.show = function() {
  49680. * $ionicLoading.show({
  49681. * template: 'Loading...',
  49682. * duration: 3000
  49683. * }).then(function(){
  49684. * console.log("The loading indicator is now displayed");
  49685. * });
  49686. * };
  49687. * $scope.hide = function(){
  49688. * $ionicLoading.hide().then(function(){
  49689. * console.log("The loading indicator is now hidden");
  49690. * });
  49691. * };
  49692. * });
  49693. * ```
  49694. */
  49695. /**
  49696. * @ngdoc object
  49697. * @name $ionicLoadingConfig
  49698. * @module ionic
  49699. * @description
  49700. * Set the default options to be passed to the {@link ionic.service:$ionicLoading} service.
  49701. *
  49702. * @usage
  49703. * ```js
  49704. * var app = angular.module('myApp', ['ionic'])
  49705. * app.constant('$ionicLoadingConfig', {
  49706. * template: 'Default Loading Template...'
  49707. * });
  49708. * app.controller('AppCtrl', function($scope, $ionicLoading) {
  49709. * $scope.showLoading = function() {
  49710. * //options default to values in $ionicLoadingConfig
  49711. * $ionicLoading.show().then(function(){
  49712. * console.log("The loading indicator is now displayed");
  49713. * });
  49714. * };
  49715. * });
  49716. * ```
  49717. */
  49718. IonicModule
  49719. .constant('$ionicLoadingConfig', {
  49720. template: '<ion-spinner></ion-spinner>'
  49721. })
  49722. .factory('$ionicLoading', [
  49723. '$ionicLoadingConfig',
  49724. '$ionicBody',
  49725. '$ionicTemplateLoader',
  49726. '$ionicBackdrop',
  49727. '$timeout',
  49728. '$q',
  49729. '$log',
  49730. '$compile',
  49731. '$ionicPlatform',
  49732. '$rootScope',
  49733. 'IONIC_BACK_PRIORITY',
  49734. function($ionicLoadingConfig, $ionicBody, $ionicTemplateLoader, $ionicBackdrop, $timeout, $q, $log, $compile, $ionicPlatform, $rootScope, IONIC_BACK_PRIORITY) {
  49735. var loaderInstance;
  49736. //default values
  49737. var deregisterBackAction = noop;
  49738. var deregisterStateListener1 = noop;
  49739. var deregisterStateListener2 = noop;
  49740. var loadingShowDelay = $q.when();
  49741. return {
  49742. /**
  49743. * @ngdoc method
  49744. * @name $ionicLoading#show
  49745. * @description Shows a loading indicator. If the indicator is already shown,
  49746. * it will set the options given and keep the indicator shown.
  49747. * @returns {promise} A promise which is resolved when the loading indicator is presented.
  49748. * @param {object} opts The options for the loading indicator. Available properties:
  49749. * - `{string=}` `template` The html content of the indicator.
  49750. * - `{string=}` `templateUrl` The url of an html template to load as the content of the indicator.
  49751. * - `{object=}` `scope` The scope to be a child of. Default: creates a child of $rootScope.
  49752. * - `{boolean=}` `noBackdrop` Whether to hide the backdrop. By default it will be shown.
  49753. * - `{boolean=}` `hideOnStateChange` Whether to hide the loading spinner when navigating
  49754. * to a new state. Default false.
  49755. * - `{number=}` `delay` How many milliseconds to delay showing the indicator. By default there is no delay.
  49756. * - `{number=}` `duration` How many milliseconds to wait until automatically
  49757. * hiding the indicator. By default, the indicator will be shown until `.hide()` is called.
  49758. */
  49759. show: showLoader,
  49760. /**
  49761. * @ngdoc method
  49762. * @name $ionicLoading#hide
  49763. * @description Hides the loading indicator, if shown.
  49764. * @returns {promise} A promise which is resolved when the loading indicator is hidden.
  49765. */
  49766. hide: hideLoader,
  49767. /**
  49768. * @private for testing
  49769. */
  49770. _getLoader: getLoader
  49771. };
  49772. function getLoader() {
  49773. if (!loaderInstance) {
  49774. loaderInstance = $ionicTemplateLoader.compile({
  49775. template: LOADING_TPL,
  49776. appendTo: $ionicBody.get()
  49777. })
  49778. .then(function(self) {
  49779. self.show = function(options) {
  49780. var templatePromise = options.templateUrl ?
  49781. $ionicTemplateLoader.load(options.templateUrl) :
  49782. //options.content: deprecated
  49783. $q.when(options.template || options.content || '');
  49784. self.scope = options.scope || self.scope;
  49785. if (!self.isShown) {
  49786. //options.showBackdrop: deprecated
  49787. self.hasBackdrop = !options.noBackdrop && options.showBackdrop !== false;
  49788. if (self.hasBackdrop) {
  49789. $ionicBackdrop.retain();
  49790. $ionicBackdrop.getElement().addClass('backdrop-loading');
  49791. }
  49792. }
  49793. if (options.duration) {
  49794. $timeout.cancel(self.durationTimeout);
  49795. self.durationTimeout = $timeout(
  49796. angular.bind(self, self.hide),
  49797. +options.duration
  49798. );
  49799. }
  49800. deregisterBackAction();
  49801. //Disable hardware back button while loading
  49802. deregisterBackAction = $ionicPlatform.registerBackButtonAction(
  49803. noop,
  49804. IONIC_BACK_PRIORITY.loading
  49805. );
  49806. templatePromise.then(function(html) {
  49807. if (html) {
  49808. var loading = self.element.children();
  49809. loading.html(html);
  49810. $compile(loading.contents())(self.scope);
  49811. }
  49812. //Don't show until template changes
  49813. if (self.isShown) {
  49814. self.element.addClass('visible');
  49815. ionic.requestAnimationFrame(function() {
  49816. if (self.isShown) {
  49817. self.element.addClass('active');
  49818. $ionicBody.addClass('loading-active');
  49819. }
  49820. });
  49821. }
  49822. });
  49823. self.isShown = true;
  49824. };
  49825. self.hide = function() {
  49826. deregisterBackAction();
  49827. if (self.isShown) {
  49828. if (self.hasBackdrop) {
  49829. $ionicBackdrop.release();
  49830. $ionicBackdrop.getElement().removeClass('backdrop-loading');
  49831. }
  49832. self.element.removeClass('active');
  49833. $ionicBody.removeClass('loading-active');
  49834. self.element.removeClass('visible');
  49835. ionic.requestAnimationFrame(function() {
  49836. !self.isShown && self.element.removeClass('visible');
  49837. });
  49838. }
  49839. $timeout.cancel(self.durationTimeout);
  49840. self.isShown = false;
  49841. var loading = self.element.children();
  49842. loading.html("");
  49843. };
  49844. return self;
  49845. });
  49846. }
  49847. return loaderInstance;
  49848. }
  49849. function showLoader(options) {
  49850. options = extend({}, $ionicLoadingConfig || {}, options || {});
  49851. // use a default delay of 100 to avoid some issues reported on github
  49852. // https://github.com/ionic-team/ionic/issues/3717
  49853. var delay = options.delay || options.showDelay || 0;
  49854. deregisterStateListener1();
  49855. deregisterStateListener2();
  49856. if (options.hideOnStateChange) {
  49857. deregisterStateListener1 = $rootScope.$on('$stateChangeSuccess', hideLoader);
  49858. deregisterStateListener2 = $rootScope.$on('$stateChangeError', hideLoader);
  49859. }
  49860. //If loading.show() was called previously, cancel it and show with our new options
  49861. $timeout.cancel(loadingShowDelay);
  49862. loadingShowDelay = $timeout(noop, delay);
  49863. return loadingShowDelay.then(getLoader).then(function(loader) {
  49864. return loader.show(options);
  49865. });
  49866. }
  49867. function hideLoader() {
  49868. deregisterStateListener1();
  49869. deregisterStateListener2();
  49870. $timeout.cancel(loadingShowDelay);
  49871. return getLoader().then(function(loader) {
  49872. return loader.hide();
  49873. });
  49874. }
  49875. }]);
  49876. /**
  49877. * @ngdoc service
  49878. * @name $ionicModal
  49879. * @module ionic
  49880. * @codepen gblny
  49881. * @description
  49882. *
  49883. * Related: {@link ionic.controller:ionicModal ionicModal controller}.
  49884. *
  49885. * The Modal is a content pane that can go over the user's main view
  49886. * temporarily. Usually used for making a choice or editing an item.
  49887. *
  49888. * Put the content of the modal inside of an `<ion-modal-view>` element.
  49889. *
  49890. * **Notes:**
  49891. * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
  49892. * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are
  49893. * called when the modal is removed.
  49894. *
  49895. * - This example assumes your modal is in your main index file or another template file. If it is in its own
  49896. * template file, remove the script tags and call it by file name.
  49897. *
  49898. * @usage
  49899. * ```html
  49900. * <script id="my-modal.html" type="text/ng-template">
  49901. * <ion-modal-view>
  49902. * <ion-header-bar>
  49903. * <h1 class="title">My Modal title</h1>
  49904. * </ion-header-bar>
  49905. * <ion-content>
  49906. * Hello!
  49907. * </ion-content>
  49908. * </ion-modal-view>
  49909. * </script>
  49910. * ```
  49911. * ```js
  49912. * angular.module('testApp', ['ionic'])
  49913. * .controller('MyController', function($scope, $ionicModal) {
  49914. * $ionicModal.fromTemplateUrl('my-modal.html', {
  49915. * scope: $scope,
  49916. * animation: 'slide-in-up'
  49917. * }).then(function(modal) {
  49918. * $scope.modal = modal;
  49919. * });
  49920. * $scope.openModal = function() {
  49921. * $scope.modal.show();
  49922. * };
  49923. * $scope.closeModal = function() {
  49924. * $scope.modal.hide();
  49925. * };
  49926. * // Cleanup the modal when we're done with it!
  49927. * $scope.$on('$destroy', function() {
  49928. * $scope.modal.remove();
  49929. * });
  49930. * // Execute action on hide modal
  49931. * $scope.$on('modal.hidden', function() {
  49932. * // Execute action
  49933. * });
  49934. * // Execute action on remove modal
  49935. * $scope.$on('modal.removed', function() {
  49936. * // Execute action
  49937. * });
  49938. * });
  49939. * ```
  49940. */
  49941. IonicModule
  49942. .factory('$ionicModal', [
  49943. '$rootScope',
  49944. '$ionicBody',
  49945. '$compile',
  49946. '$timeout',
  49947. '$ionicPlatform',
  49948. '$ionicTemplateLoader',
  49949. '$$q',
  49950. '$log',
  49951. '$ionicClickBlock',
  49952. '$window',
  49953. 'IONIC_BACK_PRIORITY',
  49954. function($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) {
  49955. /**
  49956. * @ngdoc controller
  49957. * @name ionicModal
  49958. * @module ionic
  49959. * @description
  49960. * Instantiated by the {@link ionic.service:$ionicModal} service.
  49961. *
  49962. * Be sure to call [remove()](#remove) when you are done with each modal
  49963. * to clean it up and avoid memory leaks.
  49964. *
  49965. * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating
  49966. * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are
  49967. * called when the modal is removed.
  49968. */
  49969. var ModalView = ionic.views.Modal.inherit({
  49970. /**
  49971. * @ngdoc method
  49972. * @name ionicModal#initialize
  49973. * @description Creates a new modal controller instance.
  49974. * @param {object} options An options object with the following properties:
  49975. * - `{object=}` `scope` The scope to be a child of.
  49976. * Default: creates a child of $rootScope.
  49977. * - `{string=}` `animation` The animation to show & hide with.
  49978. * Default: 'slide-in-up'
  49979. * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of
  49980. * the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show
  49981. * on Android, please use the [Ionic keyboard plugin](https://github.com/ionic-team/ionic-plugin-keyboard#keyboardshow).
  49982. * Default: false.
  49983. * - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop.
  49984. * Default: true.
  49985. * - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware
  49986. * back button on Android and similar devices. Default: true.
  49987. */
  49988. initialize: function(opts) {
  49989. ionic.views.Modal.prototype.initialize.call(this, opts);
  49990. this.animation = opts.animation || 'slide-in-up';
  49991. },
  49992. /**
  49993. * @ngdoc method
  49994. * @name ionicModal#show
  49995. * @description Show this modal instance.
  49996. * @returns {promise} A promise which is resolved when the modal is finished animating in.
  49997. */
  49998. show: function(target) {
  49999. var self = this;
  50000. if (self.scope.$$destroyed) {
  50001. $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.');
  50002. return $$q.when();
  50003. }
  50004. // on iOS, clicks will sometimes bleed through/ghost click on underlying
  50005. // elements
  50006. $ionicClickBlock.show(600);
  50007. stack.add(self);
  50008. var modalEl = jqLite(self.modalEl);
  50009. self.el.classList.remove('hide');
  50010. $timeout(function() {
  50011. if (!self._isShown) return;
  50012. $ionicBody.addClass(self.viewType + '-open');
  50013. }, 400, false);
  50014. if (!self.el.parentElement) {
  50015. modalEl.addClass(self.animation);
  50016. $ionicBody.append(self.el);
  50017. }
  50018. // if modal was closed while the keyboard was up, reset scroll view on
  50019. // next show since we can only resize it once it's visible
  50020. var scrollCtrl = modalEl.data('$$ionicScrollController');
  50021. scrollCtrl && scrollCtrl.resize();
  50022. if (target && self.positionView) {
  50023. self.positionView(target, modalEl);
  50024. // set up a listener for in case the window size changes
  50025. self._onWindowResize = function() {
  50026. if (self._isShown) self.positionView(target, modalEl);
  50027. };
  50028. ionic.on('resize', self._onWindowResize, window);
  50029. }
  50030. modalEl.addClass('ng-enter active')
  50031. .removeClass('ng-leave ng-leave-active');
  50032. self._isShown = true;
  50033. self._deregisterBackButton = $ionicPlatform.registerBackButtonAction(
  50034. self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop,
  50035. IONIC_BACK_PRIORITY.modal
  50036. );
  50037. ionic.views.Modal.prototype.show.call(self);
  50038. $timeout(function() {
  50039. if (!self._isShown) return;
  50040. modalEl.addClass('ng-enter-active');
  50041. ionic.trigger('resize');
  50042. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self);
  50043. self.el.classList.add('active');
  50044. self.scope.$broadcast('$ionicHeader.align');
  50045. self.scope.$broadcast('$ionicFooter.align');
  50046. self.scope.$broadcast('$ionic.modalPresented');
  50047. }, 20);
  50048. return $timeout(function() {
  50049. if (!self._isShown) return;
  50050. self.$el.on('touchmove', function(e) {
  50051. //Don't allow scrolling while open by dragging on backdrop
  50052. var isInScroll = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'scroll');
  50053. if (!isInScroll) {
  50054. e.preventDefault();
  50055. }
  50056. });
  50057. //After animating in, allow hide on backdrop click
  50058. self.$el.on('click', function(e) {
  50059. if (self.backdropClickToClose && e.target === self.el && stack.isHighest(self)) {
  50060. self.hide();
  50061. }
  50062. });
  50063. }, 400);
  50064. },
  50065. /**
  50066. * @ngdoc method
  50067. * @name ionicModal#hide
  50068. * @description Hide this modal instance.
  50069. * @returns {promise} A promise which is resolved when the modal is finished animating out.
  50070. */
  50071. hide: function() {
  50072. var self = this;
  50073. var modalEl = jqLite(self.modalEl);
  50074. // on iOS, clicks will sometimes bleed through/ghost click on underlying
  50075. // elements
  50076. $ionicClickBlock.show(600);
  50077. stack.remove(self);
  50078. self.el.classList.remove('active');
  50079. modalEl.addClass('ng-leave');
  50080. $timeout(function() {
  50081. if (self._isShown) return;
  50082. modalEl.addClass('ng-leave-active')
  50083. .removeClass('ng-enter ng-enter-active active');
  50084. self.scope.$broadcast('$ionic.modalRemoved');
  50085. }, 20, false);
  50086. self.$el.off('click');
  50087. self._isShown = false;
  50088. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self);
  50089. self._deregisterBackButton && self._deregisterBackButton();
  50090. ionic.views.Modal.prototype.hide.call(self);
  50091. // clean up event listeners
  50092. if (self.positionView) {
  50093. ionic.off('resize', self._onWindowResize, window);
  50094. }
  50095. return $timeout(function() {
  50096. if (!modalStack.length) {
  50097. $ionicBody.removeClass(self.viewType + '-open');
  50098. }
  50099. self.el.classList.add('hide');
  50100. }, self.hideDelay || 320);
  50101. },
  50102. /**
  50103. * @ngdoc method
  50104. * @name ionicModal#remove
  50105. * @description Remove this modal instance from the DOM and clean up.
  50106. * @returns {promise} A promise which is resolved when the modal is finished animating out.
  50107. */
  50108. remove: function() {
  50109. var self = this,
  50110. deferred, promise;
  50111. self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self);
  50112. // Only hide modal, when it is actually shown!
  50113. // The hide function shows a click-block-div for a split second, because on iOS,
  50114. // clicks will sometimes bleed through/ghost click on underlying elements.
  50115. // However, this will make the app unresponsive for short amount of time.
  50116. // We don't want that, if the modal window is already hidden.
  50117. if (self._isShown) {
  50118. promise = self.hide();
  50119. } else {
  50120. deferred = $$q.defer();
  50121. deferred.resolve();
  50122. promise = deferred.promise;
  50123. }
  50124. return promise.then(function() {
  50125. self.scope.$destroy();
  50126. self.$el.remove();
  50127. });
  50128. },
  50129. /**
  50130. * @ngdoc method
  50131. * @name ionicModal#isShown
  50132. * @returns boolean Whether this modal is currently shown.
  50133. */
  50134. isShown: function() {
  50135. return !!this._isShown;
  50136. }
  50137. });
  50138. var createModal = function(templateString, options) {
  50139. // Create a new scope for the modal
  50140. var scope = options.scope && options.scope.$new() || $rootScope.$new(true);
  50141. options.viewType = options.viewType || 'modal';
  50142. extend(scope, {
  50143. $hasHeader: false,
  50144. $hasSubheader: false,
  50145. $hasFooter: false,
  50146. $hasSubfooter: false,
  50147. $hasTabs: false,
  50148. $hasTabsTop: false
  50149. });
  50150. // Compile the template
  50151. var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope);
  50152. options.$el = element;
  50153. options.el = element[0];
  50154. options.modalEl = options.el.querySelector('.' + options.viewType);
  50155. var modal = new ModalView(options);
  50156. modal.scope = scope;
  50157. // If this wasn't a defined scope, we can assign the viewType to the isolated scope
  50158. // we created
  50159. if (!options.scope) {
  50160. scope[ options.viewType ] = modal;
  50161. }
  50162. return modal;
  50163. };
  50164. var modalStack = [];
  50165. var stack = {
  50166. add: function(modal) {
  50167. modalStack.push(modal);
  50168. },
  50169. remove: function(modal) {
  50170. var index = modalStack.indexOf(modal);
  50171. if (index > -1 && index < modalStack.length) {
  50172. modalStack.splice(index, 1);
  50173. }
  50174. },
  50175. isHighest: function(modal) {
  50176. var index = modalStack.indexOf(modal);
  50177. return (index > -1 && index === modalStack.length - 1);
  50178. }
  50179. };
  50180. return {
  50181. /**
  50182. * @ngdoc method
  50183. * @name $ionicModal#fromTemplate
  50184. * @param {string} templateString The template string to use as the modal's
  50185. * content.
  50186. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
  50187. * @returns {object} An instance of an {@link ionic.controller:ionicModal}
  50188. * controller.
  50189. */
  50190. fromTemplate: function(templateString, options) {
  50191. var modal = createModal(templateString, options || {});
  50192. return modal;
  50193. },
  50194. /**
  50195. * @ngdoc method
  50196. * @name $ionicModal#fromTemplateUrl
  50197. * @param {string} templateUrl The url to load the template from.
  50198. * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.
  50199. * options object.
  50200. * @returns {promise} A promise that will be resolved with an instance of
  50201. * an {@link ionic.controller:ionicModal} controller.
  50202. */
  50203. fromTemplateUrl: function(url, options, _) {
  50204. var cb;
  50205. //Deprecated: allow a callback as second parameter. Now we return a promise.
  50206. if (angular.isFunction(options)) {
  50207. cb = options;
  50208. options = _;
  50209. }
  50210. return $ionicTemplateLoader.load(url).then(function(templateString) {
  50211. var modal = createModal(templateString, options || {});
  50212. cb && cb(modal);
  50213. return modal;
  50214. });
  50215. },
  50216. stack: stack
  50217. };
  50218. }]);
  50219. /**
  50220. * @ngdoc service
  50221. * @name $ionicNavBarDelegate
  50222. * @module ionic
  50223. * @description
  50224. * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.
  50225. *
  50226. * @usage
  50227. *
  50228. * ```html
  50229. * <body ng-controller="MyCtrl">
  50230. * <ion-nav-bar>
  50231. * <button ng-click="setNavTitle('banana')">
  50232. * Set title to banana!
  50233. * </button>
  50234. * </ion-nav-bar>
  50235. * </body>
  50236. * ```
  50237. * ```js
  50238. * function MyCtrl($scope, $ionicNavBarDelegate) {
  50239. * $scope.setNavTitle = function(title) {
  50240. * $ionicNavBarDelegate.title(title);
  50241. * }
  50242. * }
  50243. * ```
  50244. */
  50245. IonicModule
  50246. .service('$ionicNavBarDelegate', ionic.DelegateService([
  50247. /**
  50248. * @ngdoc method
  50249. * @name $ionicNavBarDelegate#align
  50250. * @description Aligns the title with the buttons in a given direction.
  50251. * @param {string=} direction The direction to the align the title text towards.
  50252. * Available: 'left', 'right', 'center'. Default: 'center'.
  50253. */
  50254. 'align',
  50255. /**
  50256. * @ngdoc method
  50257. * @name $ionicNavBarDelegate#showBackButton
  50258. * @description
  50259. * Set/get whether the {@link ionic.directive:ionNavBackButton} is shown
  50260. * (if it exists and there is a previous view that can be navigated to).
  50261. * @param {boolean=} show Whether to show the back button.
  50262. * @returns {boolean} Whether the back button is shown.
  50263. */
  50264. 'showBackButton',
  50265. /**
  50266. * @ngdoc method
  50267. * @name $ionicNavBarDelegate#showBar
  50268. * @description
  50269. * Set/get whether the {@link ionic.directive:ionNavBar} is shown.
  50270. * @param {boolean} show Whether to show the bar.
  50271. * @returns {boolean} Whether the bar is shown.
  50272. */
  50273. 'showBar',
  50274. /**
  50275. * @ngdoc method
  50276. * @name $ionicNavBarDelegate#title
  50277. * @description
  50278. * Set the title for the {@link ionic.directive:ionNavBar}.
  50279. * @param {string} title The new title to show.
  50280. */
  50281. 'title',
  50282. // DEPRECATED, as of v1.0.0-beta14 -------
  50283. 'changeTitle',
  50284. 'setTitle',
  50285. 'getTitle',
  50286. 'back',
  50287. 'getPreviousTitle'
  50288. // END DEPRECATED -------
  50289. ]));
  50290. IonicModule
  50291. .service('$ionicNavViewDelegate', ionic.DelegateService([
  50292. 'clearCache'
  50293. ]));
  50294. /**
  50295. * @ngdoc service
  50296. * @name $ionicPlatform
  50297. * @module ionic
  50298. * @description
  50299. * An angular abstraction of {@link ionic.utility:ionic.Platform}.
  50300. *
  50301. * Used to detect the current platform, as well as do things like override the
  50302. * Android back button in PhoneGap/Cordova.
  50303. */
  50304. IonicModule
  50305. .constant('IONIC_BACK_PRIORITY', {
  50306. view: 100,
  50307. sideMenu: 150,
  50308. modal: 200,
  50309. actionSheet: 300,
  50310. popup: 400,
  50311. loading: 500
  50312. })
  50313. .provider('$ionicPlatform', function() {
  50314. return {
  50315. $get: ['$q', '$ionicScrollDelegate', function($q, $ionicScrollDelegate) {
  50316. var self = {
  50317. /**
  50318. * @ngdoc method
  50319. * @name $ionicPlatform#onHardwareBackButton
  50320. * @description
  50321. * Some platforms have a hardware back button, so this is one way to
  50322. * bind to it.
  50323. * @param {function} callback the callback to trigger when this event occurs
  50324. */
  50325. onHardwareBackButton: function(cb) {
  50326. ionic.Platform.ready(function() {
  50327. document.addEventListener('backbutton', cb, false);
  50328. });
  50329. },
  50330. /**
  50331. * @ngdoc method
  50332. * @name $ionicPlatform#offHardwareBackButton
  50333. * @description
  50334. * Remove an event listener for the backbutton.
  50335. * @param {function} callback The listener function that was
  50336. * originally bound.
  50337. */
  50338. offHardwareBackButton: function(fn) {
  50339. ionic.Platform.ready(function() {
  50340. document.removeEventListener('backbutton', fn);
  50341. });
  50342. },
  50343. /**
  50344. * @ngdoc method
  50345. * @name $ionicPlatform#registerBackButtonAction
  50346. * @description
  50347. * Register a hardware back button action. Only one action will execute
  50348. * when the back button is clicked, so this method decides which of
  50349. * the registered back button actions has the highest priority.
  50350. *
  50351. * For example, if an actionsheet is showing, the back button should
  50352. * close the actionsheet, but it should not also go back a page view
  50353. * or close a modal which may be open.
  50354. *
  50355. * The priorities for the existing back button hooks are as follows:
  50356. * Return to previous view = 100
  50357. * Close side menu = 150
  50358. * Dismiss modal = 200
  50359. * Close action sheet = 300
  50360. * Dismiss popup = 400
  50361. * Dismiss loading overlay = 500
  50362. *
  50363. * Your back button action will override each of the above actions
  50364. * whose priority is less than the priority you provide. For example,
  50365. * an action assigned a priority of 101 will override the 'return to
  50366. * previous view' action, but not any of the other actions.
  50367. *
  50368. * @param {function} callback Called when the back button is pressed,
  50369. * if this listener is the highest priority.
  50370. * @param {number} priority Only the highest priority will execute.
  50371. * @param {*=} actionId The id to assign this action. Default: a
  50372. * random unique id.
  50373. * @returns {function} A function that, when called, will deregister
  50374. * this backButtonAction.
  50375. */
  50376. $backButtonActions: {},
  50377. registerBackButtonAction: function(fn, priority, actionId) {
  50378. if (!self._hasBackButtonHandler) {
  50379. // add a back button listener if one hasn't been setup yet
  50380. self.$backButtonActions = {};
  50381. self.onHardwareBackButton(self.hardwareBackButtonClick);
  50382. self._hasBackButtonHandler = true;
  50383. }
  50384. var action = {
  50385. id: (actionId ? actionId : ionic.Utils.nextUid()),
  50386. priority: (priority ? priority : 0),
  50387. fn: fn
  50388. };
  50389. self.$backButtonActions[action.id] = action;
  50390. // return a function to de-register this back button action
  50391. return function() {
  50392. delete self.$backButtonActions[action.id];
  50393. };
  50394. },
  50395. /**
  50396. * @private
  50397. */
  50398. hardwareBackButtonClick: function(e) {
  50399. // loop through all the registered back button actions
  50400. // and only run the last one of the highest priority
  50401. var priorityAction, actionId;
  50402. for (actionId in self.$backButtonActions) {
  50403. if (!priorityAction || self.$backButtonActions[actionId].priority >= priorityAction.priority) {
  50404. priorityAction = self.$backButtonActions[actionId];
  50405. }
  50406. }
  50407. if (priorityAction) {
  50408. priorityAction.fn(e);
  50409. return priorityAction;
  50410. }
  50411. },
  50412. is: function(type) {
  50413. return ionic.Platform.is(type);
  50414. },
  50415. /**
  50416. * @ngdoc method
  50417. * @name $ionicPlatform#on
  50418. * @description
  50419. * Add Cordova event listeners, such as `pause`, `resume`, `volumedownbutton`, `batterylow`,
  50420. * `offline`, etc. More information about available event types can be found in
  50421. * [Cordova's event documentation](https://cordova.apache.org/docs/en/latest/cordova/events/events.html).
  50422. * @param {string} type Cordova [event type](https://cordova.apache.org/docs/en/latest/cordova/events/events.html).
  50423. * @param {function} callback Called when the Cordova event is fired.
  50424. * @returns {function} Returns a deregistration function to remove the event listener.
  50425. */
  50426. on: function(type, cb) {
  50427. ionic.Platform.ready(function() {
  50428. document.addEventListener(type, cb, false);
  50429. });
  50430. return function() {
  50431. ionic.Platform.ready(function() {
  50432. document.removeEventListener(type, cb);
  50433. });
  50434. };
  50435. },
  50436. /**
  50437. * @ngdoc method
  50438. * @name $ionicPlatform#ready
  50439. * @description
  50440. * Trigger a callback once the device is ready,
  50441. * or immediately if the device is already ready.
  50442. * @param {function=} callback The function to call.
  50443. * @returns {promise} A promise which is resolved when the device is ready.
  50444. */
  50445. ready: function(cb) {
  50446. var q = $q.defer();
  50447. ionic.Platform.ready(function() {
  50448. window.addEventListener('statusTap', function() {
  50449. $ionicScrollDelegate.scrollTop(true);
  50450. });
  50451. q.resolve();
  50452. cb && cb();
  50453. });
  50454. return q.promise;
  50455. }
  50456. };
  50457. return self;
  50458. }]
  50459. };
  50460. });
  50461. /**
  50462. * @ngdoc service
  50463. * @name $ionicPopover
  50464. * @module ionic
  50465. * @description
  50466. *
  50467. * Related: {@link ionic.controller:ionicPopover ionicPopover controller}.
  50468. *
  50469. * The Popover is a view that floats above an app’s content. Popovers provide an
  50470. * easy way to present or gather information from the user and are
  50471. * commonly used in the following situations:
  50472. *
  50473. * - Show more info about the current view
  50474. * - Select a commonly used tool or configuration
  50475. * - Present a list of actions to perform inside one of your views
  50476. *
  50477. * Put the content of the popover inside of an `<ion-popover-view>` element.
  50478. *
  50479. * @usage
  50480. * ```html
  50481. * <p>
  50482. * <button ng-click="openPopover($event)">Open Popover</button>
  50483. * </p>
  50484. *
  50485. * <script id="my-popover.html" type="text/ng-template">
  50486. * <ion-popover-view>
  50487. * <ion-header-bar>
  50488. * <h1 class="title">My Popover Title</h1>
  50489. * </ion-header-bar>
  50490. * <ion-content>
  50491. * Hello!
  50492. * </ion-content>
  50493. * </ion-popover-view>
  50494. * </script>
  50495. * ```
  50496. * ```js
  50497. * angular.module('testApp', ['ionic'])
  50498. * .controller('MyController', function($scope, $ionicPopover) {
  50499. *
  50500. * // .fromTemplate() method
  50501. * 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>';
  50502. *
  50503. * $scope.popover = $ionicPopover.fromTemplate(template, {
  50504. * scope: $scope
  50505. * });
  50506. *
  50507. * // .fromTemplateUrl() method
  50508. * $ionicPopover.fromTemplateUrl('my-popover.html', {
  50509. * scope: $scope
  50510. * }).then(function(popover) {
  50511. * $scope.popover = popover;
  50512. * });
  50513. *
  50514. *
  50515. * $scope.openPopover = function($event) {
  50516. * $scope.popover.show($event);
  50517. * };
  50518. * $scope.closePopover = function() {
  50519. * $scope.popover.hide();
  50520. * };
  50521. * //Cleanup the popover when we're done with it!
  50522. * $scope.$on('$destroy', function() {
  50523. * $scope.popover.remove();
  50524. * });
  50525. * // Execute action on hidden popover
  50526. * $scope.$on('popover.hidden', function() {
  50527. * // Execute action
  50528. * });
  50529. * // Execute action on remove popover
  50530. * $scope.$on('popover.removed', function() {
  50531. * // Execute action
  50532. * });
  50533. * });
  50534. * ```
  50535. */
  50536. IonicModule
  50537. .factory('$ionicPopover', ['$ionicModal', '$ionicPosition', '$document', '$window',
  50538. function($ionicModal, $ionicPosition, $document, $window) {
  50539. var POPOVER_BODY_PADDING = 6;
  50540. var POPOVER_OPTIONS = {
  50541. viewType: 'popover',
  50542. hideDelay: 1,
  50543. animation: 'none',
  50544. positionView: positionView
  50545. };
  50546. function positionView(target, popoverEle) {
  50547. var targetEle = jqLite(target.target || target);
  50548. var buttonOffset = $ionicPosition.offset(targetEle);
  50549. var popoverWidth = popoverEle.prop('offsetWidth');
  50550. var popoverHeight = popoverEle.prop('offsetHeight');
  50551. // Use innerWidth and innerHeight, because clientWidth and clientHeight
  50552. // doesn't work consistently for body on all platforms
  50553. var bodyWidth = $window.innerWidth;
  50554. var bodyHeight = $window.innerHeight;
  50555. var popoverCSS = {
  50556. left: buttonOffset.left + buttonOffset.width / 2 - popoverWidth / 2
  50557. };
  50558. var arrowEle = jqLite(popoverEle[0].querySelector('.popover-arrow'));
  50559. if (popoverCSS.left < POPOVER_BODY_PADDING) {
  50560. popoverCSS.left = POPOVER_BODY_PADDING;
  50561. } else if (popoverCSS.left + popoverWidth + POPOVER_BODY_PADDING > bodyWidth) {
  50562. popoverCSS.left = bodyWidth - popoverWidth - POPOVER_BODY_PADDING;
  50563. }
  50564. // If the popover when popped down stretches past bottom of screen,
  50565. // make it pop up if there's room above
  50566. if (buttonOffset.top + buttonOffset.height + popoverHeight > bodyHeight &&
  50567. buttonOffset.top - popoverHeight > 0) {
  50568. popoverCSS.top = buttonOffset.top - popoverHeight;
  50569. popoverEle.addClass('popover-bottom');
  50570. } else {
  50571. popoverCSS.top = buttonOffset.top + buttonOffset.height;
  50572. popoverEle.removeClass('popover-bottom');
  50573. }
  50574. arrowEle.css({
  50575. left: buttonOffset.left + buttonOffset.width / 2 -
  50576. arrowEle.prop('offsetWidth') / 2 - popoverCSS.left + 'px'
  50577. });
  50578. popoverEle.css({
  50579. top: popoverCSS.top + 'px',
  50580. left: popoverCSS.left + 'px',
  50581. marginLeft: '0',
  50582. opacity: '1'
  50583. });
  50584. }
  50585. /**
  50586. * @ngdoc controller
  50587. * @name ionicPopover
  50588. * @module ionic
  50589. * @description
  50590. * Instantiated by the {@link ionic.service:$ionicPopover} service.
  50591. *
  50592. * Be sure to call [remove()](#remove) when you are done with each popover
  50593. * to clean it up and avoid memory leaks.
  50594. *
  50595. * Note: a popover will broadcast 'popover.shown', 'popover.hidden', and 'popover.removed' events from its originating
  50596. * scope, passing in itself as an event argument. Both the popover.removed and popover.hidden events are
  50597. * called when the popover is removed.
  50598. */
  50599. /**
  50600. * @ngdoc method
  50601. * @name ionicPopover#initialize
  50602. * @description Creates a new popover controller instance.
  50603. * @param {object} options An options object with the following properties:
  50604. * - `{object=}` `scope` The scope to be a child of.
  50605. * Default: creates a child of $rootScope.
  50606. * - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of
  50607. * the popover when shown. Default: false.
  50608. * - `{boolean=}` `backdropClickToClose` Whether to close the popover on clicking the backdrop.
  50609. * Default: true.
  50610. * - `{boolean=}` `hardwareBackButtonClose` Whether the popover can be closed using the hardware
  50611. * back button on Android and similar devices. Default: true.
  50612. */
  50613. /**
  50614. * @ngdoc method
  50615. * @name ionicPopover#show
  50616. * @description Show this popover instance.
  50617. * @param {$event} $event The $event or target element which the popover should align
  50618. * itself next to.
  50619. * @returns {promise} A promise which is resolved when the popover is finished animating in.
  50620. */
  50621. /**
  50622. * @ngdoc method
  50623. * @name ionicPopover#hide
  50624. * @description Hide this popover instance.
  50625. * @returns {promise} A promise which is resolved when the popover is finished animating out.
  50626. */
  50627. /**
  50628. * @ngdoc method
  50629. * @name ionicPopover#remove
  50630. * @description Remove this popover instance from the DOM and clean up.
  50631. * @returns {promise} A promise which is resolved when the popover is finished animating out.
  50632. */
  50633. /**
  50634. * @ngdoc method
  50635. * @name ionicPopover#isShown
  50636. * @returns boolean Whether this popover is currently shown.
  50637. */
  50638. return {
  50639. /**
  50640. * @ngdoc method
  50641. * @name $ionicPopover#fromTemplate
  50642. * @param {string} templateString The template string to use as the popovers's
  50643. * content.
  50644. * @param {object} options Options to be passed to the initialize method.
  50645. * @returns {object} An instance of an {@link ionic.controller:ionicPopover}
  50646. * controller (ionicPopover is built on top of $ionicPopover).
  50647. */
  50648. fromTemplate: function(templateString, options) {
  50649. return $ionicModal.fromTemplate(templateString, ionic.Utils.extend({}, POPOVER_OPTIONS, options));
  50650. },
  50651. /**
  50652. * @ngdoc method
  50653. * @name $ionicPopover#fromTemplateUrl
  50654. * @param {string} templateUrl The url to load the template from.
  50655. * @param {object} options Options to be passed to the initialize method.
  50656. * @returns {promise} A promise that will be resolved with an instance of
  50657. * an {@link ionic.controller:ionicPopover} controller (ionicPopover is built on top of $ionicPopover).
  50658. */
  50659. fromTemplateUrl: function(url, options) {
  50660. return $ionicModal.fromTemplateUrl(url, ionic.Utils.extend({}, POPOVER_OPTIONS, options));
  50661. }
  50662. };
  50663. }]);
  50664. var POPUP_TPL =
  50665. '<div class="popup-container" ng-class="cssClass">' +
  50666. '<div class="popup">' +
  50667. '<div class="popup-head">' +
  50668. '<h3 class="popup-title" ng-bind-html="title"></h3>' +
  50669. '<h5 class="popup-sub-title" ng-bind-html="subTitle" ng-if="subTitle"></h5>' +
  50670. '</div>' +
  50671. '<div class="popup-body">' +
  50672. '</div>' +
  50673. '<div class="popup-buttons" ng-show="buttons.length">' +
  50674. '<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>' +
  50675. '</div>' +
  50676. '</div>' +
  50677. '</div>';
  50678. /**
  50679. * @ngdoc service
  50680. * @name $ionicPopup
  50681. * @module ionic
  50682. * @restrict E
  50683. * @codepen zkmhJ
  50684. * @description
  50685. *
  50686. * The Ionic Popup service allows programmatically creating and showing popup
  50687. * windows that require the user to respond in order to continue.
  50688. *
  50689. * The popup system has support for more flexible versions of the built in `alert()`, `prompt()`,
  50690. * and `confirm()` functions that users are used to, in addition to allowing popups with completely
  50691. * custom content and look.
  50692. *
  50693. * An input can be given an `autofocus` attribute so it automatically receives focus when
  50694. * the popup first shows. However, depending on certain use-cases this can cause issues with
  50695. * the tap/click system, which is why Ionic prefers using the `autofocus` attribute as
  50696. * an opt-in feature and not the default.
  50697. *
  50698. * @usage
  50699. * A few basic examples, see below for details about all of the options available.
  50700. *
  50701. * ```js
  50702. *angular.module('mySuperApp', ['ionic'])
  50703. *.controller('PopupCtrl',function($scope, $ionicPopup, $timeout) {
  50704. *
  50705. * // Triggered on a button click, or some other target
  50706. * $scope.showPopup = function() {
  50707. * $scope.data = {};
  50708. *
  50709. * // An elaborate, custom popup
  50710. * var myPopup = $ionicPopup.show({
  50711. * template: '<input type="password" ng-model="data.wifi">',
  50712. * title: 'Enter Wi-Fi Password',
  50713. * subTitle: 'Please use normal things',
  50714. * scope: $scope,
  50715. * buttons: [
  50716. * { text: 'Cancel' },
  50717. * {
  50718. * text: '<b>Save</b>',
  50719. * type: 'button-positive',
  50720. * onTap: function(e) {
  50721. * if (!$scope.data.wifi) {
  50722. * //don't allow the user to close unless he enters wifi password
  50723. * e.preventDefault();
  50724. * } else {
  50725. * return $scope.data.wifi;
  50726. * }
  50727. * }
  50728. * }
  50729. * ]
  50730. * });
  50731. *
  50732. * myPopup.then(function(res) {
  50733. * console.log('Tapped!', res);
  50734. * });
  50735. *
  50736. * $timeout(function() {
  50737. * myPopup.close(); //close the popup after 3 seconds for some reason
  50738. * }, 3000);
  50739. * };
  50740. *
  50741. * // A confirm dialog
  50742. * $scope.showConfirm = function() {
  50743. * var confirmPopup = $ionicPopup.confirm({
  50744. * title: 'Consume Ice Cream',
  50745. * template: 'Are you sure you want to eat this ice cream?'
  50746. * });
  50747. *
  50748. * confirmPopup.then(function(res) {
  50749. * if(res) {
  50750. * console.log('You are sure');
  50751. * } else {
  50752. * console.log('You are not sure');
  50753. * }
  50754. * });
  50755. * };
  50756. *
  50757. * // An alert dialog
  50758. * $scope.showAlert = function() {
  50759. * var alertPopup = $ionicPopup.alert({
  50760. * title: 'Don\'t eat that!',
  50761. * template: 'It might taste good'
  50762. * });
  50763. *
  50764. * alertPopup.then(function(res) {
  50765. * console.log('Thank you for not eating my delicious ice cream cone');
  50766. * });
  50767. * };
  50768. *});
  50769. *```
  50770. */
  50771. IonicModule
  50772. .factory('$ionicPopup', [
  50773. '$ionicTemplateLoader',
  50774. '$ionicBackdrop',
  50775. '$q',
  50776. '$timeout',
  50777. '$rootScope',
  50778. '$ionicBody',
  50779. '$compile',
  50780. '$ionicPlatform',
  50781. '$ionicModal',
  50782. 'IONIC_BACK_PRIORITY',
  50783. function($ionicTemplateLoader, $ionicBackdrop, $q, $timeout, $rootScope, $ionicBody, $compile, $ionicPlatform, $ionicModal, IONIC_BACK_PRIORITY) {
  50784. //TODO allow this to be configured
  50785. var config = {
  50786. stackPushDelay: 75
  50787. };
  50788. var popupStack = [];
  50789. var $ionicPopup = {
  50790. /**
  50791. * @ngdoc method
  50792. * @description
  50793. * Show a complex popup. This is the master show function for all popups.
  50794. *
  50795. * A complex popup has a `buttons` array, with each button having a `text` and `type`
  50796. * field, in addition to an `onTap` function. The `onTap` function, called when
  50797. * the corresponding button on the popup is tapped, will by default close the popup
  50798. * and resolve the popup promise with its return value. If you wish to prevent the
  50799. * default and keep the popup open on button tap, call `event.preventDefault()` on the
  50800. * passed in tap event. Details below.
  50801. *
  50802. * @name $ionicPopup#show
  50803. * @param {object} options The options for the new popup, of the form:
  50804. *
  50805. * ```
  50806. * {
  50807. * title: '', // String. The title of the popup.
  50808. * cssClass: '', // String, The custom CSS class name
  50809. * subTitle: '', // String (optional). The sub-title of the popup.
  50810. * template: '', // String (optional). The html template to place in the popup body.
  50811. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50812. * scope: null, // Scope (optional). A scope to link to the popup content.
  50813. * buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.
  50814. * text: 'Cancel',
  50815. * type: 'button-default',
  50816. * onTap: function(e) {
  50817. * // e.preventDefault() will stop the popup from closing when tapped.
  50818. * e.preventDefault();
  50819. * }
  50820. * }, {
  50821. * text: 'OK',
  50822. * type: 'button-positive',
  50823. * onTap: function(e) {
  50824. * // Returning a value will cause the promise to resolve with the given value.
  50825. * return scope.data.response;
  50826. * }
  50827. * }]
  50828. * }
  50829. * ```
  50830. *
  50831. * @returns {object} A promise which is resolved when the popup is closed. Has an additional
  50832. * `close` function, which can be used to programmatically close the popup.
  50833. */
  50834. show: showPopup,
  50835. /**
  50836. * @ngdoc method
  50837. * @name $ionicPopup#alert
  50838. * @description Show a simple alert popup with a message and one button that the user can
  50839. * tap to close the popup.
  50840. *
  50841. * @param {object} options The options for showing the alert, of the form:
  50842. *
  50843. * ```
  50844. * {
  50845. * title: '', // String. The title of the popup.
  50846. * cssClass: '', // String, The custom CSS class name
  50847. * subTitle: '', // String (optional). The sub-title of the popup.
  50848. * template: '', // String (optional). The html template to place in the popup body.
  50849. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50850. * okText: '', // String (default: 'OK'). The text of the OK button.
  50851. * okType: '', // String (default: 'button-positive'). The type of the OK button.
  50852. * }
  50853. * ```
  50854. *
  50855. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50856. * function `close`, which can be called with any value to programmatically close the popup
  50857. * with the given value.
  50858. */
  50859. alert: showAlert,
  50860. /**
  50861. * @ngdoc method
  50862. * @name $ionicPopup#confirm
  50863. * @description
  50864. * Show a simple confirm popup with a Cancel and OK button.
  50865. *
  50866. * Resolves the promise with true if the user presses the OK button, and false if the
  50867. * user presses the Cancel button.
  50868. *
  50869. * @param {object} options The options for showing the confirm popup, of the form:
  50870. *
  50871. * ```
  50872. * {
  50873. * title: '', // String. The title of the popup.
  50874. * cssClass: '', // String, The custom CSS class name
  50875. * subTitle: '', // String (optional). The sub-title of the popup.
  50876. * template: '', // String (optional). The html template to place in the popup body.
  50877. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50878. * cancelText: '', // String (default: 'Cancel'). The text of the Cancel button.
  50879. * cancelType: '', // String (default: 'button-default'). The type of the Cancel button.
  50880. * okText: '', // String (default: 'OK'). The text of the OK button.
  50881. * okType: '', // String (default: 'button-positive'). The type of the OK button.
  50882. * }
  50883. * ```
  50884. *
  50885. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50886. * function `close`, which can be called with any value to programmatically close the popup
  50887. * with the given value.
  50888. */
  50889. confirm: showConfirm,
  50890. /**
  50891. * @ngdoc method
  50892. * @name $ionicPopup#prompt
  50893. * @description Show a simple prompt popup, which has an input, OK button, and Cancel button.
  50894. * Resolves the promise with the value of the input if the user presses OK, and with undefined
  50895. * if the user presses Cancel.
  50896. *
  50897. * ```javascript
  50898. * $ionicPopup.prompt({
  50899. * title: 'Password Check',
  50900. * template: 'Enter your secret password',
  50901. * inputType: 'password',
  50902. * inputPlaceholder: 'Your password'
  50903. * }).then(function(res) {
  50904. * console.log('Your password is', res);
  50905. * });
  50906. * ```
  50907. * @param {object} options The options for showing the prompt popup, of the form:
  50908. *
  50909. * ```
  50910. * {
  50911. * title: '', // String. The title of the popup.
  50912. * cssClass: '', // String, The custom CSS class name
  50913. * subTitle: '', // String (optional). The sub-title of the popup.
  50914. * template: '', // String (optional). The html template to place in the popup body.
  50915. * templateUrl: '', // String (optional). The URL of an html template to place in the popup body.
  50916. * inputType: // String (default: 'text'). The type of input to use
  50917. * defaultText: // String (default: ''). The initial value placed into the input.
  50918. * maxLength: // Integer (default: null). Specify a maxlength attribute for the input.
  50919. * inputPlaceholder: // String (default: ''). A placeholder to use for the input.
  50920. * cancelText: // String (default: 'Cancel'. The text of the Cancel button.
  50921. * cancelType: // String (default: 'button-default'). The type of the Cancel button.
  50922. * okText: // String (default: 'OK'). The text of the OK button.
  50923. * okType: // String (default: 'button-positive'). The type of the OK button.
  50924. * }
  50925. * ```
  50926. *
  50927. * @returns {object} A promise which is resolved when the popup is closed. Has one additional
  50928. * function `close`, which can be called with any value to programmatically close the popup
  50929. * with the given value.
  50930. */
  50931. prompt: showPrompt,
  50932. /**
  50933. * @private for testing
  50934. */
  50935. _createPopup: createPopup,
  50936. _popupStack: popupStack
  50937. };
  50938. return $ionicPopup;
  50939. function createPopup(options) {
  50940. options = extend({
  50941. scope: null,
  50942. title: '',
  50943. buttons: []
  50944. }, options || {});
  50945. var self = {};
  50946. self.scope = (options.scope || $rootScope).$new();
  50947. self.element = jqLite(POPUP_TPL);
  50948. self.responseDeferred = $q.defer();
  50949. $ionicBody.get().appendChild(self.element[0]);
  50950. $compile(self.element)(self.scope);
  50951. extend(self.scope, {
  50952. title: options.title,
  50953. buttons: options.buttons,
  50954. subTitle: options.subTitle,
  50955. cssClass: options.cssClass,
  50956. $buttonTapped: function(button, event) {
  50957. var result = (button.onTap || noop).apply(self, [event]);
  50958. event = event.originalEvent || event; //jquery events
  50959. if (!event.defaultPrevented) {
  50960. self.responseDeferred.resolve(result);
  50961. }
  50962. }
  50963. });
  50964. $q.when(
  50965. options.templateUrl ?
  50966. $ionicTemplateLoader.load(options.templateUrl) :
  50967. (options.template || options.content || '')
  50968. ).then(function(template) {
  50969. var popupBody = jqLite(self.element[0].querySelector('.popup-body'));
  50970. if (template) {
  50971. popupBody.html(template);
  50972. $compile(popupBody.contents())(self.scope);
  50973. } else {
  50974. popupBody.remove();
  50975. }
  50976. });
  50977. self.show = function() {
  50978. if (self.isShown || self.removed) return;
  50979. $ionicModal.stack.add(self);
  50980. self.isShown = true;
  50981. ionic.requestAnimationFrame(function() {
  50982. //if hidden while waiting for raf, don't show
  50983. if (!self.isShown) return;
  50984. self.element.removeClass('popup-hidden');
  50985. self.element.addClass('popup-showing active');
  50986. focusInput(self.element);
  50987. });
  50988. };
  50989. self.hide = function(callback) {
  50990. callback = callback || noop;
  50991. if (!self.isShown) return callback();
  50992. $ionicModal.stack.remove(self);
  50993. self.isShown = false;
  50994. self.element.removeClass('active');
  50995. self.element.addClass('popup-hidden');
  50996. $timeout(callback, 250, false);
  50997. };
  50998. self.remove = function() {
  50999. if (self.removed) return;
  51000. self.hide(function() {
  51001. self.element.remove();
  51002. self.scope.$destroy();
  51003. });
  51004. self.removed = true;
  51005. };
  51006. return self;
  51007. }
  51008. function onHardwareBackButton() {
  51009. var last = popupStack[popupStack.length - 1];
  51010. last && last.responseDeferred.resolve();
  51011. }
  51012. function showPopup(options) {
  51013. var popup = $ionicPopup._createPopup(options);
  51014. var showDelay = 0;
  51015. if (popupStack.length > 0) {
  51016. showDelay = config.stackPushDelay;
  51017. $timeout(popupStack[popupStack.length - 1].hide, showDelay, false);
  51018. } else {
  51019. //Add popup-open & backdrop if this is first popup
  51020. $ionicBody.addClass('popup-open');
  51021. $ionicBackdrop.retain();
  51022. //only show the backdrop on the first popup
  51023. $ionicPopup._backButtonActionDone = $ionicPlatform.registerBackButtonAction(
  51024. onHardwareBackButton,
  51025. IONIC_BACK_PRIORITY.popup
  51026. );
  51027. }
  51028. // Expose a 'close' method on the returned promise
  51029. popup.responseDeferred.promise.close = function popupClose(result) {
  51030. if (!popup.removed) popup.responseDeferred.resolve(result);
  51031. };
  51032. //DEPRECATED: notify the promise with an object with a close method
  51033. popup.responseDeferred.notify({ close: popup.responseDeferred.close });
  51034. doShow();
  51035. return popup.responseDeferred.promise;
  51036. function doShow() {
  51037. popupStack.push(popup);
  51038. $timeout(popup.show, showDelay, false);
  51039. popup.responseDeferred.promise.then(function(result) {
  51040. var index = popupStack.indexOf(popup);
  51041. if (index !== -1) {
  51042. popupStack.splice(index, 1);
  51043. }
  51044. popup.remove();
  51045. if (popupStack.length > 0) {
  51046. popupStack[popupStack.length - 1].show();
  51047. } else {
  51048. $ionicBackdrop.release();
  51049. //Remove popup-open & backdrop if this is last popup
  51050. $timeout(function() {
  51051. // wait to remove this due to a 300ms delay native
  51052. // click which would trigging whatever was underneath this
  51053. if (!popupStack.length) {
  51054. $ionicBody.removeClass('popup-open');
  51055. }
  51056. }, 400, false);
  51057. ($ionicPopup._backButtonActionDone || noop)();
  51058. }
  51059. return result;
  51060. });
  51061. }
  51062. }
  51063. function focusInput(element) {
  51064. var focusOn = element[0].querySelector('[autofocus]');
  51065. if (focusOn) {
  51066. focusOn.focus();
  51067. }
  51068. }
  51069. function showAlert(opts) {
  51070. return showPopup(extend({
  51071. buttons: [{
  51072. text: opts.okText || 'OK',
  51073. type: opts.okType || 'button-positive',
  51074. onTap: function() {
  51075. return true;
  51076. }
  51077. }]
  51078. }, opts || {}));
  51079. }
  51080. function showConfirm(opts) {
  51081. return showPopup(extend({
  51082. buttons: [{
  51083. text: opts.cancelText || 'Cancel',
  51084. type: opts.cancelType || 'button-default',
  51085. onTap: function() { return false; }
  51086. }, {
  51087. text: opts.okText || 'OK',
  51088. type: opts.okType || 'button-positive',
  51089. onTap: function() { return true; }
  51090. }]
  51091. }, opts || {}));
  51092. }
  51093. function showPrompt(opts) {
  51094. var scope = $rootScope.$new(true);
  51095. scope.data = {};
  51096. scope.data.fieldtype = opts.inputType ? opts.inputType : 'text';
  51097. scope.data.response = opts.defaultText ? opts.defaultText : '';
  51098. scope.data.placeholder = opts.inputPlaceholder ? opts.inputPlaceholder : '';
  51099. scope.data.maxlength = opts.maxLength ? parseInt(opts.maxLength) : '';
  51100. var text = '';
  51101. if (opts.template && /<[a-z][\s\S]*>/i.test(opts.template) === false) {
  51102. text = '<span>' + opts.template + '</span>';
  51103. delete opts.template;
  51104. }
  51105. return showPopup(extend({
  51106. template: text + '<input ng-model="data.response" '
  51107. + 'type="{{ data.fieldtype }}"'
  51108. + 'maxlength="{{ data.maxlength }}"'
  51109. + 'placeholder="{{ data.placeholder }}"'
  51110. + '>',
  51111. scope: scope,
  51112. buttons: [{
  51113. text: opts.cancelText || 'Cancel',
  51114. type: opts.cancelType || 'button-default',
  51115. onTap: function() {}
  51116. }, {
  51117. text: opts.okText || 'OK',
  51118. type: opts.okType || 'button-positive',
  51119. onTap: function() {
  51120. return scope.data.response || '';
  51121. }
  51122. }]
  51123. }, opts || {}));
  51124. }
  51125. }]);
  51126. /**
  51127. * @ngdoc service
  51128. * @name $ionicPosition
  51129. * @module ionic
  51130. * @description
  51131. * A set of utility methods that can be use to retrieve position of DOM elements.
  51132. * It is meant to be used where we need to absolute-position DOM elements in
  51133. * relation to other, existing elements (this is the case for tooltips, popovers, etc.).
  51134. *
  51135. * Adapted from [AngularUI Bootstrap](https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js),
  51136. * ([license](https://github.com/angular-ui/bootstrap/blob/master/LICENSE))
  51137. */
  51138. IonicModule
  51139. .factory('$ionicPosition', ['$document', '$window', function($document, $window) {
  51140. function getStyle(el, cssprop) {
  51141. if (el.currentStyle) { //IE
  51142. return el.currentStyle[cssprop];
  51143. } else if ($window.getComputedStyle) {
  51144. return $window.getComputedStyle(el)[cssprop];
  51145. }
  51146. // finally try and get inline style
  51147. return el.style[cssprop];
  51148. }
  51149. /**
  51150. * Checks if a given element is statically positioned
  51151. * @param element - raw DOM element
  51152. */
  51153. function isStaticPositioned(element) {
  51154. return (getStyle(element, 'position') || 'static') === 'static';
  51155. }
  51156. /**
  51157. * returns the closest, non-statically positioned parentOffset of a given element
  51158. * @param element
  51159. */
  51160. var parentOffsetEl = function(element) {
  51161. var docDomEl = $document[0];
  51162. var offsetParent = element.offsetParent || docDomEl;
  51163. while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {
  51164. offsetParent = offsetParent.offsetParent;
  51165. }
  51166. return offsetParent || docDomEl;
  51167. };
  51168. return {
  51169. /**
  51170. * @ngdoc method
  51171. * @name $ionicPosition#position
  51172. * @description Get the current coordinates of the element, relative to the offset parent.
  51173. * Read-only equivalent of [jQuery's position function](http://api.jquery.com/position/).
  51174. * @param {element} element The element to get the position of.
  51175. * @returns {object} Returns an object containing the properties top, left, width and height.
  51176. */
  51177. position: function(element) {
  51178. var elBCR = this.offset(element);
  51179. var offsetParentBCR = { top: 0, left: 0 };
  51180. var offsetParentEl = parentOffsetEl(element[0]);
  51181. if (offsetParentEl != $document[0]) {
  51182. offsetParentBCR = this.offset(jqLite(offsetParentEl));
  51183. offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;
  51184. offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;
  51185. }
  51186. var boundingClientRect = element[0].getBoundingClientRect();
  51187. return {
  51188. width: boundingClientRect.width || element.prop('offsetWidth'),
  51189. height: boundingClientRect.height || element.prop('offsetHeight'),
  51190. top: elBCR.top - offsetParentBCR.top,
  51191. left: elBCR.left - offsetParentBCR.left
  51192. };
  51193. },
  51194. /**
  51195. * @ngdoc method
  51196. * @name $ionicPosition#offset
  51197. * @description Get the current coordinates of the element, relative to the document.
  51198. * Read-only equivalent of [jQuery's offset function](http://api.jquery.com/offset/).
  51199. * @param {element} element The element to get the offset of.
  51200. * @returns {object} Returns an object containing the properties top, left, width and height.
  51201. */
  51202. offset: function(element) {
  51203. var boundingClientRect = element[0].getBoundingClientRect();
  51204. return {
  51205. width: boundingClientRect.width || element.prop('offsetWidth'),
  51206. height: boundingClientRect.height || element.prop('offsetHeight'),
  51207. top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),
  51208. left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)
  51209. };
  51210. }
  51211. };
  51212. }]);
  51213. /**
  51214. * @ngdoc service
  51215. * @name $ionicScrollDelegate
  51216. * @module ionic
  51217. * @description
  51218. * Delegate for controlling scrollViews (created by
  51219. * {@link ionic.directive:ionContent} and
  51220. * {@link ionic.directive:ionScroll} directives).
  51221. *
  51222. * Methods called directly on the $ionicScrollDelegate service will control all scroll
  51223. * views. Use the {@link ionic.service:$ionicScrollDelegate#$getByHandle $getByHandle}
  51224. * method to control specific scrollViews.
  51225. *
  51226. * @usage
  51227. *
  51228. * ```html
  51229. * <body ng-controller="MainCtrl">
  51230. * <ion-content>
  51231. * <button ng-click="scrollTop()">Scroll to Top!</button>
  51232. * </ion-content>
  51233. * </body>
  51234. * ```
  51235. * ```js
  51236. * function MainCtrl($scope, $ionicScrollDelegate) {
  51237. * $scope.scrollTop = function() {
  51238. * $ionicScrollDelegate.scrollTop();
  51239. * };
  51240. * }
  51241. * ```
  51242. *
  51243. * Example of advanced usage, with two scroll areas using `delegate-handle`
  51244. * for fine control.
  51245. *
  51246. * ```html
  51247. * <body ng-controller="MainCtrl">
  51248. * <ion-content delegate-handle="mainScroll">
  51249. * <button ng-click="scrollMainToTop()">
  51250. * Scroll content to top!
  51251. * </button>
  51252. * <ion-scroll delegate-handle="small" style="height: 100px;">
  51253. * <button ng-click="scrollSmallToTop()">
  51254. * Scroll small area to top!
  51255. * </button>
  51256. * </ion-scroll>
  51257. * </ion-content>
  51258. * </body>
  51259. * ```
  51260. * ```js
  51261. * function MainCtrl($scope, $ionicScrollDelegate) {
  51262. * $scope.scrollMainToTop = function() {
  51263. * $ionicScrollDelegate.$getByHandle('mainScroll').scrollTop();
  51264. * };
  51265. * $scope.scrollSmallToTop = function() {
  51266. * $ionicScrollDelegate.$getByHandle('small').scrollTop();
  51267. * };
  51268. * }
  51269. * ```
  51270. */
  51271. IonicModule
  51272. .service('$ionicScrollDelegate', ionic.DelegateService([
  51273. /**
  51274. * @ngdoc method
  51275. * @name $ionicScrollDelegate#resize
  51276. * @description Tell the scrollView to recalculate the size of its container.
  51277. */
  51278. 'resize',
  51279. /**
  51280. * @ngdoc method
  51281. * @name $ionicScrollDelegate#scrollTop
  51282. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51283. */
  51284. 'scrollTop',
  51285. /**
  51286. * @ngdoc method
  51287. * @name $ionicScrollDelegate#scrollBottom
  51288. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51289. */
  51290. 'scrollBottom',
  51291. /**
  51292. * @ngdoc method
  51293. * @name $ionicScrollDelegate#scrollTo
  51294. * @param {number} left The x-value to scroll to.
  51295. * @param {number} top The y-value to scroll to.
  51296. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51297. */
  51298. 'scrollTo',
  51299. /**
  51300. * @ngdoc method
  51301. * @name $ionicScrollDelegate#scrollBy
  51302. * @param {number} left The x-offset to scroll by.
  51303. * @param {number} top The y-offset to scroll by.
  51304. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51305. */
  51306. 'scrollBy',
  51307. /**
  51308. * @ngdoc method
  51309. * @name $ionicScrollDelegate#zoomTo
  51310. * @param {number} level Level to zoom to.
  51311. * @param {boolean=} animate Whether to animate the zoom.
  51312. * @param {number=} originLeft Zoom in at given left coordinate.
  51313. * @param {number=} originTop Zoom in at given top coordinate.
  51314. */
  51315. 'zoomTo',
  51316. /**
  51317. * @ngdoc method
  51318. * @name $ionicScrollDelegate#zoomBy
  51319. * @param {number} factor The factor to zoom by.
  51320. * @param {boolean=} animate Whether to animate the zoom.
  51321. * @param {number=} originLeft Zoom in at given left coordinate.
  51322. * @param {number=} originTop Zoom in at given top coordinate.
  51323. */
  51324. 'zoomBy',
  51325. /**
  51326. * @ngdoc method
  51327. * @name $ionicScrollDelegate#getScrollPosition
  51328. * @returns {object} The scroll position of this view, with the following properties:
  51329. * - `{number}` `left` The distance the user has scrolled from the left (starts at 0).
  51330. * - `{number}` `top` The distance the user has scrolled from the top (starts at 0).
  51331. * - `{number}` `zoom` The current zoom level.
  51332. */
  51333. 'getScrollPosition',
  51334. /**
  51335. * @ngdoc method
  51336. * @name $ionicScrollDelegate#anchorScroll
  51337. * @description Tell the scrollView to scroll to the element with an id
  51338. * matching window.location.hash.
  51339. *
  51340. * If no matching element is found, it will scroll to top.
  51341. *
  51342. * @param {boolean=} shouldAnimate Whether the scroll should animate.
  51343. */
  51344. 'anchorScroll',
  51345. /**
  51346. * @ngdoc method
  51347. * @name $ionicScrollDelegate#freezeScroll
  51348. * @description Does not allow this scroll view to scroll either x or y.
  51349. * @param {boolean=} shouldFreeze Should this scroll view be prevented from scrolling or not.
  51350. * @returns {boolean} If the scroll view is being prevented from scrolling or not.
  51351. */
  51352. 'freezeScroll',
  51353. /**
  51354. * @ngdoc method
  51355. * @name $ionicScrollDelegate#freezeAllScrolls
  51356. * @description Does not allow any of the app's scroll views to scroll either x or y.
  51357. * @param {boolean=} shouldFreeze Should all app scrolls be prevented from scrolling or not.
  51358. */
  51359. 'freezeAllScrolls',
  51360. /**
  51361. * @ngdoc method
  51362. * @name $ionicScrollDelegate#getScrollView
  51363. * @returns {object} The scrollView associated with this delegate.
  51364. */
  51365. 'getScrollView'
  51366. /**
  51367. * @ngdoc method
  51368. * @name $ionicScrollDelegate#$getByHandle
  51369. * @param {string} handle
  51370. * @returns `delegateInstance` A delegate instance that controls only the
  51371. * scrollViews with `delegate-handle` matching the given handle.
  51372. *
  51373. * Example: `$ionicScrollDelegate.$getByHandle('my-handle').scrollTop();`
  51374. */
  51375. ]));
  51376. /**
  51377. * @ngdoc service
  51378. * @name $ionicSideMenuDelegate
  51379. * @module ionic
  51380. *
  51381. * @description
  51382. * Delegate for controlling the {@link ionic.directive:ionSideMenus} directive.
  51383. *
  51384. * Methods called directly on the $ionicSideMenuDelegate service will control all side
  51385. * menus. Use the {@link ionic.service:$ionicSideMenuDelegate#$getByHandle $getByHandle}
  51386. * method to control specific ionSideMenus instances.
  51387. *
  51388. * @usage
  51389. *
  51390. * ```html
  51391. * <body ng-controller="MainCtrl">
  51392. * <ion-side-menus>
  51393. * <ion-side-menu-content>
  51394. * Content!
  51395. * <button ng-click="toggleLeftSideMenu()">
  51396. * Toggle Left Side Menu
  51397. * </button>
  51398. * </ion-side-menu-content>
  51399. * <ion-side-menu side="left">
  51400. * Left Menu!
  51401. * <ion-side-menu>
  51402. * </ion-side-menus>
  51403. * </body>
  51404. * ```
  51405. * ```js
  51406. * function MainCtrl($scope, $ionicSideMenuDelegate) {
  51407. * $scope.toggleLeftSideMenu = function() {
  51408. * $ionicSideMenuDelegate.toggleLeft();
  51409. * };
  51410. * }
  51411. * ```
  51412. */
  51413. IonicModule
  51414. .service('$ionicSideMenuDelegate', ionic.DelegateService([
  51415. /**
  51416. * @ngdoc method
  51417. * @name $ionicSideMenuDelegate#toggleLeft
  51418. * @description Toggle the left side menu (if it exists).
  51419. * @param {boolean=} isOpen Whether to open or close the menu.
  51420. * Default: Toggles the menu.
  51421. */
  51422. 'toggleLeft',
  51423. /**
  51424. * @ngdoc method
  51425. * @name $ionicSideMenuDelegate#toggleRight
  51426. * @description Toggle the right side menu (if it exists).
  51427. * @param {boolean=} isOpen Whether to open or close the menu.
  51428. * Default: Toggles the menu.
  51429. */
  51430. 'toggleRight',
  51431. /**
  51432. * @ngdoc method
  51433. * @name $ionicSideMenuDelegate#getOpenRatio
  51434. * @description Gets the ratio of open amount over menu width. For example, a
  51435. * menu of width 100 that is opened by 50 pixels is 50% opened, and would return
  51436. * a ratio of 0.5.
  51437. *
  51438. * @returns {float} 0 if nothing is open, between 0 and 1 if left menu is
  51439. * opened/opening, and between 0 and -1 if right menu is opened/opening.
  51440. */
  51441. 'getOpenRatio',
  51442. /**
  51443. * @ngdoc method
  51444. * @name $ionicSideMenuDelegate#isOpen
  51445. * @returns {boolean} Whether either the left or right menu is currently opened.
  51446. */
  51447. 'isOpen',
  51448. /**
  51449. * @ngdoc method
  51450. * @name $ionicSideMenuDelegate#isOpenLeft
  51451. * @returns {boolean} Whether the left menu is currently opened.
  51452. */
  51453. 'isOpenLeft',
  51454. /**
  51455. * @ngdoc method
  51456. * @name $ionicSideMenuDelegate#isOpenRight
  51457. * @returns {boolean} Whether the right menu is currently opened.
  51458. */
  51459. 'isOpenRight',
  51460. /**
  51461. * @ngdoc method
  51462. * @name $ionicSideMenuDelegate#canDragContent
  51463. * @param {boolean=} canDrag Set whether the content can or cannot be dragged to open
  51464. * side menus.
  51465. * @returns {boolean} Whether the content can be dragged to open side menus.
  51466. */
  51467. 'canDragContent',
  51468. /**
  51469. * @ngdoc method
  51470. * @name $ionicSideMenuDelegate#edgeDragThreshold
  51471. * @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:
  51472. * - 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.
  51473. * - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
  51474. * - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
  51475. * @returns {boolean} Whether the drag can start only from within the edge of screen threshold.
  51476. */
  51477. 'edgeDragThreshold'
  51478. /**
  51479. * @ngdoc method
  51480. * @name $ionicSideMenuDelegate#$getByHandle
  51481. * @param {string} handle
  51482. * @returns `delegateInstance` A delegate instance that controls only the
  51483. * {@link ionic.directive:ionSideMenus} directives with `delegate-handle` matching
  51484. * the given handle.
  51485. *
  51486. * Example: `$ionicSideMenuDelegate.$getByHandle('my-handle').toggleLeft();`
  51487. */
  51488. ]));
  51489. /**
  51490. * @ngdoc service
  51491. * @name $ionicSlideBoxDelegate
  51492. * @module ionic
  51493. * @description
  51494. * Delegate that controls the {@link ionic.directive:ionSlideBox} directive.
  51495. *
  51496. * Methods called directly on the $ionicSlideBoxDelegate service will control all slide boxes. Use the {@link ionic.service:$ionicSlideBoxDelegate#$getByHandle $getByHandle}
  51497. * method to control specific slide box instances.
  51498. *
  51499. * @usage
  51500. *
  51501. * ```html
  51502. * <ion-view>
  51503. * <ion-slide-box>
  51504. * <ion-slide>
  51505. * <div class="box blue">
  51506. * <button ng-click="nextSlide()">Next slide!</button>
  51507. * </div>
  51508. * </ion-slide>
  51509. * <ion-slide>
  51510. * <div class="box red">
  51511. * Slide 2!
  51512. * </div>
  51513. * </ion-slide>
  51514. * </ion-slide-box>
  51515. * </ion-view>
  51516. * ```
  51517. * ```js
  51518. * function MyCtrl($scope, $ionicSlideBoxDelegate) {
  51519. * $scope.nextSlide = function() {
  51520. * $ionicSlideBoxDelegate.next();
  51521. * }
  51522. * }
  51523. * ```
  51524. */
  51525. IonicModule
  51526. .service('$ionicSlideBoxDelegate', ionic.DelegateService([
  51527. /**
  51528. * @ngdoc method
  51529. * @name $ionicSlideBoxDelegate#update
  51530. * @description
  51531. * Update the slidebox (for example if using Angular with ng-repeat,
  51532. * resize it for the elements inside).
  51533. */
  51534. 'update',
  51535. /**
  51536. * @ngdoc method
  51537. * @name $ionicSlideBoxDelegate#slide
  51538. * @param {number} to The index to slide to.
  51539. * @param {number=} speed The number of milliseconds the change should take.
  51540. */
  51541. 'slide',
  51542. 'select',
  51543. /**
  51544. * @ngdoc method
  51545. * @name $ionicSlideBoxDelegate#enableSlide
  51546. * @param {boolean=} shouldEnable Whether to enable sliding the slidebox.
  51547. * @returns {boolean} Whether sliding is enabled.
  51548. */
  51549. 'enableSlide',
  51550. /**
  51551. * @ngdoc method
  51552. * @name $ionicSlideBoxDelegate#previous
  51553. * @param {number=} speed The number of milliseconds the change should take.
  51554. * @description Go to the previous slide. Wraps around if at the beginning.
  51555. */
  51556. 'previous',
  51557. /**
  51558. * @ngdoc method
  51559. * @name $ionicSlideBoxDelegate#next
  51560. * @param {number=} speed The number of milliseconds the change should take.
  51561. * @description Go to the next slide. Wraps around if at the end.
  51562. */
  51563. 'next',
  51564. /**
  51565. * @ngdoc method
  51566. * @name $ionicSlideBoxDelegate#stop
  51567. * @description Stop sliding. The slideBox will not move again until
  51568. * explicitly told to do so.
  51569. */
  51570. 'stop',
  51571. 'autoPlay',
  51572. /**
  51573. * @ngdoc method
  51574. * @name $ionicSlideBoxDelegate#start
  51575. * @description Start sliding again if the slideBox was stopped.
  51576. */
  51577. 'start',
  51578. /**
  51579. * @ngdoc method
  51580. * @name $ionicSlideBoxDelegate#currentIndex
  51581. * @returns number The index of the current slide.
  51582. */
  51583. 'currentIndex',
  51584. 'selected',
  51585. /**
  51586. * @ngdoc method
  51587. * @name $ionicSlideBoxDelegate#slidesCount
  51588. * @returns number The number of slides there are currently.
  51589. */
  51590. 'slidesCount',
  51591. 'count',
  51592. 'loop'
  51593. /**
  51594. * @ngdoc method
  51595. * @name $ionicSlideBoxDelegate#$getByHandle
  51596. * @param {string} handle
  51597. * @returns `delegateInstance` A delegate instance that controls only the
  51598. * {@link ionic.directive:ionSlideBox} directives with `delegate-handle` matching
  51599. * the given handle.
  51600. *
  51601. * Example: `$ionicSlideBoxDelegate.$getByHandle('my-handle').stop();`
  51602. */
  51603. ]));
  51604. /**
  51605. * @ngdoc service
  51606. * @name $ionicTabsDelegate
  51607. * @module ionic
  51608. *
  51609. * @description
  51610. * Delegate for controlling the {@link ionic.directive:ionTabs} directive.
  51611. *
  51612. * Methods called directly on the $ionicTabsDelegate service will control all ionTabs
  51613. * directives. Use the {@link ionic.service:$ionicTabsDelegate#$getByHandle $getByHandle}
  51614. * method to control specific ionTabs instances.
  51615. *
  51616. * @usage
  51617. *
  51618. * ```html
  51619. * <body ng-controller="MyCtrl">
  51620. * <ion-tabs>
  51621. *
  51622. * <ion-tab title="Tab 1">
  51623. * Hello tab 1!
  51624. * <button ng-click="selectTabWithIndex(1)">Select tab 2!</button>
  51625. * </ion-tab>
  51626. * <ion-tab title="Tab 2">Hello tab 2!</ion-tab>
  51627. *
  51628. * </ion-tabs>
  51629. * </body>
  51630. * ```
  51631. * ```js
  51632. * function MyCtrl($scope, $ionicTabsDelegate) {
  51633. * $scope.selectTabWithIndex = function(index) {
  51634. * $ionicTabsDelegate.select(index);
  51635. * }
  51636. * }
  51637. * ```
  51638. */
  51639. IonicModule
  51640. .service('$ionicTabsDelegate', ionic.DelegateService([
  51641. /**
  51642. * @ngdoc method
  51643. * @name $ionicTabsDelegate#select
  51644. * @description Select the tab matching the given index.
  51645. *
  51646. * @param {number} index Index of the tab to select.
  51647. */
  51648. 'select',
  51649. /**
  51650. * @ngdoc method
  51651. * @name $ionicTabsDelegate#selectedIndex
  51652. * @returns `number` The index of the selected tab, or -1.
  51653. */
  51654. 'selectedIndex',
  51655. /**
  51656. * @ngdoc method
  51657. * @name $ionicTabsDelegate#showBar
  51658. * @description
  51659. * Set/get whether the {@link ionic.directive:ionTabs} is shown
  51660. * @param {boolean} show Whether to show the bar.
  51661. * @returns {boolean} Whether the bar is shown.
  51662. */
  51663. 'showBar'
  51664. /**
  51665. * @ngdoc method
  51666. * @name $ionicTabsDelegate#$getByHandle
  51667. * @param {string} handle
  51668. * @returns `delegateInstance` A delegate instance that controls only the
  51669. * {@link ionic.directive:ionTabs} directives with `delegate-handle` matching
  51670. * the given handle.
  51671. *
  51672. * Example: `$ionicTabsDelegate.$getByHandle('my-handle').select(0);`
  51673. */
  51674. ]));
  51675. // closure to keep things neat
  51676. (function() {
  51677. var templatesToCache = [];
  51678. /**
  51679. * @ngdoc service
  51680. * @name $ionicTemplateCache
  51681. * @module ionic
  51682. * @description A service that preemptively caches template files to eliminate transition flicker and boost performance.
  51683. * @usage
  51684. * State templates are cached automatically, but you can optionally cache other templates.
  51685. *
  51686. * ```js
  51687. * $ionicTemplateCache('myNgIncludeTemplate.html');
  51688. * ```
  51689. *
  51690. * Optionally disable all preemptive caching with the `$ionicConfigProvider` or individual states by setting `prefetchTemplate`
  51691. * in the `$state` definition
  51692. *
  51693. * ```js
  51694. * angular.module('myApp', ['ionic'])
  51695. * .config(function($stateProvider, $ionicConfigProvider) {
  51696. *
  51697. * // disable preemptive template caching globally
  51698. * $ionicConfigProvider.templates.prefetch(false);
  51699. *
  51700. * // disable individual states
  51701. * $stateProvider
  51702. * .state('tabs', {
  51703. * url: "/tab",
  51704. * abstract: true,
  51705. * prefetchTemplate: false,
  51706. * templateUrl: "tabs-templates/tabs.html"
  51707. * })
  51708. * .state('tabs.home', {
  51709. * url: "/home",
  51710. * views: {
  51711. * 'home-tab': {
  51712. * prefetchTemplate: false,
  51713. * templateUrl: "tabs-templates/home.html",
  51714. * controller: 'HomeTabCtrl'
  51715. * }
  51716. * }
  51717. * });
  51718. * });
  51719. * ```
  51720. */
  51721. IonicModule
  51722. .factory('$ionicTemplateCache', [
  51723. '$http',
  51724. '$templateCache',
  51725. '$timeout',
  51726. function($http, $templateCache, $timeout) {
  51727. var toCache = templatesToCache,
  51728. hasRun;
  51729. function $ionicTemplateCache(templates) {
  51730. if (typeof templates === 'undefined') {
  51731. return run();
  51732. }
  51733. if (isString(templates)) {
  51734. templates = [templates];
  51735. }
  51736. forEach(templates, function(template) {
  51737. toCache.push(template);
  51738. });
  51739. if (hasRun) {
  51740. run();
  51741. }
  51742. }
  51743. // run through methods - internal method
  51744. function run() {
  51745. var template;
  51746. $ionicTemplateCache._runCount++;
  51747. hasRun = true;
  51748. // ignore if race condition already zeroed out array
  51749. if (toCache.length === 0) return;
  51750. var i = 0;
  51751. while (i < 4 && (template = toCache.pop())) {
  51752. // note that inline templates are ignored by this request
  51753. if (isString(template)) $http.get(template, { cache: $templateCache });
  51754. i++;
  51755. }
  51756. // only preload 3 templates a second
  51757. if (toCache.length) {
  51758. $timeout(run, 1000);
  51759. }
  51760. }
  51761. // exposing for testing
  51762. $ionicTemplateCache._runCount = 0;
  51763. // default method
  51764. return $ionicTemplateCache;
  51765. }])
  51766. // Intercepts the $stateprovider.state() command to look for templateUrls that can be cached
  51767. .config([
  51768. '$stateProvider',
  51769. '$ionicConfigProvider',
  51770. function($stateProvider, $ionicConfigProvider) {
  51771. var stateProviderState = $stateProvider.state;
  51772. $stateProvider.state = function(stateName, definition) {
  51773. // don't even bother if it's disabled. note, another config may run after this, so it's not a catch-all
  51774. if (typeof definition === 'object') {
  51775. var enabled = definition.prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();
  51776. if (enabled && isString(definition.templateUrl)) templatesToCache.push(definition.templateUrl);
  51777. if (angular.isObject(definition.views)) {
  51778. for (var key in definition.views) {
  51779. enabled = definition.views[key].prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();
  51780. if (enabled && isString(definition.views[key].templateUrl)) templatesToCache.push(definition.views[key].templateUrl);
  51781. }
  51782. }
  51783. }
  51784. return stateProviderState.call($stateProvider, stateName, definition);
  51785. };
  51786. }])
  51787. // process the templateUrls collected by the $stateProvider, adding them to the cache
  51788. .run(['$ionicTemplateCache', function($ionicTemplateCache) {
  51789. $ionicTemplateCache();
  51790. }]);
  51791. })();
  51792. IonicModule
  51793. .factory('$ionicTemplateLoader', [
  51794. '$compile',
  51795. '$controller',
  51796. '$http',
  51797. '$q',
  51798. '$rootScope',
  51799. '$templateCache',
  51800. function($compile, $controller, $http, $q, $rootScope, $templateCache) {
  51801. return {
  51802. load: fetchTemplate,
  51803. compile: loadAndCompile
  51804. };
  51805. function fetchTemplate(url) {
  51806. return $http.get(url, {cache: $templateCache})
  51807. .then(function(response) {
  51808. return response.data && response.data.trim();
  51809. });
  51810. }
  51811. function loadAndCompile(options) {
  51812. options = extend({
  51813. template: '',
  51814. templateUrl: '',
  51815. scope: null,
  51816. controller: null,
  51817. locals: {},
  51818. appendTo: null
  51819. }, options || {});
  51820. var templatePromise = options.templateUrl ?
  51821. this.load(options.templateUrl) :
  51822. $q.when(options.template);
  51823. return templatePromise.then(function(template) {
  51824. var controller;
  51825. var scope = options.scope || $rootScope.$new();
  51826. //Incase template doesn't have just one root element, do this
  51827. var element = jqLite('<div>').html(template).contents();
  51828. if (options.controller) {
  51829. controller = $controller(
  51830. options.controller,
  51831. extend(options.locals, {
  51832. $scope: scope
  51833. })
  51834. );
  51835. element.children().data('$ngControllerController', controller);
  51836. }
  51837. if (options.appendTo) {
  51838. jqLite(options.appendTo).append(element);
  51839. }
  51840. $compile(element)(scope);
  51841. return {
  51842. element: element,
  51843. scope: scope
  51844. };
  51845. });
  51846. }
  51847. }]);
  51848. /**
  51849. * @private
  51850. * DEPRECATED, as of v1.0.0-beta14 -------
  51851. */
  51852. IonicModule
  51853. .factory('$ionicViewService', ['$ionicHistory', '$log', function($ionicHistory, $log) {
  51854. function warn(oldMethod, newMethod) {
  51855. $log.warn('$ionicViewService' + oldMethod + ' is deprecated, please use $ionicHistory' + newMethod + ' instead: http://ionicframework.com/docs/nightly/api/service/$ionicHistory/');
  51856. }
  51857. warn('', '');
  51858. var methodsMap = {
  51859. getCurrentView: 'currentView',
  51860. getBackView: 'backView',
  51861. getForwardView: 'forwardView',
  51862. getCurrentStateName: 'currentStateName',
  51863. nextViewOptions: 'nextViewOptions',
  51864. clearHistory: 'clearHistory'
  51865. };
  51866. forEach(methodsMap, function(newMethod, oldMethod) {
  51867. methodsMap[oldMethod] = function() {
  51868. warn('.' + oldMethod, '.' + newMethod);
  51869. return $ionicHistory[newMethod].apply(this, arguments);
  51870. };
  51871. });
  51872. return methodsMap;
  51873. }]);
  51874. /**
  51875. * @private
  51876. * TODO document
  51877. */
  51878. IonicModule.factory('$ionicViewSwitcher', [
  51879. '$timeout',
  51880. '$document',
  51881. '$q',
  51882. '$ionicClickBlock',
  51883. '$ionicConfig',
  51884. '$ionicNavBarDelegate',
  51885. function($timeout, $document, $q, $ionicClickBlock, $ionicConfig, $ionicNavBarDelegate) {
  51886. var TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
  51887. var DATA_NO_CACHE = '$noCache';
  51888. var DATA_DESTROY_ELE = '$destroyEle';
  51889. var DATA_ELE_IDENTIFIER = '$eleId';
  51890. var DATA_VIEW_ACCESSED = '$accessed';
  51891. var DATA_FALLBACK_TIMER = '$fallbackTimer';
  51892. var DATA_VIEW = '$viewData';
  51893. var NAV_VIEW_ATTR = 'nav-view';
  51894. var VIEW_STATUS_ACTIVE = 'active';
  51895. var VIEW_STATUS_CACHED = 'cached';
  51896. var VIEW_STATUS_STAGED = 'stage';
  51897. var transitionCounter = 0;
  51898. var nextTransition, nextDirection;
  51899. ionic.transition = ionic.transition || {};
  51900. ionic.transition.isActive = false;
  51901. var isActiveTimer;
  51902. var cachedAttr = ionic.DomUtil.cachedAttr;
  51903. var transitionPromises = [];
  51904. var defaultTimeout = 1100;
  51905. var ionicViewSwitcher = {
  51906. create: function(navViewCtrl, viewLocals, enteringView, leavingView, renderStart, renderEnd) {
  51907. // get a reference to an entering/leaving element if they exist
  51908. // loop through to see if the view is already in the navViewElement
  51909. var enteringEle, leavingEle;
  51910. var transitionId = ++transitionCounter;
  51911. var alreadyInDom;
  51912. var switcher = {
  51913. init: function(registerData, callback) {
  51914. ionicViewSwitcher.isTransitioning(true);
  51915. switcher.loadViewElements(registerData);
  51916. switcher.render(registerData, function() {
  51917. callback && callback();
  51918. });
  51919. },
  51920. loadViewElements: function(registerData) {
  51921. var x, l, viewEle;
  51922. var viewElements = navViewCtrl.getViewElements();
  51923. var enteringEleIdentifier = getViewElementIdentifier(viewLocals, enteringView);
  51924. var navViewActiveEleId = navViewCtrl.activeEleId();
  51925. for (x = 0, l = viewElements.length; x < l; x++) {
  51926. viewEle = viewElements.eq(x);
  51927. if (viewEle.data(DATA_ELE_IDENTIFIER) === enteringEleIdentifier) {
  51928. // we found an existing element in the DOM that should be entering the view
  51929. if (viewEle.data(DATA_NO_CACHE)) {
  51930. // the existing element should not be cached, don't use it
  51931. viewEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier + ionic.Utils.nextUid());
  51932. viewEle.data(DATA_DESTROY_ELE, true);
  51933. } else {
  51934. enteringEle = viewEle;
  51935. }
  51936. } else if (isDefined(navViewActiveEleId) && viewEle.data(DATA_ELE_IDENTIFIER) === navViewActiveEleId) {
  51937. leavingEle = viewEle;
  51938. }
  51939. if (enteringEle && leavingEle) break;
  51940. }
  51941. alreadyInDom = !!enteringEle;
  51942. if (!alreadyInDom) {
  51943. // still no existing element to use
  51944. // create it using existing template/scope/locals
  51945. enteringEle = registerData.ele || ionicViewSwitcher.createViewEle(viewLocals);
  51946. // existing elements in the DOM are looked up by their state name and state id
  51947. enteringEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier);
  51948. }
  51949. if (renderEnd) {
  51950. navViewCtrl.activeEleId(enteringEleIdentifier);
  51951. }
  51952. registerData.ele = null;
  51953. },
  51954. render: function(registerData, callback) {
  51955. if (alreadyInDom) {
  51956. // it was already found in the DOM, just reconnect the scope
  51957. ionic.Utils.reconnectScope(enteringEle.scope());
  51958. } else {
  51959. // the entering element is not already in the DOM
  51960. // set that the entering element should be "staged" and its
  51961. // styles of where this element will go before it hits the DOM
  51962. navViewAttr(enteringEle, VIEW_STATUS_STAGED);
  51963. var enteringData = getTransitionData(viewLocals, enteringEle, registerData.direction, enteringView);
  51964. var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;
  51965. transitionFn(enteringEle, null, enteringData.direction, true).run(0);
  51966. enteringEle.data(DATA_VIEW, {
  51967. viewId: enteringData.viewId,
  51968. historyId: enteringData.historyId,
  51969. stateName: enteringData.stateName,
  51970. stateParams: enteringData.stateParams
  51971. });
  51972. // if the current state has cache:false
  51973. // or the element has cache-view="false" attribute
  51974. if (viewState(viewLocals).cache === false || viewState(viewLocals).cache === 'false' ||
  51975. enteringEle.attr('cache-view') == 'false' || $ionicConfig.views.maxCache() === 0) {
  51976. enteringEle.data(DATA_NO_CACHE, true);
  51977. }
  51978. // append the entering element to the DOM, create a new scope and run link
  51979. var viewScope = navViewCtrl.appendViewElement(enteringEle, viewLocals);
  51980. delete enteringData.direction;
  51981. delete enteringData.transition;
  51982. viewScope.$emit('$ionicView.loaded', enteringData);
  51983. }
  51984. // update that this view was just accessed
  51985. enteringEle.data(DATA_VIEW_ACCESSED, Date.now());
  51986. callback && callback();
  51987. },
  51988. transition: function(direction, enableBack, allowAnimate) {
  51989. var deferred;
  51990. var enteringData = getTransitionData(viewLocals, enteringEle, direction, enteringView);
  51991. var leavingData = extend(extend({}, enteringData), getViewData(leavingView));
  51992. enteringData.transitionId = leavingData.transitionId = transitionId;
  51993. enteringData.fromCache = !!alreadyInDom;
  51994. enteringData.enableBack = !!enableBack;
  51995. enteringData.renderStart = renderStart;
  51996. enteringData.renderEnd = renderEnd;
  51997. cachedAttr(enteringEle.parent(), 'nav-view-transition', enteringData.transition);
  51998. cachedAttr(enteringEle.parent(), 'nav-view-direction', enteringData.direction);
  51999. // cancel any previous transition complete fallbacks
  52000. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  52001. // get the transition ready and see if it'll animate
  52002. var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;
  52003. var viewTransition = transitionFn(enteringEle, leavingEle, enteringData.direction,
  52004. enteringData.shouldAnimate && allowAnimate && renderEnd);
  52005. if (viewTransition.shouldAnimate) {
  52006. // attach transitionend events (and fallback timer)
  52007. enteringEle.on(TRANSITIONEND_EVENT, completeOnTransitionEnd);
  52008. enteringEle.data(DATA_FALLBACK_TIMER, $timeout(transitionComplete, defaultTimeout));
  52009. $ionicClickBlock.show(defaultTimeout);
  52010. }
  52011. if (renderStart) {
  52012. // notify the views "before" the transition starts
  52013. switcher.emit('before', enteringData, leavingData);
  52014. // stage entering element, opacity 0, no transition duration
  52015. navViewAttr(enteringEle, VIEW_STATUS_STAGED);
  52016. // render the elements in the correct location for their starting point
  52017. viewTransition.run(0);
  52018. }
  52019. if (renderEnd) {
  52020. // create a promise so we can keep track of when all transitions finish
  52021. // only required if this transition should complete
  52022. deferred = $q.defer();
  52023. transitionPromises.push(deferred.promise);
  52024. }
  52025. if (renderStart && renderEnd) {
  52026. // CSS "auto" transitioned, not manually transitioned
  52027. // wait a frame so the styles apply before auto transitioning
  52028. $timeout(function() {
  52029. ionic.requestAnimationFrame(onReflow);
  52030. });
  52031. } else if (!renderEnd) {
  52032. // just the start of a manual transition
  52033. // but it will not render the end of the transition
  52034. navViewAttr(enteringEle, 'entering');
  52035. navViewAttr(leavingEle, 'leaving');
  52036. // return the transition run method so each step can be ran manually
  52037. return {
  52038. run: viewTransition.run,
  52039. cancel: function(shouldAnimate) {
  52040. if (shouldAnimate) {
  52041. enteringEle.on(TRANSITIONEND_EVENT, cancelOnTransitionEnd);
  52042. enteringEle.data(DATA_FALLBACK_TIMER, $timeout(cancelTransition, defaultTimeout));
  52043. $ionicClickBlock.show(defaultTimeout);
  52044. } else {
  52045. cancelTransition();
  52046. }
  52047. viewTransition.shouldAnimate = shouldAnimate;
  52048. viewTransition.run(0);
  52049. viewTransition = null;
  52050. }
  52051. };
  52052. } else if (renderEnd) {
  52053. // just the end of a manual transition
  52054. // happens after the manual transition has completed
  52055. // and a full history change has happened
  52056. onReflow();
  52057. }
  52058. function onReflow() {
  52059. // remove that we're staging the entering element so it can auto transition
  52060. navViewAttr(enteringEle, viewTransition.shouldAnimate ? 'entering' : VIEW_STATUS_ACTIVE);
  52061. navViewAttr(leavingEle, viewTransition.shouldAnimate ? 'leaving' : VIEW_STATUS_CACHED);
  52062. // start the auto transition and let the CSS take over
  52063. viewTransition.run(1);
  52064. // trigger auto transitions on the associated nav bars
  52065. $ionicNavBarDelegate._instances.forEach(function(instance) {
  52066. instance.triggerTransitionStart(transitionId);
  52067. });
  52068. if (!viewTransition.shouldAnimate) {
  52069. // no animated auto transition
  52070. transitionComplete();
  52071. }
  52072. }
  52073. // Make sure that transitionend events bubbling up from children won't fire
  52074. // transitionComplete. Will only go forward if ev.target == the element listening.
  52075. function completeOnTransitionEnd(ev) {
  52076. if (ev.target !== this) return;
  52077. transitionComplete();
  52078. }
  52079. function transitionComplete() {
  52080. if (transitionComplete.x) return;
  52081. transitionComplete.x = true;
  52082. enteringEle.off(TRANSITIONEND_EVENT, completeOnTransitionEnd);
  52083. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  52084. leavingEle && $timeout.cancel(leavingEle.data(DATA_FALLBACK_TIMER));
  52085. // resolve that this one transition (there could be many w/ nested views)
  52086. deferred && deferred.resolve(navViewCtrl);
  52087. // the most recent transition added has completed and all the active
  52088. // transition promises should be added to the services array of promises
  52089. if (transitionId === transitionCounter) {
  52090. $q.all(transitionPromises).then(ionicViewSwitcher.transitionEnd);
  52091. // emit that the views have finished transitioning
  52092. // each parent nav-view will update which views are active and cached
  52093. switcher.emit('after', enteringData, leavingData);
  52094. switcher.cleanup(enteringData);
  52095. }
  52096. // tell the nav bars that the transition has ended
  52097. $ionicNavBarDelegate._instances.forEach(function(instance) {
  52098. instance.triggerTransitionEnd();
  52099. });
  52100. // remove any references that could cause memory issues
  52101. nextTransition = nextDirection = enteringView = leavingView = enteringEle = leavingEle = null;
  52102. }
  52103. // Make sure that transitionend events bubbling up from children won't fire
  52104. // transitionComplete. Will only go forward if ev.target == the element listening.
  52105. function cancelOnTransitionEnd(ev) {
  52106. if (ev.target !== this) return;
  52107. cancelTransition();
  52108. }
  52109. function cancelTransition() {
  52110. navViewAttr(enteringEle, VIEW_STATUS_CACHED);
  52111. navViewAttr(leavingEle, VIEW_STATUS_ACTIVE);
  52112. enteringEle.off(TRANSITIONEND_EVENT, cancelOnTransitionEnd);
  52113. $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));
  52114. ionicViewSwitcher.transitionEnd([navViewCtrl]);
  52115. }
  52116. },
  52117. emit: function(step, enteringData, leavingData) {
  52118. var enteringScope = getScopeForElement(enteringEle, enteringData);
  52119. var leavingScope = getScopeForElement(leavingEle, leavingData);
  52120. var prefixesAreEqual;
  52121. if ( !enteringData.viewId || enteringData.abstractView ) {
  52122. // it's an abstract view, so treat it accordingly
  52123. // we only get access to the leaving scope once in the transition,
  52124. // so dispatch all events right away if it exists
  52125. if ( leavingScope ) {
  52126. leavingScope.$emit('$ionicView.beforeLeave', leavingData);
  52127. leavingScope.$emit('$ionicView.leave', leavingData);
  52128. leavingScope.$emit('$ionicView.afterLeave', leavingData);
  52129. leavingScope.$broadcast('$ionicParentView.beforeLeave', leavingData);
  52130. leavingScope.$broadcast('$ionicParentView.leave', leavingData);
  52131. leavingScope.$broadcast('$ionicParentView.afterLeave', leavingData);
  52132. }
  52133. }
  52134. else {
  52135. // it's a regular view, so do the normal process
  52136. if (step == 'after') {
  52137. if (enteringScope) {
  52138. enteringScope.$emit('$ionicView.enter', enteringData);
  52139. enteringScope.$broadcast('$ionicParentView.enter', enteringData);
  52140. }
  52141. if (leavingScope) {
  52142. leavingScope.$emit('$ionicView.leave', leavingData);
  52143. leavingScope.$broadcast('$ionicParentView.leave', leavingData);
  52144. }
  52145. else if (enteringScope && leavingData && leavingData.viewId && enteringData.stateName !== leavingData.stateName) {
  52146. // we only want to dispatch this when we are doing a single-tier
  52147. // state change such as changing a tab, so compare the state
  52148. // for the same state-prefix but different suffix
  52149. prefixesAreEqual = compareStatePrefixes(enteringData.stateName, leavingData.stateName);
  52150. if ( prefixesAreEqual ) {
  52151. enteringScope.$emit('$ionicNavView.leave', leavingData);
  52152. }
  52153. }
  52154. }
  52155. if (enteringScope) {
  52156. enteringScope.$emit('$ionicView.' + step + 'Enter', enteringData);
  52157. enteringScope.$broadcast('$ionicParentView.' + step + 'Enter', enteringData);
  52158. }
  52159. if (leavingScope) {
  52160. leavingScope.$emit('$ionicView.' + step + 'Leave', leavingData);
  52161. leavingScope.$broadcast('$ionicParentView.' + step + 'Leave', leavingData);
  52162. } else if (enteringScope && leavingData && leavingData.viewId && enteringData.stateName !== leavingData.stateName) {
  52163. // we only want to dispatch this when we are doing a single-tier
  52164. // state change such as changing a tab, so compare the state
  52165. // for the same state-prefix but different suffix
  52166. prefixesAreEqual = compareStatePrefixes(enteringData.stateName, leavingData.stateName);
  52167. if ( prefixesAreEqual ) {
  52168. enteringScope.$emit('$ionicNavView.' + step + 'Leave', leavingData);
  52169. }
  52170. }
  52171. }
  52172. },
  52173. cleanup: function(transData) {
  52174. // check if any views should be removed
  52175. if (leavingEle && transData.direction == 'back' && !$ionicConfig.views.forwardCache()) {
  52176. // if they just navigated back we can destroy the forward view
  52177. // do not remove forward views if cacheForwardViews config is true
  52178. destroyViewEle(leavingEle);
  52179. }
  52180. var viewElements = navViewCtrl.getViewElements();
  52181. var viewElementsLength = viewElements.length;
  52182. var x, viewElement;
  52183. var removeOldestAccess = (viewElementsLength - 1) > $ionicConfig.views.maxCache();
  52184. var removableEle;
  52185. var oldestAccess = Date.now();
  52186. for (x = 0; x < viewElementsLength; x++) {
  52187. viewElement = viewElements.eq(x);
  52188. if (removeOldestAccess && viewElement.data(DATA_VIEW_ACCESSED) < oldestAccess) {
  52189. // remember what was the oldest element to be accessed so it can be destroyed
  52190. oldestAccess = viewElement.data(DATA_VIEW_ACCESSED);
  52191. removableEle = viewElements.eq(x);
  52192. } else if (viewElement.data(DATA_DESTROY_ELE) && navViewAttr(viewElement) != VIEW_STATUS_ACTIVE) {
  52193. destroyViewEle(viewElement);
  52194. }
  52195. }
  52196. destroyViewEle(removableEle);
  52197. if (enteringEle.data(DATA_NO_CACHE)) {
  52198. enteringEle.data(DATA_DESTROY_ELE, true);
  52199. }
  52200. },
  52201. enteringEle: function() { return enteringEle; },
  52202. leavingEle: function() { return leavingEle; }
  52203. };
  52204. return switcher;
  52205. },
  52206. transitionEnd: function(navViewCtrls) {
  52207. forEach(navViewCtrls, function(navViewCtrl) {
  52208. navViewCtrl.transitionEnd();
  52209. });
  52210. ionicViewSwitcher.isTransitioning(false);
  52211. $ionicClickBlock.hide();
  52212. transitionPromises = [];
  52213. },
  52214. nextTransition: function(val) {
  52215. nextTransition = val;
  52216. },
  52217. nextDirection: function(val) {
  52218. nextDirection = val;
  52219. },
  52220. isTransitioning: function(val) {
  52221. if (arguments.length) {
  52222. ionic.transition.isActive = !!val;
  52223. $timeout.cancel(isActiveTimer);
  52224. if (val) {
  52225. isActiveTimer = $timeout(function() {
  52226. ionicViewSwitcher.isTransitioning(false);
  52227. }, 999);
  52228. }
  52229. }
  52230. return ionic.transition.isActive;
  52231. },
  52232. createViewEle: function(viewLocals) {
  52233. var containerEle = $document[0].createElement('div');
  52234. if (viewLocals && viewLocals.$template) {
  52235. containerEle.innerHTML = viewLocals.$template;
  52236. if (containerEle.children.length === 1) {
  52237. containerEle.children[0].classList.add('pane');
  52238. if ( viewLocals.$$state && viewLocals.$$state.self && viewLocals.$$state.self['abstract'] ) {
  52239. angular.element(containerEle.children[0]).attr("abstract", "true");
  52240. }
  52241. else {
  52242. if ( viewLocals.$$state && viewLocals.$$state.self ) {
  52243. angular.element(containerEle.children[0]).attr("state", viewLocals.$$state.self.name);
  52244. }
  52245. }
  52246. return jqLite(containerEle.children[0]);
  52247. }
  52248. }
  52249. containerEle.className = "pane";
  52250. return jqLite(containerEle);
  52251. },
  52252. viewEleIsActive: function(viewEle, isActiveAttr) {
  52253. navViewAttr(viewEle, isActiveAttr ? VIEW_STATUS_ACTIVE : VIEW_STATUS_CACHED);
  52254. },
  52255. getTransitionData: getTransitionData,
  52256. navViewAttr: navViewAttr,
  52257. destroyViewEle: destroyViewEle
  52258. };
  52259. return ionicViewSwitcher;
  52260. function getViewElementIdentifier(locals, view) {
  52261. if (viewState(locals)['abstract']) return viewState(locals).name;
  52262. if (view) return view.stateId || view.viewId;
  52263. return ionic.Utils.nextUid();
  52264. }
  52265. function viewState(locals) {
  52266. return locals && locals.$$state && locals.$$state.self || {};
  52267. }
  52268. function getTransitionData(viewLocals, enteringEle, direction, view) {
  52269. // Priority
  52270. // 1) attribute directive on the button/link to this view
  52271. // 2) entering element's attribute
  52272. // 3) entering view's $state config property
  52273. // 4) view registration data
  52274. // 5) global config
  52275. // 6) fallback value
  52276. var state = viewState(viewLocals);
  52277. var viewTransition = nextTransition || cachedAttr(enteringEle, 'view-transition') || state.viewTransition || $ionicConfig.views.transition() || 'ios';
  52278. var navBarTransition = $ionicConfig.navBar.transition();
  52279. direction = nextDirection || cachedAttr(enteringEle, 'view-direction') || state.viewDirection || direction || 'none';
  52280. return extend(getViewData(view), {
  52281. transition: viewTransition,
  52282. navBarTransition: navBarTransition === 'view' ? viewTransition : navBarTransition,
  52283. direction: direction,
  52284. shouldAnimate: (viewTransition !== 'none' && direction !== 'none')
  52285. });
  52286. }
  52287. function getViewData(view) {
  52288. view = view || {};
  52289. return {
  52290. viewId: view.viewId,
  52291. historyId: view.historyId,
  52292. stateId: view.stateId,
  52293. stateName: view.stateName,
  52294. stateParams: view.stateParams
  52295. };
  52296. }
  52297. function navViewAttr(ele, value) {
  52298. if (arguments.length > 1) {
  52299. cachedAttr(ele, NAV_VIEW_ATTR, value);
  52300. } else {
  52301. return cachedAttr(ele, NAV_VIEW_ATTR);
  52302. }
  52303. }
  52304. function destroyViewEle(ele) {
  52305. // we found an element that should be removed
  52306. // destroy its scope, then remove the element
  52307. if (ele && ele.length) {
  52308. var viewScope = ele.scope();
  52309. if (viewScope) {
  52310. viewScope.$emit('$ionicView.unloaded', ele.data(DATA_VIEW));
  52311. viewScope.$destroy();
  52312. }
  52313. ele.remove();
  52314. }
  52315. }
  52316. function compareStatePrefixes(enteringStateName, exitingStateName) {
  52317. var enteringStateSuffixIndex = enteringStateName.lastIndexOf('.');
  52318. var exitingStateSuffixIndex = exitingStateName.lastIndexOf('.');
  52319. // if either of the prefixes are empty, just return false
  52320. if ( enteringStateSuffixIndex < 0 || exitingStateSuffixIndex < 0 ) {
  52321. return false;
  52322. }
  52323. var enteringPrefix = enteringStateName.substring(0, enteringStateSuffixIndex);
  52324. var exitingPrefix = exitingStateName.substring(0, exitingStateSuffixIndex);
  52325. return enteringPrefix === exitingPrefix;
  52326. }
  52327. function getScopeForElement(element, stateData) {
  52328. if ( !element ) {
  52329. return null;
  52330. }
  52331. // check if it's abstract
  52332. var attributeValue = angular.element(element).attr("abstract");
  52333. var stateValue = angular.element(element).attr("state");
  52334. if ( attributeValue !== "true" ) {
  52335. // it's not an abstract view, so make sure the element
  52336. // matches the state. Due to abstract view weirdness,
  52337. // sometimes it doesn't. If it doesn't, don't dispatch events
  52338. // so leave the scope undefined
  52339. if ( stateValue === stateData.stateName ) {
  52340. return angular.element(element).scope();
  52341. }
  52342. return null;
  52343. }
  52344. else {
  52345. // it is an abstract element, so look for element with the "state" attributeValue
  52346. // set to the name of the stateData state
  52347. var elements = aggregateNavViewChildren(element);
  52348. for ( var i = 0; i < elements.length; i++ ) {
  52349. var state = angular.element(elements[i]).attr("state");
  52350. if ( state === stateData.stateName ) {
  52351. stateData.abstractView = true;
  52352. return angular.element(elements[i]).scope();
  52353. }
  52354. }
  52355. // we didn't find a match, so return null
  52356. return null;
  52357. }
  52358. }
  52359. function aggregateNavViewChildren(element) {
  52360. var aggregate = [];
  52361. var navViews = angular.element(element).find("ion-nav-view");
  52362. for ( var i = 0; i < navViews.length; i++ ) {
  52363. var children = angular.element(navViews[i]).children();
  52364. var childrenAggregated = [];
  52365. for ( var j = 0; j < children.length; j++ ) {
  52366. childrenAggregated = childrenAggregated.concat(children[j]);
  52367. }
  52368. aggregate = aggregate.concat(childrenAggregated);
  52369. }
  52370. return aggregate;
  52371. }
  52372. }]);
  52373. /**
  52374. * ================== angular-ios9-uiwebview.patch.js v1.1.1 ==================
  52375. *
  52376. * This patch works around iOS9 UIWebView regression that causes infinite digest
  52377. * errors in Angular.
  52378. *
  52379. * The patch can be applied to Angular 1.2.0 – 1.4.5. Newer versions of Angular
  52380. * have the workaround baked in.
  52381. *
  52382. * To apply this patch load/bundle this file with your application and add a
  52383. * dependency on the "ngIOS9UIWebViewPatch" module to your main app module.
  52384. *
  52385. * For example:
  52386. *
  52387. * ```
  52388. * angular.module('myApp', ['ngRoute'])`
  52389. * ```
  52390. *
  52391. * becomes
  52392. *
  52393. * ```
  52394. * angular.module('myApp', ['ngRoute', 'ngIOS9UIWebViewPatch'])
  52395. * ```
  52396. *
  52397. *
  52398. * More info:
  52399. * - https://openradar.appspot.com/22186109
  52400. * - https://github.com/angular/angular.js/issues/12241
  52401. * - https://github.com/ionic-team/ionic/issues/4082
  52402. *
  52403. *
  52404. * @license AngularJS
  52405. * (c) 2010-2015 Google, Inc. http://angularjs.org
  52406. * License: MIT
  52407. */
  52408. angular.module('ngIOS9UIWebViewPatch', ['ng']).config(['$provide', function($provide) {
  52409. 'use strict';
  52410. $provide.decorator('$browser', ['$delegate', '$window', function($delegate, $window) {
  52411. if (isIOS9UIWebView($window.navigator.userAgent)) {
  52412. return applyIOS9Shim($delegate);
  52413. }
  52414. return $delegate;
  52415. function isIOS9UIWebView(userAgent) {
  52416. return /(iPhone|iPad|iPod).* OS 9_\d/.test(userAgent) && !/Version\/9\./.test(userAgent);
  52417. }
  52418. function applyIOS9Shim(browser) {
  52419. var pendingLocationUrl = null;
  52420. var originalUrlFn = browser.url;
  52421. browser.url = function() {
  52422. if (arguments.length) {
  52423. pendingLocationUrl = arguments[0];
  52424. return originalUrlFn.apply(browser, arguments);
  52425. }
  52426. return pendingLocationUrl || originalUrlFn.apply(browser, arguments);
  52427. };
  52428. window.addEventListener('popstate', clearPendingLocationUrl, false);
  52429. window.addEventListener('hashchange', clearPendingLocationUrl, false);
  52430. function clearPendingLocationUrl() {
  52431. pendingLocationUrl = null;
  52432. }
  52433. return browser;
  52434. }
  52435. }]);
  52436. }]);
  52437. /**
  52438. * @private
  52439. * Parts of Ionic requires that $scope data is attached to the element.
  52440. * We do not want to disable adding $scope data to the $element when
  52441. * $compileProvider.debugInfoEnabled(false) is used.
  52442. */
  52443. IonicModule.config(['$provide', function($provide) {
  52444. $provide.decorator('$compile', ['$delegate', function($compile) {
  52445. $compile.$$addScopeInfo = function $$addScopeInfo($element, scope, isolated, noTemplate) {
  52446. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  52447. $element.data(dataName, scope);
  52448. };
  52449. return $compile;
  52450. }]);
  52451. }]);
  52452. /**
  52453. * @private
  52454. */
  52455. IonicModule.config([
  52456. '$provide',
  52457. function($provide) {
  52458. function $LocationDecorator($location, $timeout) {
  52459. $location.__hash = $location.hash;
  52460. //Fix: when window.location.hash is set, the scrollable area
  52461. //found nearest to body's scrollTop is set to scroll to an element
  52462. //with that ID.
  52463. $location.hash = function(value) {
  52464. if (isDefined(value) && value.length > 0) {
  52465. $timeout(function() {
  52466. var scroll = document.querySelector('.scroll-content');
  52467. if (scroll) {
  52468. scroll.scrollTop = 0;
  52469. }
  52470. }, 0, false);
  52471. }
  52472. return $location.__hash(value);
  52473. };
  52474. return $location;
  52475. }
  52476. $provide.decorator('$location', ['$delegate', '$timeout', $LocationDecorator]);
  52477. }]);
  52478. IonicModule
  52479. .controller('$ionicHeaderBar', [
  52480. '$scope',
  52481. '$element',
  52482. '$attrs',
  52483. '$q',
  52484. '$ionicConfig',
  52485. '$ionicHistory',
  52486. function($scope, $element, $attrs, $q, $ionicConfig, $ionicHistory) {
  52487. var TITLE = 'title';
  52488. var BACK_TEXT = 'back-text';
  52489. var BACK_BUTTON = 'back-button';
  52490. var DEFAULT_TITLE = 'default-title';
  52491. var PREVIOUS_TITLE = 'previous-title';
  52492. var HIDE = 'hide';
  52493. var self = this;
  52494. var titleText = '';
  52495. var previousTitleText = '';
  52496. var titleLeft = 0;
  52497. var titleRight = 0;
  52498. var titleCss = '';
  52499. var isBackEnabled = false;
  52500. var isBackShown = true;
  52501. var isNavBackShown = true;
  52502. var isBackElementShown = false;
  52503. var titleTextWidth = 0;
  52504. self.beforeEnter = function(viewData) {
  52505. $scope.$broadcast('$ionicView.beforeEnter', viewData);
  52506. };
  52507. self.title = function(newTitleText) {
  52508. if (arguments.length && newTitleText !== titleText) {
  52509. getEle(TITLE).innerHTML = newTitleText;
  52510. titleText = newTitleText;
  52511. titleTextWidth = 0;
  52512. }
  52513. return titleText;
  52514. };
  52515. self.enableBack = function(shouldEnable, disableReset) {
  52516. // whether or not the back button show be visible, according
  52517. // to the navigation and history
  52518. if (arguments.length) {
  52519. isBackEnabled = shouldEnable;
  52520. if (!disableReset) self.updateBackButton();
  52521. }
  52522. return isBackEnabled;
  52523. };
  52524. self.showBack = function(shouldShow, disableReset) {
  52525. // different from enableBack() because this will always have the back
  52526. // visually hidden if false, even if the history says it should show
  52527. if (arguments.length) {
  52528. isBackShown = shouldShow;
  52529. if (!disableReset) self.updateBackButton();
  52530. }
  52531. return isBackShown;
  52532. };
  52533. self.showNavBack = function(shouldShow) {
  52534. // different from showBack() because this is for the entire nav bar's
  52535. // setting for all of it's child headers. For internal use.
  52536. isNavBackShown = shouldShow;
  52537. self.updateBackButton();
  52538. };
  52539. self.updateBackButton = function() {
  52540. var ele;
  52541. if ((isBackShown && isNavBackShown && isBackEnabled) !== isBackElementShown) {
  52542. isBackElementShown = isBackShown && isNavBackShown && isBackEnabled;
  52543. ele = getEle(BACK_BUTTON);
  52544. ele && ele.classList[ isBackElementShown ? 'remove' : 'add' ](HIDE);
  52545. }
  52546. if (isBackEnabled) {
  52547. ele = ele || getEle(BACK_BUTTON);
  52548. if (ele) {
  52549. if (self.backButtonIcon !== $ionicConfig.backButton.icon()) {
  52550. ele = getEle(BACK_BUTTON + ' .icon');
  52551. if (ele) {
  52552. self.backButtonIcon = $ionicConfig.backButton.icon();
  52553. ele.className = 'icon ' + self.backButtonIcon;
  52554. }
  52555. }
  52556. if (self.backButtonText !== $ionicConfig.backButton.text()) {
  52557. ele = getEle(BACK_BUTTON + ' .back-text');
  52558. if (ele) {
  52559. ele.textContent = self.backButtonText = $ionicConfig.backButton.text();
  52560. }
  52561. }
  52562. }
  52563. }
  52564. };
  52565. self.titleTextWidth = function() {
  52566. var element = getEle(TITLE);
  52567. if ( element ) {
  52568. // If the element has a nav-bar-title, use that instead
  52569. // to calculate the width of the title
  52570. var children = angular.element(element).children();
  52571. for ( var i = 0; i < children.length; i++ ) {
  52572. if ( angular.element(children[i]).hasClass('nav-bar-title') ) {
  52573. element = children[i];
  52574. break;
  52575. }
  52576. }
  52577. }
  52578. var bounds = ionic.DomUtil.getTextBounds(element);
  52579. titleTextWidth = Math.min(bounds && bounds.width || 30);
  52580. return titleTextWidth;
  52581. };
  52582. self.titleWidth = function() {
  52583. var titleWidth = self.titleTextWidth();
  52584. var offsetWidth = getEle(TITLE).offsetWidth;
  52585. if (offsetWidth < titleWidth) {
  52586. titleWidth = offsetWidth + (titleLeft - titleRight - 5);
  52587. }
  52588. return titleWidth;
  52589. };
  52590. self.titleTextX = function() {
  52591. return ($element[0].offsetWidth / 2) - (self.titleWidth() / 2);
  52592. };
  52593. self.titleLeftRight = function() {
  52594. return titleLeft - titleRight;
  52595. };
  52596. self.backButtonTextLeft = function() {
  52597. var offsetLeft = 0;
  52598. var ele = getEle(BACK_TEXT);
  52599. while (ele) {
  52600. offsetLeft += ele.offsetLeft;
  52601. ele = ele.parentElement;
  52602. }
  52603. return offsetLeft;
  52604. };
  52605. self.resetBackButton = function(viewData) {
  52606. if ($ionicConfig.backButton.previousTitleText()) {
  52607. var previousTitleEle = getEle(PREVIOUS_TITLE);
  52608. if (previousTitleEle) {
  52609. previousTitleEle.classList.remove(HIDE);
  52610. var view = (viewData && $ionicHistory.getViewById(viewData.viewId));
  52611. var newPreviousTitleText = $ionicHistory.backTitle(view);
  52612. if (newPreviousTitleText !== previousTitleText) {
  52613. previousTitleText = previousTitleEle.innerHTML = newPreviousTitleText;
  52614. }
  52615. }
  52616. var defaultTitleEle = getEle(DEFAULT_TITLE);
  52617. if (defaultTitleEle) {
  52618. defaultTitleEle.classList.remove(HIDE);
  52619. }
  52620. }
  52621. };
  52622. self.align = function(textAlign) {
  52623. var titleEle = getEle(TITLE);
  52624. textAlign = textAlign || $attrs.alignTitle || $ionicConfig.navBar.alignTitle();
  52625. var widths = self.calcWidths(textAlign, false);
  52626. if (isBackShown && previousTitleText && $ionicConfig.backButton.previousTitleText()) {
  52627. var previousTitleWidths = self.calcWidths(textAlign, true);
  52628. var availableTitleWidth = $element[0].offsetWidth - previousTitleWidths.titleLeft - previousTitleWidths.titleRight;
  52629. if (self.titleTextWidth() <= availableTitleWidth) {
  52630. widths = previousTitleWidths;
  52631. }
  52632. }
  52633. return self.updatePositions(titleEle, widths.titleLeft, widths.titleRight, widths.buttonsLeft, widths.buttonsRight, widths.css, widths.showPrevTitle);
  52634. };
  52635. self.calcWidths = function(textAlign, isPreviousTitle) {
  52636. var titleEle = getEle(TITLE);
  52637. var backBtnEle = getEle(BACK_BUTTON);
  52638. var x, y, z, b, c, d, childSize, bounds;
  52639. var childNodes = $element[0].childNodes;
  52640. var buttonsLeft = 0;
  52641. var buttonsRight = 0;
  52642. var isCountRightOfTitle;
  52643. var updateTitleLeft = 0;
  52644. var updateTitleRight = 0;
  52645. var updateCss = '';
  52646. var backButtonWidth = 0;
  52647. // Compute how wide the left children are
  52648. // Skip all titles (there may still be two titles, one leaving the dom)
  52649. // Once we encounter a titleEle, realize we are now counting the right-buttons, not left
  52650. for (x = 0; x < childNodes.length; x++) {
  52651. c = childNodes[x];
  52652. childSize = 0;
  52653. if (c.nodeType == 1) {
  52654. // element node
  52655. if (c === titleEle) {
  52656. isCountRightOfTitle = true;
  52657. continue;
  52658. }
  52659. if (c.classList.contains(HIDE)) {
  52660. continue;
  52661. }
  52662. if (isBackShown && c === backBtnEle) {
  52663. for (y = 0; y < c.childNodes.length; y++) {
  52664. b = c.childNodes[y];
  52665. if (b.nodeType == 1) {
  52666. if (b.classList.contains(BACK_TEXT)) {
  52667. for (z = 0; z < b.children.length; z++) {
  52668. d = b.children[z];
  52669. if (isPreviousTitle) {
  52670. if (d.classList.contains(DEFAULT_TITLE)) continue;
  52671. backButtonWidth += d.offsetWidth;
  52672. } else {
  52673. if (d.classList.contains(PREVIOUS_TITLE)) continue;
  52674. backButtonWidth += d.offsetWidth;
  52675. }
  52676. }
  52677. } else {
  52678. backButtonWidth += b.offsetWidth;
  52679. }
  52680. } else if (b.nodeType == 3 && b.nodeValue.trim()) {
  52681. bounds = ionic.DomUtil.getTextBounds(b);
  52682. backButtonWidth += bounds && bounds.width || 0;
  52683. }
  52684. }
  52685. childSize = backButtonWidth || c.offsetWidth;
  52686. } else {
  52687. // not the title, not the back button, not a hidden element
  52688. childSize = c.offsetWidth;
  52689. }
  52690. } else if (c.nodeType == 3 && c.nodeValue.trim()) {
  52691. // text node
  52692. bounds = ionic.DomUtil.getTextBounds(c);
  52693. childSize = bounds && bounds.width || 0;
  52694. }
  52695. if (isCountRightOfTitle) {
  52696. buttonsRight += childSize;
  52697. } else {
  52698. buttonsLeft += childSize;
  52699. }
  52700. }
  52701. // Size and align the header titleEle based on the sizes of the left and
  52702. // right children, and the desired alignment mode
  52703. if (textAlign == 'left') {
  52704. updateCss = 'title-left';
  52705. if (buttonsLeft) {
  52706. updateTitleLeft = buttonsLeft + 15;
  52707. }
  52708. if (buttonsRight) {
  52709. updateTitleRight = buttonsRight + 15;
  52710. }
  52711. } else if (textAlign == 'right') {
  52712. updateCss = 'title-right';
  52713. if (buttonsLeft) {
  52714. updateTitleLeft = buttonsLeft + 15;
  52715. }
  52716. if (buttonsRight) {
  52717. updateTitleRight = buttonsRight + 15;
  52718. }
  52719. } else {
  52720. // center the default
  52721. var margin = Math.max(buttonsLeft, buttonsRight) + 10;
  52722. if (margin > 10) {
  52723. updateTitleLeft = updateTitleRight = margin;
  52724. }
  52725. }
  52726. return {
  52727. backButtonWidth: backButtonWidth,
  52728. buttonsLeft: buttonsLeft,
  52729. buttonsRight: buttonsRight,
  52730. titleLeft: updateTitleLeft,
  52731. titleRight: updateTitleRight,
  52732. showPrevTitle: isPreviousTitle,
  52733. css: updateCss
  52734. };
  52735. };
  52736. self.updatePositions = function(titleEle, updateTitleLeft, updateTitleRight, buttonsLeft, buttonsRight, updateCss, showPreviousTitle) {
  52737. var deferred = $q.defer();
  52738. // only make DOM updates when there are actual changes
  52739. if (titleEle) {
  52740. if (updateTitleLeft !== titleLeft) {
  52741. titleEle.style.left = updateTitleLeft ? updateTitleLeft + 'px' : '';
  52742. titleLeft = updateTitleLeft;
  52743. }
  52744. if (updateTitleRight !== titleRight) {
  52745. titleEle.style.right = updateTitleRight ? updateTitleRight + 'px' : '';
  52746. titleRight = updateTitleRight;
  52747. }
  52748. if (updateCss !== titleCss) {
  52749. updateCss && titleEle.classList.add(updateCss);
  52750. titleCss && titleEle.classList.remove(titleCss);
  52751. titleCss = updateCss;
  52752. }
  52753. }
  52754. if ($ionicConfig.backButton.previousTitleText()) {
  52755. var prevTitle = getEle(PREVIOUS_TITLE);
  52756. var defaultTitle = getEle(DEFAULT_TITLE);
  52757. prevTitle && prevTitle.classList[ showPreviousTitle ? 'remove' : 'add'](HIDE);
  52758. defaultTitle && defaultTitle.classList[ showPreviousTitle ? 'add' : 'remove'](HIDE);
  52759. }
  52760. ionic.requestAnimationFrame(function() {
  52761. if (titleEle && titleEle.offsetWidth + 10 < titleEle.scrollWidth) {
  52762. var minRight = buttonsRight + 5;
  52763. var testRight = $element[0].offsetWidth - titleLeft - self.titleTextWidth() - 20;
  52764. updateTitleRight = testRight < minRight ? minRight : testRight;
  52765. if (updateTitleRight !== titleRight) {
  52766. titleEle.style.right = updateTitleRight + 'px';
  52767. titleRight = updateTitleRight;
  52768. }
  52769. }
  52770. deferred.resolve();
  52771. });
  52772. return deferred.promise;
  52773. };
  52774. self.setCss = function(elementClassname, css) {
  52775. ionic.DomUtil.cachedStyles(getEle(elementClassname), css);
  52776. };
  52777. var eleCache = {};
  52778. function getEle(className) {
  52779. if (!eleCache[className]) {
  52780. eleCache[className] = $element[0].querySelector('.' + className);
  52781. }
  52782. return eleCache[className];
  52783. }
  52784. $scope.$on('$destroy', function() {
  52785. for (var n in eleCache) eleCache[n] = null;
  52786. });
  52787. }]);
  52788. IonicModule
  52789. .controller('$ionInfiniteScroll', [
  52790. '$scope',
  52791. '$attrs',
  52792. '$element',
  52793. '$timeout',
  52794. function($scope, $attrs, $element, $timeout) {
  52795. var self = this;
  52796. self.isLoading = false;
  52797. $scope.icon = function() {
  52798. return isDefined($attrs.icon) ? $attrs.icon : 'ion-load-d';
  52799. };
  52800. $scope.spinner = function() {
  52801. return isDefined($attrs.spinner) ? $attrs.spinner : '';
  52802. };
  52803. $scope.$on('scroll.infiniteScrollComplete', function() {
  52804. finishInfiniteScroll();
  52805. });
  52806. $scope.$on('$destroy', function() {
  52807. if (self.scrollCtrl && self.scrollCtrl.$element) self.scrollCtrl.$element.off('scroll', self.checkBounds);
  52808. if (self.scrollEl && self.scrollEl.removeEventListener) {
  52809. self.scrollEl.removeEventListener('scroll', self.checkBounds);
  52810. }
  52811. });
  52812. // debounce checking infinite scroll events
  52813. self.checkBounds = ionic.Utils.throttle(checkInfiniteBounds, 300);
  52814. function onInfinite() {
  52815. ionic.requestAnimationFrame(function() {
  52816. $element[0].classList.add('active');
  52817. });
  52818. self.isLoading = true;
  52819. $scope.$parent && $scope.$parent.$apply($attrs.onInfinite || '');
  52820. }
  52821. function finishInfiniteScroll() {
  52822. ionic.requestAnimationFrame(function() {
  52823. $element[0].classList.remove('active');
  52824. });
  52825. $timeout(function() {
  52826. if (self.jsScrolling) self.scrollView.resize();
  52827. // only check bounds again immediately if the page isn't cached (scroll el has height)
  52828. if ((self.jsScrolling && self.scrollView.__container && self.scrollView.__container.offsetHeight > 0) ||
  52829. !self.jsScrolling) {
  52830. self.checkBounds();
  52831. }
  52832. }, 30, false);
  52833. self.isLoading = false;
  52834. }
  52835. // check if we've scrolled far enough to trigger an infinite scroll
  52836. function checkInfiniteBounds() {
  52837. if (self.isLoading) return;
  52838. var maxScroll = {};
  52839. if (self.jsScrolling) {
  52840. maxScroll = self.getJSMaxScroll();
  52841. var scrollValues = self.scrollView.getValues();
  52842. if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||
  52843. (maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {
  52844. onInfinite();
  52845. }
  52846. } else {
  52847. maxScroll = self.getNativeMaxScroll();
  52848. if ((
  52849. maxScroll.left !== -1 &&
  52850. self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth
  52851. ) || (
  52852. maxScroll.top !== -1 &&
  52853. self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight
  52854. )) {
  52855. onInfinite();
  52856. }
  52857. }
  52858. }
  52859. // determine the threshold at which we should fire an infinite scroll
  52860. // note: this gets processed every scroll event, can it be cached?
  52861. self.getJSMaxScroll = function() {
  52862. var maxValues = self.scrollView.getScrollMax();
  52863. return {
  52864. left: self.scrollView.options.scrollingX ?
  52865. calculateMaxValue(maxValues.left) :
  52866. -1,
  52867. top: self.scrollView.options.scrollingY ?
  52868. calculateMaxValue(maxValues.top) :
  52869. -1
  52870. };
  52871. };
  52872. self.getNativeMaxScroll = function() {
  52873. var maxValues = {
  52874. left: self.scrollEl.scrollWidth,
  52875. top: self.scrollEl.scrollHeight
  52876. };
  52877. var computedStyle = window.getComputedStyle(self.scrollEl) || {};
  52878. return {
  52879. left: maxValues.left &&
  52880. (computedStyle.overflowX === 'scroll' ||
  52881. computedStyle.overflowX === 'auto' ||
  52882. self.scrollEl.style['overflow-x'] === 'scroll') ?
  52883. calculateMaxValue(maxValues.left) : -1,
  52884. top: maxValues.top &&
  52885. (computedStyle.overflowY === 'scroll' ||
  52886. computedStyle.overflowY === 'auto' ||
  52887. self.scrollEl.style['overflow-y'] === 'scroll' ) ?
  52888. calculateMaxValue(maxValues.top) : -1
  52889. };
  52890. };
  52891. // determine pixel refresh distance based on % or value
  52892. function calculateMaxValue(maximum) {
  52893. var distance = ($attrs.distance || '2.5%').trim();
  52894. var isPercent = distance.indexOf('%') !== -1;
  52895. return isPercent ?
  52896. maximum * (1 - parseFloat(distance) / 100) :
  52897. maximum - parseFloat(distance);
  52898. }
  52899. //for testing
  52900. self.__finishInfiniteScroll = finishInfiniteScroll;
  52901. }]);
  52902. /**
  52903. * @ngdoc service
  52904. * @name $ionicListDelegate
  52905. * @module ionic
  52906. *
  52907. * @description
  52908. * Delegate for controlling the {@link ionic.directive:ionList} directive.
  52909. *
  52910. * Methods called directly on the $ionicListDelegate service will control all lists.
  52911. * Use the {@link ionic.service:$ionicListDelegate#$getByHandle $getByHandle}
  52912. * method to control specific ionList instances.
  52913. *
  52914. * @usage
  52915. * ```html
  52916. * {% raw %}
  52917. * <ion-content ng-controller="MyCtrl">
  52918. * <button class="button" ng-click="showDeleteButtons()"></button>
  52919. * <ion-list>
  52920. * <ion-item ng-repeat="i in items">
  52921. * Hello, {{i}}!
  52922. * <ion-delete-button class="ion-minus-circled"></ion-delete-button>
  52923. * </ion-item>
  52924. * </ion-list>
  52925. * </ion-content>
  52926. * {% endraw %}
  52927. * ```
  52928. * ```js
  52929. * function MyCtrl($scope, $ionicListDelegate) {
  52930. * $scope.showDeleteButtons = function() {
  52931. * $ionicListDelegate.showDelete(true);
  52932. * };
  52933. * }
  52934. * ```
  52935. */
  52936. IonicModule.service('$ionicListDelegate', ionic.DelegateService([
  52937. /**
  52938. * @ngdoc method
  52939. * @name $ionicListDelegate#showReorder
  52940. * @param {boolean=} showReorder Set whether or not this list is showing its reorder buttons.
  52941. * @returns {boolean} Whether the reorder buttons are shown.
  52942. */
  52943. 'showReorder',
  52944. /**
  52945. * @ngdoc method
  52946. * @name $ionicListDelegate#showDelete
  52947. * @param {boolean=} showDelete Set whether or not this list is showing its delete buttons.
  52948. * @returns {boolean} Whether the delete buttons are shown.
  52949. */
  52950. 'showDelete',
  52951. /**
  52952. * @ngdoc method
  52953. * @name $ionicListDelegate#canSwipeItems
  52954. * @param {boolean=} canSwipeItems Set whether or not this list is able to swipe to show
  52955. * option buttons.
  52956. * @returns {boolean} Whether the list is able to swipe to show option buttons.
  52957. */
  52958. 'canSwipeItems',
  52959. /**
  52960. * @ngdoc method
  52961. * @name $ionicListDelegate#closeOptionButtons
  52962. * @description Closes any option buttons on the list that are swiped open.
  52963. */
  52964. 'closeOptionButtons'
  52965. /**
  52966. * @ngdoc method
  52967. * @name $ionicListDelegate#$getByHandle
  52968. * @param {string} handle
  52969. * @returns `delegateInstance` A delegate instance that controls only the
  52970. * {@link ionic.directive:ionList} directives with `delegate-handle` matching
  52971. * the given handle.
  52972. *
  52973. * Example: `$ionicListDelegate.$getByHandle('my-handle').showReorder(true);`
  52974. */
  52975. ]))
  52976. .controller('$ionicList', [
  52977. '$scope',
  52978. '$attrs',
  52979. '$ionicListDelegate',
  52980. '$ionicHistory',
  52981. function($scope, $attrs, $ionicListDelegate, $ionicHistory) {
  52982. var self = this;
  52983. var isSwipeable = true;
  52984. var isReorderShown = false;
  52985. var isDeleteShown = false;
  52986. var deregisterInstance = $ionicListDelegate._registerInstance(
  52987. self, $attrs.delegateHandle, function() {
  52988. return $ionicHistory.isActiveScope($scope);
  52989. }
  52990. );
  52991. $scope.$on('$destroy', deregisterInstance);
  52992. self.showReorder = function(show) {
  52993. if (arguments.length) {
  52994. isReorderShown = !!show;
  52995. }
  52996. return isReorderShown;
  52997. };
  52998. self.showDelete = function(show) {
  52999. if (arguments.length) {
  53000. isDeleteShown = !!show;
  53001. }
  53002. return isDeleteShown;
  53003. };
  53004. self.canSwipeItems = function(can) {
  53005. if (arguments.length) {
  53006. isSwipeable = !!can;
  53007. }
  53008. return isSwipeable;
  53009. };
  53010. self.closeOptionButtons = function() {
  53011. self.listView && self.listView.clearDragEffects();
  53012. };
  53013. }]);
  53014. IonicModule
  53015. .controller('$ionicNavBar', [
  53016. '$scope',
  53017. '$element',
  53018. '$attrs',
  53019. '$compile',
  53020. '$timeout',
  53021. '$ionicNavBarDelegate',
  53022. '$ionicConfig',
  53023. '$ionicHistory',
  53024. function($scope, $element, $attrs, $compile, $timeout, $ionicNavBarDelegate, $ionicConfig, $ionicHistory) {
  53025. var CSS_HIDE = 'hide';
  53026. var DATA_NAV_BAR_CTRL = '$ionNavBarController';
  53027. var PRIMARY_BUTTONS = 'primaryButtons';
  53028. var SECONDARY_BUTTONS = 'secondaryButtons';
  53029. var BACK_BUTTON = 'backButton';
  53030. var ITEM_TYPES = 'primaryButtons secondaryButtons leftButtons rightButtons title'.split(' ');
  53031. var self = this;
  53032. var headerBars = [];
  53033. var navElementHtml = {};
  53034. var isVisible = true;
  53035. var queuedTransitionStart, queuedTransitionEnd, latestTransitionId;
  53036. $element.parent().data(DATA_NAV_BAR_CTRL, self);
  53037. var delegateHandle = $attrs.delegateHandle || 'navBar' + ionic.Utils.nextUid();
  53038. var deregisterInstance = $ionicNavBarDelegate._registerInstance(self, delegateHandle);
  53039. self.init = function() {
  53040. $element.addClass('nav-bar-container');
  53041. ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', $ionicConfig.views.transition());
  53042. // create two nav bar blocks which will trade out which one is shown
  53043. self.createHeaderBar(false);
  53044. self.createHeaderBar(true);
  53045. $scope.$emit('ionNavBar.init', delegateHandle);
  53046. };
  53047. self.createHeaderBar = function(isActive) {
  53048. var containerEle = jqLite('<div class="nav-bar-block">');
  53049. ionic.DomUtil.cachedAttr(containerEle, 'nav-bar', isActive ? 'active' : 'cached');
  53050. var alignTitle = $attrs.alignTitle || $ionicConfig.navBar.alignTitle();
  53051. var headerBarEle = jqLite('<ion-header-bar>').addClass($attrs['class']).attr('align-title', alignTitle);
  53052. if (isDefined($attrs.noTapScroll)) headerBarEle.attr('no-tap-scroll', $attrs.noTapScroll);
  53053. var titleEle = jqLite('<div class="title title-' + alignTitle + '">');
  53054. var navEle = {};
  53055. var lastViewItemEle = {};
  53056. var leftButtonsEle, rightButtonsEle;
  53057. navEle[BACK_BUTTON] = createNavElement(BACK_BUTTON);
  53058. navEle[BACK_BUTTON] && headerBarEle.append(navEle[BACK_BUTTON]);
  53059. // append title in the header, this is the rock to where buttons append
  53060. headerBarEle.append(titleEle);
  53061. forEach(ITEM_TYPES, function(itemType) {
  53062. // create default button elements
  53063. navEle[itemType] = createNavElement(itemType);
  53064. // append and position buttons
  53065. positionItem(navEle[itemType], itemType);
  53066. });
  53067. // add header-item to the root children
  53068. for (var x = 0; x < headerBarEle[0].children.length; x++) {
  53069. headerBarEle[0].children[x].classList.add('header-item');
  53070. }
  53071. // compile header and append to the DOM
  53072. containerEle.append(headerBarEle);
  53073. $element.append($compile(containerEle)($scope.$new()));
  53074. var headerBarCtrl = headerBarEle.data('$ionHeaderBarController');
  53075. headerBarCtrl.backButtonIcon = $ionicConfig.backButton.icon();
  53076. headerBarCtrl.backButtonText = $ionicConfig.backButton.text();
  53077. var headerBarInstance = {
  53078. isActive: isActive,
  53079. title: function(newTitleText) {
  53080. headerBarCtrl.title(newTitleText);
  53081. },
  53082. setItem: function(navBarItemEle, itemType) {
  53083. // first make sure any exiting nav bar item has been removed
  53084. headerBarInstance.removeItem(itemType);
  53085. if (navBarItemEle) {
  53086. if (itemType === 'title') {
  53087. // clear out the text based title
  53088. headerBarInstance.title("");
  53089. }
  53090. // there's a custom nav bar item
  53091. positionItem(navBarItemEle, itemType);
  53092. if (navEle[itemType]) {
  53093. // make sure the default on this itemType is hidden
  53094. navEle[itemType].addClass(CSS_HIDE);
  53095. }
  53096. lastViewItemEle[itemType] = navBarItemEle;
  53097. } else if (navEle[itemType]) {
  53098. // there's a default button for this side and no view button
  53099. navEle[itemType].removeClass(CSS_HIDE);
  53100. }
  53101. },
  53102. removeItem: function(itemType) {
  53103. if (lastViewItemEle[itemType]) {
  53104. lastViewItemEle[itemType].scope().$destroy();
  53105. lastViewItemEle[itemType].remove();
  53106. lastViewItemEle[itemType] = null;
  53107. }
  53108. },
  53109. containerEle: function() {
  53110. return containerEle;
  53111. },
  53112. headerBarEle: function() {
  53113. return headerBarEle;
  53114. },
  53115. afterLeave: function() {
  53116. forEach(ITEM_TYPES, function(itemType) {
  53117. headerBarInstance.removeItem(itemType);
  53118. });
  53119. headerBarCtrl.resetBackButton();
  53120. },
  53121. controller: function() {
  53122. return headerBarCtrl;
  53123. },
  53124. destroy: function() {
  53125. forEach(ITEM_TYPES, function(itemType) {
  53126. headerBarInstance.removeItem(itemType);
  53127. });
  53128. containerEle.scope().$destroy();
  53129. for (var n in navEle) {
  53130. if (navEle[n]) {
  53131. navEle[n].removeData();
  53132. navEle[n] = null;
  53133. }
  53134. }
  53135. leftButtonsEle && leftButtonsEle.removeData();
  53136. rightButtonsEle && rightButtonsEle.removeData();
  53137. titleEle.removeData();
  53138. headerBarEle.removeData();
  53139. containerEle.remove();
  53140. containerEle = headerBarEle = titleEle = leftButtonsEle = rightButtonsEle = null;
  53141. }
  53142. };
  53143. function positionItem(ele, itemType) {
  53144. if (!ele) return;
  53145. if (itemType === 'title') {
  53146. // title element
  53147. titleEle.append(ele);
  53148. } else if (itemType == 'rightButtons' ||
  53149. (itemType == SECONDARY_BUTTONS && $ionicConfig.navBar.positionSecondaryButtons() != 'left') ||
  53150. (itemType == PRIMARY_BUTTONS && $ionicConfig.navBar.positionPrimaryButtons() == 'right')) {
  53151. // right side
  53152. if (!rightButtonsEle) {
  53153. rightButtonsEle = jqLite('<div class="buttons buttons-right">');
  53154. headerBarEle.append(rightButtonsEle);
  53155. }
  53156. if (itemType == SECONDARY_BUTTONS) {
  53157. rightButtonsEle.append(ele);
  53158. } else {
  53159. rightButtonsEle.prepend(ele);
  53160. }
  53161. } else {
  53162. // left side
  53163. if (!leftButtonsEle) {
  53164. leftButtonsEle = jqLite('<div class="buttons buttons-left">');
  53165. if (navEle[BACK_BUTTON]) {
  53166. navEle[BACK_BUTTON].after(leftButtonsEle);
  53167. } else {
  53168. headerBarEle.prepend(leftButtonsEle);
  53169. }
  53170. }
  53171. if (itemType == SECONDARY_BUTTONS) {
  53172. leftButtonsEle.append(ele);
  53173. } else {
  53174. leftButtonsEle.prepend(ele);
  53175. }
  53176. }
  53177. }
  53178. headerBars.push(headerBarInstance);
  53179. return headerBarInstance;
  53180. };
  53181. self.navElement = function(type, html) {
  53182. if (isDefined(html)) {
  53183. navElementHtml[type] = html;
  53184. }
  53185. return navElementHtml[type];
  53186. };
  53187. self.update = function(viewData) {
  53188. var showNavBar = !viewData.hasHeaderBar && viewData.showNavBar;
  53189. viewData.transition = $ionicConfig.views.transition();
  53190. if (!showNavBar) {
  53191. viewData.direction = 'none';
  53192. }
  53193. self.enable(showNavBar);
  53194. var enteringHeaderBar = self.isInitialized ? getOffScreenHeaderBar() : getOnScreenHeaderBar();
  53195. var leavingHeaderBar = self.isInitialized ? getOnScreenHeaderBar() : null;
  53196. var enteringHeaderCtrl = enteringHeaderBar.controller();
  53197. // update if the entering header should show the back button or not
  53198. enteringHeaderCtrl.enableBack(viewData.enableBack, true);
  53199. enteringHeaderCtrl.showBack(viewData.showBack, true);
  53200. enteringHeaderCtrl.updateBackButton();
  53201. // update the entering header bar's title
  53202. self.title(viewData.title, enteringHeaderBar);
  53203. self.showBar(showNavBar);
  53204. // update the nav bar items, depending if the view has their own or not
  53205. if (viewData.navBarItems) {
  53206. forEach(ITEM_TYPES, function(itemType) {
  53207. enteringHeaderBar.setItem(viewData.navBarItems[itemType], itemType);
  53208. });
  53209. }
  53210. // begin transition of entering and leaving header bars
  53211. self.transition(enteringHeaderBar, leavingHeaderBar, viewData);
  53212. self.isInitialized = true;
  53213. navSwipeAttr('');
  53214. };
  53215. self.transition = function(enteringHeaderBar, leavingHeaderBar, viewData) {
  53216. var enteringHeaderBarCtrl = enteringHeaderBar.controller();
  53217. var transitionFn = $ionicConfig.transitions.navBar[viewData.navBarTransition] || $ionicConfig.transitions.navBar.none;
  53218. var transitionId = viewData.transitionId;
  53219. enteringHeaderBarCtrl.beforeEnter(viewData);
  53220. var navBarTransition = transitionFn(enteringHeaderBar, leavingHeaderBar, viewData.direction, viewData.shouldAnimate && self.isInitialized);
  53221. ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', viewData.navBarTransition);
  53222. ionic.DomUtil.cachedAttr($element, 'nav-bar-direction', viewData.direction);
  53223. if (navBarTransition.shouldAnimate && viewData.renderEnd) {
  53224. navBarAttr(enteringHeaderBar, 'stage');
  53225. } else {
  53226. navBarAttr(enteringHeaderBar, 'entering');
  53227. navBarAttr(leavingHeaderBar, 'leaving');
  53228. }
  53229. enteringHeaderBarCtrl.resetBackButton(viewData);
  53230. navBarTransition.run(0);
  53231. self.activeTransition = {
  53232. run: function(step) {
  53233. navBarTransition.shouldAnimate = false;
  53234. navBarTransition.direction = 'back';
  53235. navBarTransition.run(step);
  53236. },
  53237. cancel: function(shouldAnimate, speed, cancelData) {
  53238. navSwipeAttr(speed);
  53239. navBarAttr(leavingHeaderBar, 'active');
  53240. navBarAttr(enteringHeaderBar, 'cached');
  53241. navBarTransition.shouldAnimate = shouldAnimate;
  53242. navBarTransition.run(0);
  53243. self.activeTransition = navBarTransition = null;
  53244. var runApply;
  53245. if (cancelData.showBar !== self.showBar()) {
  53246. self.showBar(cancelData.showBar);
  53247. }
  53248. if (cancelData.showBackButton !== self.showBackButton()) {
  53249. self.showBackButton(cancelData.showBackButton);
  53250. }
  53251. if (runApply) {
  53252. $scope.$apply();
  53253. }
  53254. },
  53255. complete: function(shouldAnimate, speed) {
  53256. navSwipeAttr(speed);
  53257. navBarTransition.shouldAnimate = shouldAnimate;
  53258. navBarTransition.run(1);
  53259. queuedTransitionEnd = transitionEnd;
  53260. }
  53261. };
  53262. $timeout(enteringHeaderBarCtrl.align, 16);
  53263. queuedTransitionStart = function() {
  53264. if (latestTransitionId !== transitionId) return;
  53265. navBarAttr(enteringHeaderBar, 'entering');
  53266. navBarAttr(leavingHeaderBar, 'leaving');
  53267. navBarTransition.run(1);
  53268. queuedTransitionEnd = function() {
  53269. if (latestTransitionId == transitionId || !navBarTransition.shouldAnimate) {
  53270. transitionEnd();
  53271. }
  53272. };
  53273. queuedTransitionStart = null;
  53274. };
  53275. function transitionEnd() {
  53276. for (var x = 0; x < headerBars.length; x++) {
  53277. headerBars[x].isActive = false;
  53278. }
  53279. enteringHeaderBar.isActive = true;
  53280. navBarAttr(enteringHeaderBar, 'active');
  53281. navBarAttr(leavingHeaderBar, 'cached');
  53282. self.activeTransition = navBarTransition = queuedTransitionEnd = null;
  53283. }
  53284. queuedTransitionStart();
  53285. };
  53286. self.triggerTransitionStart = function(triggerTransitionId) {
  53287. latestTransitionId = triggerTransitionId;
  53288. queuedTransitionStart && queuedTransitionStart();
  53289. };
  53290. self.triggerTransitionEnd = function() {
  53291. queuedTransitionEnd && queuedTransitionEnd();
  53292. };
  53293. self.showBar = function(shouldShow) {
  53294. if (arguments.length) {
  53295. self.visibleBar(shouldShow);
  53296. $scope.$parent.$hasHeader = !!shouldShow;
  53297. }
  53298. return !!$scope.$parent.$hasHeader;
  53299. };
  53300. self.visibleBar = function(shouldShow) {
  53301. if (shouldShow && !isVisible) {
  53302. $element.removeClass(CSS_HIDE);
  53303. self.align();
  53304. } else if (!shouldShow && isVisible) {
  53305. $element.addClass(CSS_HIDE);
  53306. }
  53307. isVisible = shouldShow;
  53308. };
  53309. self.enable = function(val) {
  53310. // set primary to show first
  53311. self.visibleBar(val);
  53312. // set non primary to hide second
  53313. for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {
  53314. if ($ionicNavBarDelegate._instances[x] !== self) $ionicNavBarDelegate._instances[x].visibleBar(false);
  53315. }
  53316. };
  53317. /**
  53318. * @ngdoc method
  53319. * @name $ionicNavBar#showBackButton
  53320. * @description Show/hide the nav bar back button when there is a
  53321. * back view. If the back button is not possible, for example, the
  53322. * first view in the stack, then this will not force the back button
  53323. * to show.
  53324. */
  53325. self.showBackButton = function(shouldShow) {
  53326. if (arguments.length) {
  53327. for (var x = 0; x < headerBars.length; x++) {
  53328. headerBars[x].controller().showNavBack(!!shouldShow);
  53329. }
  53330. $scope.$isBackButtonShown = !!shouldShow;
  53331. }
  53332. return $scope.$isBackButtonShown;
  53333. };
  53334. /**
  53335. * @ngdoc method
  53336. * @name $ionicNavBar#showActiveBackButton
  53337. * @description Show/hide only the active header bar's back button.
  53338. */
  53339. self.showActiveBackButton = function(shouldShow) {
  53340. var headerBar = getOnScreenHeaderBar();
  53341. if (headerBar) {
  53342. if (arguments.length) {
  53343. return headerBar.controller().showBack(shouldShow);
  53344. }
  53345. return headerBar.controller().showBack();
  53346. }
  53347. };
  53348. self.title = function(newTitleText, headerBar) {
  53349. if (isDefined(newTitleText)) {
  53350. newTitleText = newTitleText || '';
  53351. headerBar = headerBar || getOnScreenHeaderBar();
  53352. headerBar && headerBar.title(newTitleText);
  53353. $scope.$title = newTitleText;
  53354. $ionicHistory.currentTitle(newTitleText);
  53355. }
  53356. return $scope.$title;
  53357. };
  53358. self.align = function(val, headerBar) {
  53359. headerBar = headerBar || getOnScreenHeaderBar();
  53360. headerBar && headerBar.controller().align(val);
  53361. };
  53362. self.hasTabsTop = function(isTabsTop) {
  53363. $element[isTabsTop ? 'addClass' : 'removeClass']('nav-bar-tabs-top');
  53364. };
  53365. self.hasBarSubheader = function(isBarSubheader) {
  53366. $element[isBarSubheader ? 'addClass' : 'removeClass']('nav-bar-has-subheader');
  53367. };
  53368. // DEPRECATED, as of v1.0.0-beta14 -------
  53369. self.changeTitle = function(val) {
  53370. deprecatedWarning('changeTitle(val)', 'title(val)');
  53371. self.title(val);
  53372. };
  53373. self.setTitle = function(val) {
  53374. deprecatedWarning('setTitle(val)', 'title(val)');
  53375. self.title(val);
  53376. };
  53377. self.getTitle = function() {
  53378. deprecatedWarning('getTitle()', 'title()');
  53379. return self.title();
  53380. };
  53381. self.back = function() {
  53382. deprecatedWarning('back()', '$ionicHistory.goBack()');
  53383. $ionicHistory.goBack();
  53384. };
  53385. self.getPreviousTitle = function() {
  53386. deprecatedWarning('getPreviousTitle()', '$ionicHistory.backTitle()');
  53387. $ionicHistory.goBack();
  53388. };
  53389. function deprecatedWarning(oldMethod, newMethod) {
  53390. var warn = console.warn || console.log;
  53391. warn && warn.call(console, 'navBarController.' + oldMethod + ' is deprecated, please use ' + newMethod + ' instead');
  53392. }
  53393. // END DEPRECATED -------
  53394. function createNavElement(type) {
  53395. if (navElementHtml[type]) {
  53396. return jqLite(navElementHtml[type]);
  53397. }
  53398. }
  53399. function getOnScreenHeaderBar() {
  53400. for (var x = 0; x < headerBars.length; x++) {
  53401. if (headerBars[x].isActive) return headerBars[x];
  53402. }
  53403. }
  53404. function getOffScreenHeaderBar() {
  53405. for (var x = 0; x < headerBars.length; x++) {
  53406. if (!headerBars[x].isActive) return headerBars[x];
  53407. }
  53408. }
  53409. function navBarAttr(ctrl, val) {
  53410. ctrl && ionic.DomUtil.cachedAttr(ctrl.containerEle(), 'nav-bar', val);
  53411. }
  53412. function navSwipeAttr(val) {
  53413. ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);
  53414. }
  53415. $scope.$on('$destroy', function() {
  53416. $scope.$parent.$hasHeader = false;
  53417. $element.parent().removeData(DATA_NAV_BAR_CTRL);
  53418. for (var x = 0; x < headerBars.length; x++) {
  53419. headerBars[x].destroy();
  53420. }
  53421. $element.remove();
  53422. $element = headerBars = null;
  53423. deregisterInstance();
  53424. });
  53425. }]);
  53426. IonicModule
  53427. .controller('$ionicNavView', [
  53428. '$scope',
  53429. '$element',
  53430. '$attrs',
  53431. '$compile',
  53432. '$controller',
  53433. '$ionicNavBarDelegate',
  53434. '$ionicNavViewDelegate',
  53435. '$ionicHistory',
  53436. '$ionicViewSwitcher',
  53437. '$ionicConfig',
  53438. '$ionicScrollDelegate',
  53439. '$ionicSideMenuDelegate',
  53440. function($scope, $element, $attrs, $compile, $controller, $ionicNavBarDelegate, $ionicNavViewDelegate, $ionicHistory, $ionicViewSwitcher, $ionicConfig, $ionicScrollDelegate, $ionicSideMenuDelegate) {
  53441. var DATA_ELE_IDENTIFIER = '$eleId';
  53442. var DATA_DESTROY_ELE = '$destroyEle';
  53443. var DATA_NO_CACHE = '$noCache';
  53444. var VIEW_STATUS_ACTIVE = 'active';
  53445. var VIEW_STATUS_CACHED = 'cached';
  53446. var self = this;
  53447. var direction;
  53448. var isPrimary = false;
  53449. var navBarDelegate;
  53450. var activeEleId;
  53451. var navViewAttr = $ionicViewSwitcher.navViewAttr;
  53452. var disableRenderStartViewId, disableAnimation;
  53453. self.scope = $scope;
  53454. self.element = $element;
  53455. self.init = function() {
  53456. var navViewName = $attrs.name || '';
  53457. // Find the details of the parent view directive (if any) and use it
  53458. // to derive our own qualified view name, then hang our own details
  53459. // off the DOM so child directives can find it.
  53460. var parent = $element.parent().inheritedData('$uiView');
  53461. var parentViewName = ((parent && parent.state) ? parent.state.name : '');
  53462. if (navViewName.indexOf('@') < 0) navViewName = navViewName + '@' + parentViewName;
  53463. var viewData = { name: navViewName, state: null };
  53464. $element.data('$uiView', viewData);
  53465. var deregisterInstance = $ionicNavViewDelegate._registerInstance(self, $attrs.delegateHandle);
  53466. $scope.$on('$destroy', function() {
  53467. deregisterInstance();
  53468. // ensure no scrolls have been left frozen
  53469. if (self.isSwipeFreeze) {
  53470. $ionicScrollDelegate.freezeAllScrolls(false);
  53471. }
  53472. });
  53473. $scope.$on('$ionicHistory.deselect', self.cacheCleanup);
  53474. $scope.$on('$ionicTabs.top', onTabsTop);
  53475. $scope.$on('$ionicSubheader', onBarSubheader);
  53476. $scope.$on('$ionicTabs.beforeLeave', onTabsLeave);
  53477. $scope.$on('$ionicTabs.afterLeave', onTabsLeave);
  53478. $scope.$on('$ionicTabs.leave', onTabsLeave);
  53479. ionic.Platform.ready(function() {
  53480. if ( ionic.Platform.isWebView() && ionic.Platform.isIOS() ) {
  53481. self.initSwipeBack();
  53482. }
  53483. });
  53484. return viewData;
  53485. };
  53486. self.register = function(viewLocals) {
  53487. var leavingView = extend({}, $ionicHistory.currentView());
  53488. // register that a view is coming in and get info on how it should transition
  53489. var registerData = $ionicHistory.register($scope, viewLocals);
  53490. // update which direction
  53491. self.update(registerData);
  53492. // begin rendering and transitioning
  53493. var enteringView = $ionicHistory.getViewById(registerData.viewId) || {};
  53494. var renderStart = (disableRenderStartViewId !== registerData.viewId);
  53495. self.render(registerData, viewLocals, enteringView, leavingView, renderStart, true);
  53496. };
  53497. self.update = function(registerData) {
  53498. // always reset that this is the primary navView
  53499. isPrimary = true;
  53500. // remember what direction this navView should use
  53501. // this may get updated later by a child navView
  53502. direction = registerData.direction;
  53503. var parentNavViewCtrl = $element.parent().inheritedData('$ionNavViewController');
  53504. if (parentNavViewCtrl) {
  53505. // this navView is nested inside another one
  53506. // update the parent to use this direction and not
  53507. // the other it originally was set to
  53508. // inform the parent navView that it is not the primary navView
  53509. parentNavViewCtrl.isPrimary(false);
  53510. if (direction === 'enter' || direction === 'exit') {
  53511. // they're entering/exiting a history
  53512. // find parent navViewController
  53513. parentNavViewCtrl.direction(direction);
  53514. if (direction === 'enter') {
  53515. // reset the direction so this navView doesn't animate
  53516. // because it's parent will
  53517. direction = 'none';
  53518. }
  53519. }
  53520. }
  53521. };
  53522. self.render = function(registerData, viewLocals, enteringView, leavingView, renderStart, renderEnd) {
  53523. // register the view and figure out where it lives in the various
  53524. // histories and nav stacks, along with how views should enter/leave
  53525. var switcher = $ionicViewSwitcher.create(self, viewLocals, enteringView, leavingView, renderStart, renderEnd);
  53526. // init the rendering of views for this navView directive
  53527. switcher.init(registerData, function() {
  53528. // the view is now compiled, in the dom and linked, now lets transition the views.
  53529. // this uses a callback incase THIS nav-view has a nested nav-view, and after the NESTED
  53530. // nav-view links, the NESTED nav-view would update which direction THIS nav-view should use
  53531. // kick off the transition of views
  53532. switcher.transition(self.direction(), registerData.enableBack, !disableAnimation);
  53533. // reset private vars for next time
  53534. disableRenderStartViewId = disableAnimation = null;
  53535. });
  53536. };
  53537. self.beforeEnter = function(transitionData) {
  53538. if (isPrimary) {
  53539. // only update this nav-view's nav-bar if this is the primary nav-view
  53540. navBarDelegate = transitionData.navBarDelegate;
  53541. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53542. associatedNavBarCtrl && associatedNavBarCtrl.update(transitionData);
  53543. navSwipeAttr('');
  53544. }
  53545. };
  53546. self.activeEleId = function(eleId) {
  53547. if (arguments.length) {
  53548. activeEleId = eleId;
  53549. }
  53550. return activeEleId;
  53551. };
  53552. self.transitionEnd = function() {
  53553. var viewElements = $element.children();
  53554. var x, l, viewElement;
  53555. for (x = 0, l = viewElements.length; x < l; x++) {
  53556. viewElement = viewElements.eq(x);
  53557. if (viewElement.data(DATA_ELE_IDENTIFIER) === activeEleId) {
  53558. // this is the active element
  53559. navViewAttr(viewElement, VIEW_STATUS_ACTIVE);
  53560. } else if (navViewAttr(viewElement) === 'leaving' || navViewAttr(viewElement) === VIEW_STATUS_ACTIVE || navViewAttr(viewElement) === VIEW_STATUS_CACHED) {
  53561. // this is a leaving element or was the former active element, or is an cached element
  53562. if (viewElement.data(DATA_DESTROY_ELE) || viewElement.data(DATA_NO_CACHE)) {
  53563. // this element shouldn't stay cached
  53564. $ionicViewSwitcher.destroyViewEle(viewElement);
  53565. } else {
  53566. // keep in the DOM, mark as cached
  53567. navViewAttr(viewElement, VIEW_STATUS_CACHED);
  53568. // disconnect the leaving scope
  53569. ionic.Utils.disconnectScope(viewElement.scope());
  53570. }
  53571. }
  53572. }
  53573. navSwipeAttr('');
  53574. // ensure no scrolls have been left frozen
  53575. if (self.isSwipeFreeze) {
  53576. $ionicScrollDelegate.freezeAllScrolls(false);
  53577. }
  53578. };
  53579. function onTabsLeave(ev, data) {
  53580. var viewElements = $element.children();
  53581. var viewElement, viewScope;
  53582. for (var x = 0, l = viewElements.length; x < l; x++) {
  53583. viewElement = viewElements.eq(x);
  53584. if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {
  53585. viewScope = viewElement.scope();
  53586. viewScope && viewScope.$emit(ev.name.replace('Tabs', 'View'), data);
  53587. viewScope && viewScope.$broadcast(ev.name.replace('Tabs', 'ParentView'), data);
  53588. break;
  53589. }
  53590. }
  53591. }
  53592. self.cacheCleanup = function() {
  53593. var viewElements = $element.children();
  53594. for (var x = 0, l = viewElements.length; x < l; x++) {
  53595. if (viewElements.eq(x).data(DATA_DESTROY_ELE)) {
  53596. $ionicViewSwitcher.destroyViewEle(viewElements.eq(x));
  53597. }
  53598. }
  53599. };
  53600. self.clearCache = function(stateIds) {
  53601. var viewElements = $element.children();
  53602. var viewElement, viewScope, x, l, y, eleIdentifier;
  53603. for (x = 0, l = viewElements.length; x < l; x++) {
  53604. viewElement = viewElements.eq(x);
  53605. if (stateIds) {
  53606. eleIdentifier = viewElement.data(DATA_ELE_IDENTIFIER);
  53607. for (y = 0; y < stateIds.length; y++) {
  53608. if (eleIdentifier === stateIds[y]) {
  53609. $ionicViewSwitcher.destroyViewEle(viewElement);
  53610. }
  53611. }
  53612. continue;
  53613. }
  53614. if (navViewAttr(viewElement) == VIEW_STATUS_CACHED) {
  53615. $ionicViewSwitcher.destroyViewEle(viewElement);
  53616. } else if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {
  53617. viewScope = viewElement.scope();
  53618. viewScope && viewScope.$broadcast('$ionicView.clearCache');
  53619. }
  53620. }
  53621. };
  53622. self.getViewElements = function() {
  53623. return $element.children();
  53624. };
  53625. self.appendViewElement = function(viewEle, viewLocals) {
  53626. // compile the entering element and get the link function
  53627. var linkFn = $compile(viewEle);
  53628. $element.append(viewEle);
  53629. var viewScope = $scope.$new();
  53630. if (viewLocals && viewLocals.$$controller) {
  53631. viewLocals.$scope = viewScope;
  53632. var controller = $controller(viewLocals.$$controller, viewLocals);
  53633. if (viewLocals.$$controllerAs) {
  53634. viewScope[viewLocals.$$controllerAs] = controller;
  53635. }
  53636. $element.children().data('$ngControllerController', controller);
  53637. }
  53638. linkFn(viewScope);
  53639. return viewScope;
  53640. };
  53641. self.title = function(val) {
  53642. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53643. associatedNavBarCtrl && associatedNavBarCtrl.title(val);
  53644. };
  53645. /**
  53646. * @ngdoc method
  53647. * @name $ionicNavView#enableBackButton
  53648. * @description Enable/disable if the back button can be shown or not. For
  53649. * example, the very first view in the navigation stack would not have a
  53650. * back view, so the back button would be disabled.
  53651. */
  53652. self.enableBackButton = function(shouldEnable) {
  53653. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53654. associatedNavBarCtrl && associatedNavBarCtrl.enableBackButton(shouldEnable);
  53655. };
  53656. /**
  53657. * @ngdoc method
  53658. * @name $ionicNavView#showBackButton
  53659. * @description Show/hide the nav bar active back button. If the back button
  53660. * is not possible this will not force the back button to show. The
  53661. * `enableBackButton()` method handles if a back button is even possible or not.
  53662. */
  53663. self.showBackButton = function(shouldShow) {
  53664. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53665. if (associatedNavBarCtrl) {
  53666. if (arguments.length) {
  53667. return associatedNavBarCtrl.showActiveBackButton(shouldShow);
  53668. }
  53669. return associatedNavBarCtrl.showActiveBackButton();
  53670. }
  53671. return true;
  53672. };
  53673. self.showBar = function(val) {
  53674. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53675. if (associatedNavBarCtrl) {
  53676. if (arguments.length) {
  53677. return associatedNavBarCtrl.showBar(val);
  53678. }
  53679. return associatedNavBarCtrl.showBar();
  53680. }
  53681. return true;
  53682. };
  53683. self.isPrimary = function(val) {
  53684. if (arguments.length) {
  53685. isPrimary = val;
  53686. }
  53687. return isPrimary;
  53688. };
  53689. self.direction = function(val) {
  53690. if (arguments.length) {
  53691. direction = val;
  53692. }
  53693. return direction;
  53694. };
  53695. self.initSwipeBack = function() {
  53696. var swipeBackHitWidth = $ionicConfig.views.swipeBackHitWidth();
  53697. var viewTransition, associatedNavBarCtrl, backView;
  53698. var deregDragStart, deregDrag, deregRelease;
  53699. var windowWidth, startDragX, dragPoints;
  53700. var cancelData = {};
  53701. function onDragStart(ev) {
  53702. if (!isPrimary || !$ionicConfig.views.swipeBackEnabled() || $ionicSideMenuDelegate.isOpenRight() ) return;
  53703. startDragX = getDragX(ev);
  53704. if (startDragX > swipeBackHitWidth) return;
  53705. backView = $ionicHistory.backView();
  53706. var currentView = $ionicHistory.currentView();
  53707. if (!backView || backView.historyId !== currentView.historyId || currentView.canSwipeBack === false) return;
  53708. if (!windowWidth) windowWidth = window.innerWidth;
  53709. self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(true);
  53710. var registerData = {
  53711. direction: 'back'
  53712. };
  53713. dragPoints = [];
  53714. cancelData = {
  53715. showBar: self.showBar(),
  53716. showBackButton: self.showBackButton()
  53717. };
  53718. var switcher = $ionicViewSwitcher.create(self, registerData, backView, currentView, true, false);
  53719. switcher.loadViewElements(registerData);
  53720. switcher.render(registerData);
  53721. viewTransition = switcher.transition('back', $ionicHistory.enabledBack(backView), true);
  53722. associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53723. deregDrag = ionic.onGesture('drag', onDrag, $element[0]);
  53724. deregRelease = ionic.onGesture('release', onRelease, $element[0]);
  53725. }
  53726. function onDrag(ev) {
  53727. if (isPrimary && viewTransition) {
  53728. var dragX = getDragX(ev);
  53729. dragPoints.push({
  53730. t: Date.now(),
  53731. x: dragX
  53732. });
  53733. if (dragX >= windowWidth - 15) {
  53734. onRelease(ev);
  53735. } else {
  53736. var step = Math.min(Math.max(getSwipeCompletion(dragX), 0), 1);
  53737. viewTransition.run(step);
  53738. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.run(step);
  53739. }
  53740. }
  53741. }
  53742. function onRelease(ev) {
  53743. if (isPrimary && viewTransition && dragPoints && dragPoints.length > 1) {
  53744. var now = Date.now();
  53745. var releaseX = getDragX(ev);
  53746. var startDrag = dragPoints[dragPoints.length - 1];
  53747. for (var x = dragPoints.length - 2; x >= 0; x--) {
  53748. if (now - startDrag.t > 200) {
  53749. break;
  53750. }
  53751. startDrag = dragPoints[x];
  53752. }
  53753. var isSwipingRight = (releaseX >= dragPoints[dragPoints.length - 2].x);
  53754. var releaseSwipeCompletion = getSwipeCompletion(releaseX);
  53755. var velocity = Math.abs(startDrag.x - releaseX) / (now - startDrag.t);
  53756. // private variables because ui-router has no way to pass custom data using $state.go
  53757. disableRenderStartViewId = backView.viewId;
  53758. disableAnimation = (releaseSwipeCompletion < 0.03 || releaseSwipeCompletion > 0.97);
  53759. if (isSwipingRight && (releaseSwipeCompletion > 0.5 || velocity > 0.1)) {
  53760. // complete view transition on release
  53761. var speed = (velocity > 0.5 || velocity < 0.05 || releaseX > windowWidth - 45) ? 'fast' : 'slow';
  53762. navSwipeAttr(disableAnimation ? '' : speed);
  53763. backView.go();
  53764. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.complete(!disableAnimation, speed);
  53765. } else {
  53766. // cancel view transition on release
  53767. navSwipeAttr(disableAnimation ? '' : 'fast');
  53768. disableRenderStartViewId = null;
  53769. viewTransition.cancel(!disableAnimation);
  53770. associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.cancel(!disableAnimation, 'fast', cancelData);
  53771. disableAnimation = null;
  53772. }
  53773. }
  53774. ionic.offGesture(deregDrag, 'drag', onDrag);
  53775. ionic.offGesture(deregRelease, 'release', onRelease);
  53776. windowWidth = viewTransition = dragPoints = null;
  53777. self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(false);
  53778. }
  53779. function getDragX(ev) {
  53780. return ionic.tap.pointerCoord(ev.gesture.srcEvent).x;
  53781. }
  53782. function getSwipeCompletion(dragX) {
  53783. return (dragX - startDragX) / windowWidth;
  53784. }
  53785. deregDragStart = ionic.onGesture('dragstart', onDragStart, $element[0]);
  53786. $scope.$on('$destroy', function() {
  53787. ionic.offGesture(deregDragStart, 'dragstart', onDragStart);
  53788. ionic.offGesture(deregDrag, 'drag', onDrag);
  53789. ionic.offGesture(deregRelease, 'release', onRelease);
  53790. self.element = viewTransition = associatedNavBarCtrl = null;
  53791. });
  53792. };
  53793. function navSwipeAttr(val) {
  53794. ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);
  53795. }
  53796. function onTabsTop(ev, isTabsTop) {
  53797. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53798. associatedNavBarCtrl && associatedNavBarCtrl.hasTabsTop(isTabsTop);
  53799. }
  53800. function onBarSubheader(ev, isBarSubheader) {
  53801. var associatedNavBarCtrl = getAssociatedNavBarCtrl();
  53802. associatedNavBarCtrl && associatedNavBarCtrl.hasBarSubheader(isBarSubheader);
  53803. }
  53804. function getAssociatedNavBarCtrl() {
  53805. if (navBarDelegate) {
  53806. for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {
  53807. if ($ionicNavBarDelegate._instances[x].$$delegateHandle == navBarDelegate) {
  53808. return $ionicNavBarDelegate._instances[x];
  53809. }
  53810. }
  53811. }
  53812. return $element.inheritedData('$ionNavBarController');
  53813. }
  53814. }]);
  53815. IonicModule
  53816. .controller('$ionicRefresher', [
  53817. '$scope',
  53818. '$attrs',
  53819. '$element',
  53820. '$ionicBind',
  53821. '$timeout',
  53822. function($scope, $attrs, $element, $ionicBind, $timeout) {
  53823. var self = this,
  53824. isDragging = false,
  53825. isOverscrolling = false,
  53826. dragOffset = 0,
  53827. lastOverscroll = 0,
  53828. ptrThreshold = 60,
  53829. activated = false,
  53830. scrollTime = 500,
  53831. startY = null,
  53832. deltaY = null,
  53833. canOverscroll = true,
  53834. scrollParent,
  53835. scrollChild;
  53836. if (!isDefined($attrs.pullingIcon)) {
  53837. $attrs.$set('pullingIcon', 'ion-android-arrow-down');
  53838. }
  53839. $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';
  53840. $scope.showIcon = isDefined($attrs.refreshingIcon);
  53841. $ionicBind($scope, $attrs, {
  53842. pullingIcon: '@',
  53843. pullingText: '@',
  53844. refreshingIcon: '@',
  53845. refreshingText: '@',
  53846. spinner: '@',
  53847. disablePullingRotation: '@',
  53848. $onRefresh: '&onRefresh',
  53849. $onPulling: '&onPulling'
  53850. });
  53851. function handleMousedown(e) {
  53852. e.touches = e.touches || [{
  53853. screenX: e.screenX,
  53854. screenY: e.screenY
  53855. }];
  53856. // Mouse needs this
  53857. startY = Math.floor(e.touches[0].screenY);
  53858. }
  53859. function handleTouchstart(e) {
  53860. e.touches = e.touches || [{
  53861. screenX: e.screenX,
  53862. screenY: e.screenY
  53863. }];
  53864. startY = e.touches[0].screenY;
  53865. }
  53866. function handleTouchend() {
  53867. // reset Y
  53868. startY = null;
  53869. // if this wasn't an overscroll, get out immediately
  53870. if (!canOverscroll && !isDragging) {
  53871. return;
  53872. }
  53873. // the user has overscrolled but went back to native scrolling
  53874. if (!isDragging) {
  53875. dragOffset = 0;
  53876. isOverscrolling = false;
  53877. setScrollLock(false);
  53878. } else {
  53879. isDragging = false;
  53880. dragOffset = 0;
  53881. // the user has scroll far enough to trigger a refresh
  53882. if (lastOverscroll > ptrThreshold) {
  53883. start();
  53884. scrollTo(ptrThreshold, scrollTime);
  53885. // the user has overscrolled but not far enough to trigger a refresh
  53886. } else {
  53887. scrollTo(0, scrollTime, deactivate);
  53888. isOverscrolling = false;
  53889. }
  53890. }
  53891. }
  53892. function handleTouchmove(e) {
  53893. e.touches = e.touches || [{
  53894. screenX: e.screenX,
  53895. screenY: e.screenY
  53896. }];
  53897. // Force mouse events to have had a down event first
  53898. if (!startY && e.type == 'mousemove') {
  53899. return;
  53900. }
  53901. // if multitouch or regular scroll event, get out immediately
  53902. if (!canOverscroll || e.touches.length > 1) {
  53903. return;
  53904. }
  53905. //if this is a new drag, keep track of where we start
  53906. if (startY === null) {
  53907. startY = e.touches[0].screenY;
  53908. }
  53909. deltaY = e.touches[0].screenY - startY;
  53910. // how far have we dragged so far?
  53911. // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch
  53912. // Only do this if we're not on crosswalk
  53913. if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && !ionic.Platform.isCrosswalk() && scrollParent.scrollTop === 0 && deltaY > 0) {
  53914. isDragging = true;
  53915. e.preventDefault();
  53916. }
  53917. // if we've dragged up and back down in to native scroll territory
  53918. if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {
  53919. if (isOverscrolling) {
  53920. isOverscrolling = false;
  53921. setScrollLock(false);
  53922. }
  53923. if (isDragging) {
  53924. nativescroll(scrollParent, deltaY - dragOffset * -1);
  53925. }
  53926. // if we're not at overscroll 0 yet, 0 out
  53927. if (lastOverscroll !== 0) {
  53928. overscroll(0);
  53929. }
  53930. return;
  53931. } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {
  53932. // starting overscroll, but drag started below scrollTop 0, so we need to offset the position
  53933. dragOffset = deltaY;
  53934. }
  53935. // prevent native scroll events while overscrolling
  53936. e.preventDefault();
  53937. // if not overscrolling yet, initiate overscrolling
  53938. if (!isOverscrolling) {
  53939. isOverscrolling = true;
  53940. setScrollLock(true);
  53941. }
  53942. isDragging = true;
  53943. // overscroll according to the user's drag so far
  53944. overscroll((deltaY - dragOffset) / 3);
  53945. // update the icon accordingly
  53946. if (!activated && lastOverscroll > ptrThreshold) {
  53947. activated = true;
  53948. ionic.requestAnimationFrame(activate);
  53949. } else if (activated && lastOverscroll < ptrThreshold) {
  53950. activated = false;
  53951. ionic.requestAnimationFrame(deactivate);
  53952. }
  53953. }
  53954. function handleScroll(e) {
  53955. // canOverscrol is used to greatly simplify the drag handler during normal scrolling
  53956. canOverscroll = (e.target.scrollTop === 0) || isDragging;
  53957. }
  53958. function overscroll(val) {
  53959. scrollChild.style[ionic.CSS.TRANSFORM] = 'translate3d(0px, ' + val + 'px, 0px)';
  53960. lastOverscroll = val;
  53961. }
  53962. function nativescroll(target, newScrollTop) {
  53963. // creates a scroll event that bubbles, can be cancelled, and with its view
  53964. // and detail property initialized to window and 1, respectively
  53965. target.scrollTop = newScrollTop;
  53966. var e = document.createEvent("UIEvents");
  53967. e.initUIEvent("scroll", true, true, window, 1);
  53968. target.dispatchEvent(e);
  53969. }
  53970. function setScrollLock(enabled) {
  53971. // set the scrollbar to be position:fixed in preparation to overscroll
  53972. // or remove it so the app can be natively scrolled
  53973. if (enabled) {
  53974. ionic.requestAnimationFrame(function() {
  53975. scrollChild.classList.add('overscroll');
  53976. show();
  53977. });
  53978. } else {
  53979. ionic.requestAnimationFrame(function() {
  53980. scrollChild.classList.remove('overscroll');
  53981. hide();
  53982. deactivate();
  53983. });
  53984. }
  53985. }
  53986. $scope.$on('scroll.refreshComplete', function() {
  53987. // prevent the complete from firing before the scroll has started
  53988. $timeout(function() {
  53989. ionic.requestAnimationFrame(tail);
  53990. // scroll back to home during tail animation
  53991. scrollTo(0, scrollTime, deactivate);
  53992. // return to native scrolling after tail animation has time to finish
  53993. $timeout(function() {
  53994. if (isOverscrolling) {
  53995. isOverscrolling = false;
  53996. setScrollLock(false);
  53997. }
  53998. }, scrollTime);
  53999. }, scrollTime);
  54000. });
  54001. function scrollTo(Y, duration, callback) {
  54002. // scroll animation loop w/ easing
  54003. // credit https://gist.github.com/dezinezync/5487119
  54004. var start = Date.now(),
  54005. from = lastOverscroll;
  54006. if (from === Y) {
  54007. callback();
  54008. return; /* Prevent scrolling to the Y point if already there */
  54009. }
  54010. // decelerating to zero velocity
  54011. function easeOutCubic(t) {
  54012. return (--t) * t * t + 1;
  54013. }
  54014. // scroll loop
  54015. function scroll() {
  54016. var currentTime = Date.now(),
  54017. time = Math.min(1, ((currentTime - start) / duration)),
  54018. // where .5 would be 50% of time on a linear scale easedT gives a
  54019. // fraction based on the easing method
  54020. easedT = easeOutCubic(time);
  54021. overscroll(Math.floor((easedT * (Y - from)) + from));
  54022. if (time < 1) {
  54023. ionic.requestAnimationFrame(scroll);
  54024. } else {
  54025. if (Y < 5 && Y > -5) {
  54026. isOverscrolling = false;
  54027. setScrollLock(false);
  54028. }
  54029. callback && callback();
  54030. }
  54031. }
  54032. // start scroll loop
  54033. ionic.requestAnimationFrame(scroll);
  54034. }
  54035. var touchStartEvent, touchMoveEvent, touchEndEvent;
  54036. if (window.navigator.pointerEnabled) {
  54037. touchStartEvent = 'pointerdown';
  54038. touchMoveEvent = 'pointermove';
  54039. touchEndEvent = 'pointerup';
  54040. } else if (window.navigator.msPointerEnabled) {
  54041. touchStartEvent = 'MSPointerDown';
  54042. touchMoveEvent = 'MSPointerMove';
  54043. touchEndEvent = 'MSPointerUp';
  54044. } else {
  54045. touchStartEvent = 'touchstart';
  54046. touchMoveEvent = 'touchmove';
  54047. touchEndEvent = 'touchend';
  54048. }
  54049. self.init = function() {
  54050. scrollParent = $element.parent().parent()[0];
  54051. scrollChild = $element.parent()[0];
  54052. if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||
  54053. !scrollChild || !scrollChild.classList.contains('scroll')) {
  54054. throw new Error('Refresher must be immediate child of ion-content or ion-scroll');
  54055. }
  54056. ionic.on(touchStartEvent, handleTouchstart, scrollChild);
  54057. ionic.on(touchMoveEvent, handleTouchmove, scrollChild);
  54058. ionic.on(touchEndEvent, handleTouchend, scrollChild);
  54059. ionic.on('mousedown', handleMousedown, scrollChild);
  54060. ionic.on('mousemove', handleTouchmove, scrollChild);
  54061. ionic.on('mouseup', handleTouchend, scrollChild);
  54062. ionic.on('scroll', handleScroll, scrollParent);
  54063. // cleanup when done
  54064. $scope.$on('$destroy', destroy);
  54065. };
  54066. function destroy() {
  54067. if ( scrollChild ) {
  54068. ionic.off(touchStartEvent, handleTouchstart, scrollChild);
  54069. ionic.off(touchMoveEvent, handleTouchmove, scrollChild);
  54070. ionic.off(touchEndEvent, handleTouchend, scrollChild);
  54071. ionic.off('mousedown', handleMousedown, scrollChild);
  54072. ionic.off('mousemove', handleTouchmove, scrollChild);
  54073. ionic.off('mouseup', handleTouchend, scrollChild);
  54074. }
  54075. if ( scrollParent ) {
  54076. ionic.off('scroll', handleScroll, scrollParent);
  54077. }
  54078. scrollParent = null;
  54079. scrollChild = null;
  54080. }
  54081. // DOM manipulation and broadcast methods shared by JS and Native Scrolling
  54082. // getter used by JS Scrolling
  54083. self.getRefresherDomMethods = function() {
  54084. return {
  54085. activate: activate,
  54086. deactivate: deactivate,
  54087. start: start,
  54088. show: show,
  54089. hide: hide,
  54090. tail: tail
  54091. };
  54092. };
  54093. function activate() {
  54094. $element[0].classList.add('active');
  54095. $scope.$onPulling();
  54096. }
  54097. function deactivate() {
  54098. // give tail 150ms to finish
  54099. $timeout(function() {
  54100. // deactivateCallback
  54101. $element.removeClass('active refreshing refreshing-tail');
  54102. if (activated) activated = false;
  54103. }, 150);
  54104. }
  54105. function start() {
  54106. // startCallback
  54107. $element[0].classList.add('refreshing');
  54108. var q = $scope.$onRefresh();
  54109. if (q && q.then) {
  54110. q['finally'](function() {
  54111. $scope.$broadcast('scroll.refreshComplete');
  54112. });
  54113. }
  54114. }
  54115. function show() {
  54116. // showCallback
  54117. $element[0].classList.remove('invisible');
  54118. }
  54119. function hide() {
  54120. // showCallback
  54121. $element[0].classList.add('invisible');
  54122. }
  54123. function tail() {
  54124. // tailCallback
  54125. $element[0].classList.add('refreshing-tail');
  54126. }
  54127. // for testing
  54128. self.__handleTouchmove = handleTouchmove;
  54129. self.__getScrollChild = function() { return scrollChild; };
  54130. self.__getScrollParent = function() { return scrollParent; };
  54131. }
  54132. ]);
  54133. /**
  54134. * @private
  54135. */
  54136. IonicModule
  54137. .controller('$ionicScroll', [
  54138. '$scope',
  54139. 'scrollViewOptions',
  54140. '$timeout',
  54141. '$window',
  54142. '$location',
  54143. '$document',
  54144. '$ionicScrollDelegate',
  54145. '$ionicHistory',
  54146. function($scope,
  54147. scrollViewOptions,
  54148. $timeout,
  54149. $window,
  54150. $location,
  54151. $document,
  54152. $ionicScrollDelegate,
  54153. $ionicHistory) {
  54154. var self = this;
  54155. // for testing
  54156. self.__timeout = $timeout;
  54157. self._scrollViewOptions = scrollViewOptions; //for testing
  54158. self.isNative = function() {
  54159. return !!scrollViewOptions.nativeScrolling;
  54160. };
  54161. var element = self.element = scrollViewOptions.el;
  54162. var $element = self.$element = jqLite(element);
  54163. var scrollView;
  54164. if (self.isNative()) {
  54165. scrollView = self.scrollView = new ionic.views.ScrollNative(scrollViewOptions);
  54166. } else {
  54167. scrollView = self.scrollView = new ionic.views.Scroll(scrollViewOptions);
  54168. }
  54169. //Attach self to element as a controller so other directives can require this controller
  54170. //through `require: '$ionicScroll'
  54171. //Also attach to parent so that sibling elements can require this
  54172. ($element.parent().length ? $element.parent() : $element)
  54173. .data('$$ionicScrollController', self);
  54174. var deregisterInstance = $ionicScrollDelegate._registerInstance(
  54175. self, scrollViewOptions.delegateHandle, function() {
  54176. return $ionicHistory.isActiveScope($scope);
  54177. }
  54178. );
  54179. if (!isDefined(scrollViewOptions.bouncing)) {
  54180. ionic.Platform.ready(function() {
  54181. if (scrollView && scrollView.options) {
  54182. scrollView.options.bouncing = true;
  54183. if (ionic.Platform.isAndroid()) {
  54184. // No bouncing by default on Android
  54185. scrollView.options.bouncing = false;
  54186. // Faster scroll decel
  54187. scrollView.options.deceleration = 0.95;
  54188. }
  54189. }
  54190. });
  54191. }
  54192. var resize = angular.bind(scrollView, scrollView.resize);
  54193. angular.element($window).on('resize', resize);
  54194. var scrollFunc = function(e) {
  54195. var detail = (e.originalEvent || e).detail || {};
  54196. $scope.$onScroll && $scope.$onScroll({
  54197. event: e,
  54198. scrollTop: detail.scrollTop || 0,
  54199. scrollLeft: detail.scrollLeft || 0
  54200. });
  54201. };
  54202. $element.on('scroll', scrollFunc);
  54203. $scope.$on('$destroy', function() {
  54204. deregisterInstance();
  54205. scrollView && scrollView.__cleanup && scrollView.__cleanup();
  54206. angular.element($window).off('resize', resize);
  54207. if ( $element ) {
  54208. $element.off('scroll', scrollFunc);
  54209. }
  54210. if ( self._scrollViewOptions ) {
  54211. self._scrollViewOptions.el = null;
  54212. }
  54213. if ( scrollViewOptions ) {
  54214. scrollViewOptions.el = null;
  54215. }
  54216. scrollView = self.scrollView = scrollViewOptions = self._scrollViewOptions = element = self.$element = $element = null;
  54217. });
  54218. $timeout(function() {
  54219. scrollView && scrollView.run && scrollView.run();
  54220. });
  54221. self.getScrollView = function() {
  54222. return scrollView;
  54223. };
  54224. self.getScrollPosition = function() {
  54225. return scrollView.getValues();
  54226. };
  54227. self.resize = function() {
  54228. return $timeout(resize, 0, false).then(function() {
  54229. $element && $element.triggerHandler('scroll-resize');
  54230. });
  54231. };
  54232. self.scrollTop = function(shouldAnimate) {
  54233. self.resize().then(function() {
  54234. if (!scrollView) {
  54235. return;
  54236. }
  54237. scrollView.scrollTo(0, 0, !!shouldAnimate);
  54238. });
  54239. };
  54240. self.scrollBottom = function(shouldAnimate) {
  54241. self.resize().then(function() {
  54242. if (!scrollView) {
  54243. return;
  54244. }
  54245. var max = scrollView.getScrollMax();
  54246. scrollView.scrollTo(max.left, max.top, !!shouldAnimate);
  54247. });
  54248. };
  54249. self.scrollTo = function(left, top, shouldAnimate) {
  54250. self.resize().then(function() {
  54251. if (!scrollView) {
  54252. return;
  54253. }
  54254. scrollView.scrollTo(left, top, !!shouldAnimate);
  54255. });
  54256. };
  54257. self.zoomTo = function(zoom, shouldAnimate, originLeft, originTop) {
  54258. self.resize().then(function() {
  54259. if (!scrollView) {
  54260. return;
  54261. }
  54262. scrollView.zoomTo(zoom, !!shouldAnimate, originLeft, originTop);
  54263. });
  54264. };
  54265. self.zoomBy = function(zoom, shouldAnimate, originLeft, originTop) {
  54266. self.resize().then(function() {
  54267. if (!scrollView) {
  54268. return;
  54269. }
  54270. scrollView.zoomBy(zoom, !!shouldAnimate, originLeft, originTop);
  54271. });
  54272. };
  54273. self.scrollBy = function(left, top, shouldAnimate) {
  54274. self.resize().then(function() {
  54275. if (!scrollView) {
  54276. return;
  54277. }
  54278. scrollView.scrollBy(left, top, !!shouldAnimate);
  54279. });
  54280. };
  54281. self.anchorScroll = function(shouldAnimate) {
  54282. self.resize().then(function() {
  54283. if (!scrollView) {
  54284. return;
  54285. }
  54286. var hash = $location.hash();
  54287. var elm = hash && $document[0].getElementById(hash);
  54288. if (!(hash && elm)) {
  54289. scrollView.scrollTo(0, 0, !!shouldAnimate);
  54290. return;
  54291. }
  54292. var curElm = elm;
  54293. var scrollLeft = 0, scrollTop = 0;
  54294. do {
  54295. if (curElm !== null) scrollLeft += curElm.offsetLeft;
  54296. if (curElm !== null) scrollTop += curElm.offsetTop;
  54297. curElm = curElm.offsetParent;
  54298. } while (curElm.attributes != self.element.attributes && curElm.offsetParent);
  54299. scrollView.scrollTo(scrollLeft, scrollTop, !!shouldAnimate);
  54300. });
  54301. };
  54302. self.freezeScroll = scrollView.freeze;
  54303. self.freezeScrollShut = scrollView.freezeShut;
  54304. self.freezeAllScrolls = function(shouldFreeze) {
  54305. for (var i = 0; i < $ionicScrollDelegate._instances.length; i++) {
  54306. $ionicScrollDelegate._instances[i].freezeScroll(shouldFreeze);
  54307. }
  54308. };
  54309. /**
  54310. * @private
  54311. */
  54312. self._setRefresher = function(refresherScope, refresherElement, refresherMethods) {
  54313. self.refresher = refresherElement;
  54314. var refresherHeight = self.refresher.clientHeight || 60;
  54315. scrollView.activatePullToRefresh(
  54316. refresherHeight,
  54317. refresherMethods
  54318. );
  54319. };
  54320. }]);
  54321. IonicModule
  54322. .controller('$ionicSideMenus', [
  54323. '$scope',
  54324. '$attrs',
  54325. '$ionicSideMenuDelegate',
  54326. '$ionicPlatform',
  54327. '$ionicBody',
  54328. '$ionicHistory',
  54329. '$ionicScrollDelegate',
  54330. 'IONIC_BACK_PRIORITY',
  54331. '$rootScope',
  54332. function($scope, $attrs, $ionicSideMenuDelegate, $ionicPlatform, $ionicBody, $ionicHistory, $ionicScrollDelegate, IONIC_BACK_PRIORITY, $rootScope) {
  54333. var self = this;
  54334. var rightShowing, leftShowing, isDragging;
  54335. var startX, lastX, offsetX, isAsideExposed;
  54336. var enableMenuWithBackViews = true;
  54337. self.$scope = $scope;
  54338. self.initialize = function(options) {
  54339. self.left = options.left;
  54340. self.right = options.right;
  54341. self.setContent(options.content);
  54342. self.dragThresholdX = options.dragThresholdX || 10;
  54343. $ionicHistory.registerHistory(self.$scope);
  54344. };
  54345. /**
  54346. * Set the content view controller if not passed in the constructor options.
  54347. *
  54348. * @param {object} content
  54349. */
  54350. self.setContent = function(content) {
  54351. if (content) {
  54352. self.content = content;
  54353. self.content.onDrag = function(e) {
  54354. self._handleDrag(e);
  54355. };
  54356. self.content.endDrag = function(e) {
  54357. self._endDrag(e);
  54358. };
  54359. }
  54360. };
  54361. self.isOpenLeft = function() {
  54362. return self.getOpenAmount() > 0;
  54363. };
  54364. self.isOpenRight = function() {
  54365. return self.getOpenAmount() < 0;
  54366. };
  54367. /**
  54368. * Toggle the left menu to open 100%
  54369. */
  54370. self.toggleLeft = function(shouldOpen) {
  54371. if (isAsideExposed || !self.left.isEnabled) return;
  54372. var openAmount = self.getOpenAmount();
  54373. if (arguments.length === 0) {
  54374. shouldOpen = openAmount <= 0;
  54375. }
  54376. self.content.enableAnimation();
  54377. if (!shouldOpen) {
  54378. self.openPercentage(0);
  54379. $rootScope.$emit('$ionicSideMenuClose', 'left');
  54380. } else {
  54381. self.openPercentage(100);
  54382. $rootScope.$emit('$ionicSideMenuOpen', 'left');
  54383. }
  54384. };
  54385. /**
  54386. * Toggle the right menu to open 100%
  54387. */
  54388. self.toggleRight = function(shouldOpen) {
  54389. if (isAsideExposed || !self.right.isEnabled) return;
  54390. var openAmount = self.getOpenAmount();
  54391. if (arguments.length === 0) {
  54392. shouldOpen = openAmount >= 0;
  54393. }
  54394. self.content.enableAnimation();
  54395. if (!shouldOpen) {
  54396. self.openPercentage(0);
  54397. $rootScope.$emit('$ionicSideMenuClose', 'right');
  54398. } else {
  54399. self.openPercentage(-100);
  54400. $rootScope.$emit('$ionicSideMenuOpen', 'right');
  54401. }
  54402. };
  54403. self.toggle = function(side) {
  54404. if (side == 'right') {
  54405. self.toggleRight();
  54406. } else {
  54407. self.toggleLeft();
  54408. }
  54409. };
  54410. /**
  54411. * Close all menus.
  54412. */
  54413. self.close = function() {
  54414. self.openPercentage(0);
  54415. $rootScope.$emit('$ionicSideMenuClose', 'left');
  54416. $rootScope.$emit('$ionicSideMenuClose', 'right');
  54417. };
  54418. /**
  54419. * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)
  54420. */
  54421. self.getOpenAmount = function() {
  54422. return self.content && self.content.getTranslateX() || 0;
  54423. };
  54424. /**
  54425. * @return {float} The ratio of open amount over menu width. For example, a
  54426. * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative
  54427. * for right menu.
  54428. */
  54429. self.getOpenRatio = function() {
  54430. var amount = self.getOpenAmount();
  54431. if (amount >= 0) {
  54432. return amount / self.left.width;
  54433. }
  54434. return amount / self.right.width;
  54435. };
  54436. self.isOpen = function() {
  54437. return self.getOpenAmount() !== 0;
  54438. };
  54439. /**
  54440. * @return {float} The percentage of open amount over menu width. For example, a
  54441. * menu of width 100 open 50 pixels would be open 50%. Value is negative
  54442. * for right menu.
  54443. */
  54444. self.getOpenPercentage = function() {
  54445. return self.getOpenRatio() * 100;
  54446. };
  54447. /**
  54448. * Open the menu with a given percentage amount.
  54449. * @param {float} percentage The percentage (positive or negative for left/right) to open the menu.
  54450. */
  54451. self.openPercentage = function(percentage) {
  54452. var p = percentage / 100;
  54453. if (self.left && percentage >= 0) {
  54454. self.openAmount(self.left.width * p);
  54455. } else if (self.right && percentage < 0) {
  54456. self.openAmount(self.right.width * p);
  54457. }
  54458. // add the CSS class "menu-open" if the percentage does not
  54459. // equal 0, otherwise remove the class from the body element
  54460. $ionicBody.enableClass((percentage !== 0), 'menu-open');
  54461. self.content.setCanScroll(percentage == 0);
  54462. };
  54463. /*
  54464. function freezeAllScrolls(shouldFreeze) {
  54465. if (shouldFreeze && !self.isScrollFreeze) {
  54466. $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);
  54467. } else if (!shouldFreeze && self.isScrollFreeze) {
  54468. $ionicScrollDelegate.freezeAllScrolls(false);
  54469. }
  54470. self.isScrollFreeze = shouldFreeze;
  54471. }
  54472. */
  54473. /**
  54474. * Open the menu the given pixel amount.
  54475. * @param {float} amount the pixel amount to open the menu. Positive value for left menu,
  54476. * negative value for right menu (only one menu will be visible at a time).
  54477. */
  54478. self.openAmount = function(amount) {
  54479. var maxLeft = self.left && self.left.width || 0;
  54480. var maxRight = self.right && self.right.width || 0;
  54481. // Check if we can move to that side, depending if the left/right panel is enabled
  54482. if (!(self.left && self.left.isEnabled) && amount > 0) {
  54483. self.content.setTranslateX(0);
  54484. return;
  54485. }
  54486. if (!(self.right && self.right.isEnabled) && amount < 0) {
  54487. self.content.setTranslateX(0);
  54488. return;
  54489. }
  54490. if (leftShowing && amount > maxLeft) {
  54491. self.content.setTranslateX(maxLeft);
  54492. return;
  54493. }
  54494. if (rightShowing && amount < -maxRight) {
  54495. self.content.setTranslateX(-maxRight);
  54496. return;
  54497. }
  54498. self.content.setTranslateX(amount);
  54499. leftShowing = amount > 0;
  54500. rightShowing = amount < 0;
  54501. if (amount > 0) {
  54502. // Push the z-index of the right menu down
  54503. self.right && self.right.pushDown && self.right.pushDown();
  54504. // Bring the z-index of the left menu up
  54505. self.left && self.left.bringUp && self.left.bringUp();
  54506. } else {
  54507. // Bring the z-index of the right menu up
  54508. self.right && self.right.bringUp && self.right.bringUp();
  54509. // Push the z-index of the left menu down
  54510. self.left && self.left.pushDown && self.left.pushDown();
  54511. }
  54512. };
  54513. /**
  54514. * Given an event object, find the final resting position of this side
  54515. * menu. For example, if the user "throws" the content to the right and
  54516. * releases the touch, the left menu should snap open (animated, of course).
  54517. *
  54518. * @param {Event} e the gesture event to use for snapping
  54519. */
  54520. self.snapToRest = function(e) {
  54521. // We want to animate at the end of this
  54522. self.content.enableAnimation();
  54523. isDragging = false;
  54524. // Check how much the panel is open after the drag, and
  54525. // what the drag velocity is
  54526. var ratio = self.getOpenRatio();
  54527. if (ratio === 0) {
  54528. // Just to be safe
  54529. self.openPercentage(0);
  54530. return;
  54531. }
  54532. var velocityThreshold = 0.3;
  54533. var velocityX = e.gesture.velocityX;
  54534. var direction = e.gesture.direction;
  54535. // Going right, less than half, too slow (snap back)
  54536. if (ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
  54537. self.openPercentage(0);
  54538. }
  54539. // Going left, more than half, too slow (snap back)
  54540. else if (ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {
  54541. self.openPercentage(100);
  54542. }
  54543. // Going left, less than half, too slow (snap back)
  54544. else if (ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {
  54545. self.openPercentage(0);
  54546. }
  54547. // Going right, more than half, too slow (snap back)
  54548. else if (ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {
  54549. self.openPercentage(-100);
  54550. }
  54551. // Going right, more than half, or quickly (snap open)
  54552. else if (direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {
  54553. self.openPercentage(100);
  54554. }
  54555. // Going left, more than half, or quickly (span open)
  54556. else if (direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {
  54557. self.openPercentage(-100);
  54558. }
  54559. // Snap back for safety
  54560. else {
  54561. self.openPercentage(0);
  54562. }
  54563. };
  54564. self.enableMenuWithBackViews = function(val) {
  54565. if (arguments.length) {
  54566. enableMenuWithBackViews = !!val;
  54567. }
  54568. return enableMenuWithBackViews;
  54569. };
  54570. self.isAsideExposed = function() {
  54571. return !!isAsideExposed;
  54572. };
  54573. self.exposeAside = function(shouldExposeAside) {
  54574. if (!(self.left && self.left.isEnabled) && !(self.right && self.right.isEnabled)) return;
  54575. self.close();
  54576. isAsideExposed = shouldExposeAside;
  54577. if ((self.left && self.left.isEnabled) && (self.right && self.right.isEnabled)) {
  54578. self.content.setMarginLeftAndRight(isAsideExposed ? self.left.width : 0, isAsideExposed ? self.right.width : 0);
  54579. } else if (self.left && self.left.isEnabled) {
  54580. // set the left marget width if it should be exposed
  54581. // otherwise set false so there's no left margin
  54582. self.content.setMarginLeft(isAsideExposed ? self.left.width : 0);
  54583. } else if (self.right && self.right.isEnabled) {
  54584. self.content.setMarginRight(isAsideExposed ? self.right.width : 0);
  54585. }
  54586. self.$scope.$emit('$ionicExposeAside', isAsideExposed);
  54587. };
  54588. self.activeAsideResizing = function(isResizing) {
  54589. $ionicBody.enableClass(isResizing, 'aside-resizing');
  54590. };
  54591. // End a drag with the given event
  54592. self._endDrag = function(e) {
  54593. if (isAsideExposed) return;
  54594. if (isDragging) {
  54595. self.snapToRest(e);
  54596. }
  54597. startX = null;
  54598. lastX = null;
  54599. offsetX = null;
  54600. };
  54601. // Handle a drag event
  54602. self._handleDrag = function(e) {
  54603. if (isAsideExposed || !$scope.dragContent) return;
  54604. // If we don't have start coords, grab and store them
  54605. if (!startX) {
  54606. startX = e.gesture.touches[0].pageX;
  54607. lastX = startX;
  54608. } else {
  54609. // Grab the current tap coords
  54610. lastX = e.gesture.touches[0].pageX;
  54611. }
  54612. // Calculate difference from the tap points
  54613. if (!isDragging && Math.abs(lastX - startX) > self.dragThresholdX) {
  54614. // if the difference is greater than threshold, start dragging using the current
  54615. // point as the starting point
  54616. startX = lastX;
  54617. isDragging = true;
  54618. // Initialize dragging
  54619. self.content.disableAnimation();
  54620. offsetX = self.getOpenAmount();
  54621. }
  54622. if (isDragging) {
  54623. self.openAmount(offsetX + (lastX - startX));
  54624. //self.content.setCanScroll(false);
  54625. }
  54626. };
  54627. self.canDragContent = function(canDrag) {
  54628. if (arguments.length) {
  54629. $scope.dragContent = !!canDrag;
  54630. }
  54631. return $scope.dragContent;
  54632. };
  54633. self.edgeThreshold = 25;
  54634. self.edgeThresholdEnabled = false;
  54635. self.edgeDragThreshold = function(value) {
  54636. if (arguments.length) {
  54637. if (isNumber(value) && value > 0) {
  54638. self.edgeThreshold = value;
  54639. self.edgeThresholdEnabled = true;
  54640. } else {
  54641. self.edgeThresholdEnabled = !!value;
  54642. }
  54643. }
  54644. return self.edgeThresholdEnabled;
  54645. };
  54646. self.isDraggableTarget = function(e) {
  54647. //Only restrict edge when sidemenu is closed and restriction is enabled
  54648. var shouldOnlyAllowEdgeDrag = self.edgeThresholdEnabled && !self.isOpen();
  54649. var startX = e.gesture.startEvent && e.gesture.startEvent.center &&
  54650. e.gesture.startEvent.center.pageX;
  54651. var dragIsWithinBounds = !shouldOnlyAllowEdgeDrag ||
  54652. startX <= self.edgeThreshold ||
  54653. startX >= self.content.element.offsetWidth - self.edgeThreshold;
  54654. var backView = $ionicHistory.backView();
  54655. var menuEnabled = enableMenuWithBackViews ? true : !backView;
  54656. if (!menuEnabled) {
  54657. var currentView = $ionicHistory.currentView() || {};
  54658. return (dragIsWithinBounds && (backView.historyId !== currentView.historyId));
  54659. }
  54660. return ($scope.dragContent || self.isOpen()) &&
  54661. dragIsWithinBounds &&
  54662. !e.gesture.srcEvent.defaultPrevented &&
  54663. menuEnabled &&
  54664. !e.target.tagName.match(/input|textarea|select|object|embed/i) &&
  54665. !e.target.isContentEditable &&
  54666. !(e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll') == 'true');
  54667. };
  54668. $scope.sideMenuContentTranslateX = 0;
  54669. var deregisterBackButtonAction = noop;
  54670. var closeSideMenu = angular.bind(self, self.close);
  54671. $scope.$watch(function() {
  54672. return self.getOpenAmount() !== 0;
  54673. }, function(isOpen) {
  54674. deregisterBackButtonAction();
  54675. if (isOpen) {
  54676. deregisterBackButtonAction = $ionicPlatform.registerBackButtonAction(
  54677. closeSideMenu,
  54678. IONIC_BACK_PRIORITY.sideMenu
  54679. );
  54680. }
  54681. });
  54682. var deregisterInstance = $ionicSideMenuDelegate._registerInstance(
  54683. self, $attrs.delegateHandle, function() {
  54684. return $ionicHistory.isActiveScope($scope);
  54685. }
  54686. );
  54687. $scope.$on('$destroy', function() {
  54688. deregisterInstance();
  54689. deregisterBackButtonAction();
  54690. self.$scope = null;
  54691. if (self.content) {
  54692. self.content.setCanScroll(true);
  54693. self.content.element = null;
  54694. self.content = null;
  54695. }
  54696. });
  54697. self.initialize({
  54698. left: {
  54699. width: 275
  54700. },
  54701. right: {
  54702. width: 275
  54703. }
  54704. });
  54705. }]);
  54706. (function(ionic) {
  54707. var TRANSLATE32 = 'translate(32,32)';
  54708. var STROKE_OPACITY = 'stroke-opacity';
  54709. var ROUND = 'round';
  54710. var INDEFINITE = 'indefinite';
  54711. var DURATION = '750ms';
  54712. var NONE = 'none';
  54713. var SHORTCUTS = {
  54714. a: 'animate',
  54715. an: 'attributeName',
  54716. at: 'animateTransform',
  54717. c: 'circle',
  54718. da: 'stroke-dasharray',
  54719. os: 'stroke-dashoffset',
  54720. f: 'fill',
  54721. lc: 'stroke-linecap',
  54722. rc: 'repeatCount',
  54723. sw: 'stroke-width',
  54724. t: 'transform',
  54725. v: 'values'
  54726. };
  54727. var SPIN_ANIMATION = {
  54728. v: '0,32,32;360,32,32',
  54729. an: 'transform',
  54730. type: 'rotate',
  54731. rc: INDEFINITE,
  54732. dur: DURATION
  54733. };
  54734. function createSvgElement(tagName, data, parent, spinnerName) {
  54735. var ele = document.createElement(SHORTCUTS[tagName] || tagName);
  54736. var k, x, y;
  54737. for (k in data) {
  54738. if (angular.isArray(data[k])) {
  54739. for (x = 0; x < data[k].length; x++) {
  54740. if (data[k][x].fn) {
  54741. for (y = 0; y < data[k][x].t; y++) {
  54742. createSvgElement(k, data[k][x].fn(y, spinnerName), ele, spinnerName);
  54743. }
  54744. } else {
  54745. createSvgElement(k, data[k][x], ele, spinnerName);
  54746. }
  54747. }
  54748. } else {
  54749. setSvgAttribute(ele, k, data[k]);
  54750. }
  54751. }
  54752. parent.appendChild(ele);
  54753. }
  54754. function setSvgAttribute(ele, k, v) {
  54755. ele.setAttribute(SHORTCUTS[k] || k, v);
  54756. }
  54757. function animationValues(strValues, i) {
  54758. var values = strValues.split(';');
  54759. var back = values.slice(i);
  54760. var front = values.slice(0, values.length - back.length);
  54761. values = back.concat(front).reverse();
  54762. return values.join(';') + ';' + values[0];
  54763. }
  54764. var IOS_SPINNER = {
  54765. sw: 4,
  54766. lc: ROUND,
  54767. line: [{
  54768. fn: function(i, spinnerName) {
  54769. return {
  54770. y1: spinnerName == 'ios' ? 17 : 12,
  54771. y2: spinnerName == 'ios' ? 29 : 20,
  54772. t: TRANSLATE32 + ' rotate(' + (30 * i + (i < 6 ? 180 : -180)) + ')',
  54773. a: [{
  54774. fn: function() {
  54775. return {
  54776. an: STROKE_OPACITY,
  54777. dur: DURATION,
  54778. v: animationValues('0;.1;.15;.25;.35;.45;.55;.65;.7;.85;1', i),
  54779. rc: INDEFINITE
  54780. };
  54781. },
  54782. t: 1
  54783. }]
  54784. };
  54785. },
  54786. t: 12
  54787. }]
  54788. };
  54789. var spinners = {
  54790. android: {
  54791. c: [{
  54792. sw: 6,
  54793. da: 128,
  54794. os: 82,
  54795. r: 26,
  54796. cx: 32,
  54797. cy: 32,
  54798. f: NONE
  54799. }]
  54800. },
  54801. ios: IOS_SPINNER,
  54802. 'ios-small': IOS_SPINNER,
  54803. bubbles: {
  54804. sw: 0,
  54805. c: [{
  54806. fn: function(i) {
  54807. return {
  54808. cx: 24 * Math.cos(2 * Math.PI * i / 8),
  54809. cy: 24 * Math.sin(2 * Math.PI * i / 8),
  54810. t: TRANSLATE32,
  54811. a: [{
  54812. fn: function() {
  54813. return {
  54814. an: 'r',
  54815. dur: DURATION,
  54816. v: animationValues('1;2;3;4;5;6;7;8', i),
  54817. rc: INDEFINITE
  54818. };
  54819. },
  54820. t: 1
  54821. }]
  54822. };
  54823. },
  54824. t: 8
  54825. }]
  54826. },
  54827. circles: {
  54828. c: [{
  54829. fn: function(i) {
  54830. return {
  54831. r: 5,
  54832. cx: 24 * Math.cos(2 * Math.PI * i / 8),
  54833. cy: 24 * Math.sin(2 * Math.PI * i / 8),
  54834. t: TRANSLATE32,
  54835. sw: 0,
  54836. a: [{
  54837. fn: function() {
  54838. return {
  54839. an: 'fill-opacity',
  54840. dur: DURATION,
  54841. v: animationValues('.3;.3;.3;.4;.7;.85;.9;1', i),
  54842. rc: INDEFINITE
  54843. };
  54844. },
  54845. t: 1
  54846. }]
  54847. };
  54848. },
  54849. t: 8
  54850. }]
  54851. },
  54852. crescent: {
  54853. c: [{
  54854. sw: 4,
  54855. da: 128,
  54856. os: 82,
  54857. r: 26,
  54858. cx: 32,
  54859. cy: 32,
  54860. f: NONE,
  54861. at: [SPIN_ANIMATION]
  54862. }]
  54863. },
  54864. dots: {
  54865. c: [{
  54866. fn: function(i) {
  54867. return {
  54868. cx: 16 + (16 * i),
  54869. cy: 32,
  54870. sw: 0,
  54871. a: [{
  54872. fn: function() {
  54873. return {
  54874. an: 'fill-opacity',
  54875. dur: DURATION,
  54876. v: animationValues('.5;.6;.8;1;.8;.6;.5', i),
  54877. rc: INDEFINITE
  54878. };
  54879. },
  54880. t: 1
  54881. }, {
  54882. fn: function() {
  54883. return {
  54884. an: 'r',
  54885. dur: DURATION,
  54886. v: animationValues('4;5;6;5;4;3;3', i),
  54887. rc: INDEFINITE
  54888. };
  54889. },
  54890. t: 1
  54891. }]
  54892. };
  54893. },
  54894. t: 3
  54895. }]
  54896. },
  54897. lines: {
  54898. sw: 7,
  54899. lc: ROUND,
  54900. line: [{
  54901. fn: function(i) {
  54902. return {
  54903. x1: 10 + (i * 14),
  54904. x2: 10 + (i * 14),
  54905. a: [{
  54906. fn: function() {
  54907. return {
  54908. an: 'y1',
  54909. dur: DURATION,
  54910. v: animationValues('16;18;28;18;16', i),
  54911. rc: INDEFINITE
  54912. };
  54913. },
  54914. t: 1
  54915. }, {
  54916. fn: function() {
  54917. return {
  54918. an: 'y2',
  54919. dur: DURATION,
  54920. v: animationValues('48;44;36;46;48', i),
  54921. rc: INDEFINITE
  54922. };
  54923. },
  54924. t: 1
  54925. }, {
  54926. fn: function() {
  54927. return {
  54928. an: STROKE_OPACITY,
  54929. dur: DURATION,
  54930. v: animationValues('1;.8;.5;.4;1', i),
  54931. rc: INDEFINITE
  54932. };
  54933. },
  54934. t: 1
  54935. }]
  54936. };
  54937. },
  54938. t: 4
  54939. }]
  54940. },
  54941. ripple: {
  54942. f: NONE,
  54943. 'fill-rule': 'evenodd',
  54944. sw: 3,
  54945. circle: [{
  54946. fn: function(i) {
  54947. return {
  54948. cx: 32,
  54949. cy: 32,
  54950. a: [{
  54951. fn: function() {
  54952. return {
  54953. an: 'r',
  54954. begin: (i * -1) + 's',
  54955. dur: '2s',
  54956. v: '0;24',
  54957. keyTimes: '0;1',
  54958. keySplines: '0.1,0.2,0.3,1',
  54959. calcMode: 'spline',
  54960. rc: INDEFINITE
  54961. };
  54962. },
  54963. t: 1
  54964. }, {
  54965. fn: function() {
  54966. return {
  54967. an: STROKE_OPACITY,
  54968. begin: (i * -1) + 's',
  54969. dur: '2s',
  54970. v: '.2;1;.2;0',
  54971. rc: INDEFINITE
  54972. };
  54973. },
  54974. t: 1
  54975. }]
  54976. };
  54977. },
  54978. t: 2
  54979. }]
  54980. },
  54981. spiral: {
  54982. defs: [{
  54983. linearGradient: [{
  54984. id: 'sGD',
  54985. gradientUnits: 'userSpaceOnUse',
  54986. x1: 55, y1: 46, x2: 2, y2: 46,
  54987. stop: [{
  54988. offset: 0.1,
  54989. class: 'stop1'
  54990. }, {
  54991. offset: 1,
  54992. class: 'stop2'
  54993. }]
  54994. }]
  54995. }],
  54996. g: [{
  54997. sw: 4,
  54998. lc: ROUND,
  54999. f: NONE,
  55000. path: [{
  55001. stroke: 'url(#sGD)',
  55002. d: 'M4,32 c0,15,12,28,28,28c8,0,16-4,21-9'
  55003. }, {
  55004. d: 'M60,32 C60,16,47.464,4,32,4S4,16,4,32'
  55005. }],
  55006. at: [SPIN_ANIMATION]
  55007. }]
  55008. }
  55009. };
  55010. var animations = {
  55011. android: function(ele) {
  55012. // Note that this is called as a function, not a constructor.
  55013. var self = {};
  55014. this.stop = false;
  55015. var rIndex = 0;
  55016. var rotateCircle = 0;
  55017. var startTime;
  55018. var svgEle = ele.querySelector('g');
  55019. var circleEle = ele.querySelector('circle');
  55020. function run() {
  55021. if (self.stop) return;
  55022. var v = easeInOutCubic(Date.now() - startTime, 650);
  55023. var scaleX = 1;
  55024. var translateX = 0;
  55025. var dasharray = (188 - (58 * v));
  55026. var dashoffset = (182 - (182 * v));
  55027. if (rIndex % 2) {
  55028. scaleX = -1;
  55029. translateX = -64;
  55030. dasharray = (128 - (-58 * v));
  55031. dashoffset = (182 * v);
  55032. }
  55033. var rotateLine = [0, -101, -90, -11, -180, 79, -270, -191][rIndex];
  55034. setSvgAttribute(circleEle, 'da', Math.max(Math.min(dasharray, 188), 128));
  55035. setSvgAttribute(circleEle, 'os', Math.max(Math.min(dashoffset, 182), 0));
  55036. setSvgAttribute(circleEle, 't', 'scale(' + scaleX + ',1) translate(' + translateX + ',0) rotate(' + rotateLine + ',32,32)');
  55037. rotateCircle += 4.1;
  55038. if (rotateCircle > 359) rotateCircle = 0;
  55039. setSvgAttribute(svgEle, 't', 'rotate(' + rotateCircle + ',32,32)');
  55040. if (v >= 1) {
  55041. rIndex++;
  55042. if (rIndex > 7) rIndex = 0;
  55043. startTime = Date.now();
  55044. }
  55045. ionic.requestAnimationFrame(run);
  55046. }
  55047. return function() {
  55048. startTime = Date.now();
  55049. run();
  55050. return self;
  55051. };
  55052. }
  55053. };
  55054. function easeInOutCubic(t, c) {
  55055. t /= c / 2;
  55056. if (t < 1) return 1 / 2 * t * t * t;
  55057. t -= 2;
  55058. return 1 / 2 * (t * t * t + 2);
  55059. }
  55060. IonicModule
  55061. .controller('$ionicSpinner', [
  55062. '$element',
  55063. '$attrs',
  55064. '$ionicConfig',
  55065. function($element, $attrs, $ionicConfig) {
  55066. var spinnerName, anim;
  55067. this.init = function() {
  55068. spinnerName = $attrs.icon || $ionicConfig.spinner.icon();
  55069. var container = document.createElement('div');
  55070. createSvgElement('svg', {
  55071. viewBox: '0 0 64 64',
  55072. g: [spinners[spinnerName]]
  55073. }, container, spinnerName);
  55074. // Specifically for animations to work,
  55075. // Android 4.3 and below requires the element to be
  55076. // added as an html string, rather than dynmically
  55077. // building up the svg element and appending it.
  55078. $element.html(container.innerHTML);
  55079. this.start();
  55080. return spinnerName;
  55081. };
  55082. this.start = function() {
  55083. animations[spinnerName] && (anim = animations[spinnerName]($element[0])());
  55084. };
  55085. this.stop = function() {
  55086. animations[spinnerName] && (anim.stop = true);
  55087. };
  55088. }]);
  55089. })(ionic);
  55090. IonicModule
  55091. .controller('$ionicTab', [
  55092. '$scope',
  55093. '$ionicHistory',
  55094. '$attrs',
  55095. '$location',
  55096. '$state',
  55097. function($scope, $ionicHistory, $attrs, $location, $state) {
  55098. this.$scope = $scope;
  55099. //All of these exposed for testing
  55100. this.hrefMatchesState = function() {
  55101. return $attrs.href && $location.path().indexOf(
  55102. $attrs.href.replace(/^#/, '').replace(/\/$/, '')
  55103. ) === 0;
  55104. };
  55105. this.srefMatchesState = function() {
  55106. return $attrs.uiSref && $state.includes($attrs.uiSref.split('(')[0]);
  55107. };
  55108. this.navNameMatchesState = function() {
  55109. return this.navViewName && $ionicHistory.isCurrentStateNavView(this.navViewName);
  55110. };
  55111. this.tabMatchesState = function() {
  55112. return this.hrefMatchesState() || this.srefMatchesState() || this.navNameMatchesState();
  55113. };
  55114. }]);
  55115. IonicModule
  55116. .controller('$ionicTabs', [
  55117. '$scope',
  55118. '$element',
  55119. '$ionicHistory',
  55120. function($scope, $element, $ionicHistory) {
  55121. var self = this;
  55122. var selectedTab = null;
  55123. var previousSelectedTab = null;
  55124. var selectedTabIndex;
  55125. var isVisible = true;
  55126. self.tabs = [];
  55127. self.selectedIndex = function() {
  55128. return self.tabs.indexOf(selectedTab);
  55129. };
  55130. self.selectedTab = function() {
  55131. return selectedTab;
  55132. };
  55133. self.previousSelectedTab = function() {
  55134. return previousSelectedTab;
  55135. };
  55136. self.add = function(tab) {
  55137. $ionicHistory.registerHistory(tab);
  55138. self.tabs.push(tab);
  55139. };
  55140. self.remove = function(tab) {
  55141. var tabIndex = self.tabs.indexOf(tab);
  55142. if (tabIndex === -1) {
  55143. return;
  55144. }
  55145. //Use a field like '$tabSelected' so developers won't accidentally set it in controllers etc
  55146. if (tab.$tabSelected) {
  55147. self.deselect(tab);
  55148. //Try to select a new tab if we're removing a tab
  55149. if (self.tabs.length === 1) {
  55150. //Do nothing if there are no other tabs to select
  55151. } else {
  55152. //Select previous tab if it's the last tab, else select next tab
  55153. var newTabIndex = tabIndex === self.tabs.length - 1 ? tabIndex - 1 : tabIndex + 1;
  55154. self.select(self.tabs[newTabIndex]);
  55155. }
  55156. }
  55157. self.tabs.splice(tabIndex, 1);
  55158. };
  55159. self.deselect = function(tab) {
  55160. if (tab.$tabSelected) {
  55161. previousSelectedTab = selectedTab;
  55162. selectedTab = selectedTabIndex = null;
  55163. tab.$tabSelected = false;
  55164. (tab.onDeselect || noop)();
  55165. tab.$broadcast && tab.$broadcast('$ionicHistory.deselect');
  55166. }
  55167. };
  55168. self.select = function(tab, shouldEmitEvent) {
  55169. var tabIndex;
  55170. if (isNumber(tab)) {
  55171. tabIndex = tab;
  55172. if (tabIndex >= self.tabs.length) return;
  55173. tab = self.tabs[tabIndex];
  55174. } else {
  55175. tabIndex = self.tabs.indexOf(tab);
  55176. }
  55177. if (arguments.length === 1) {
  55178. shouldEmitEvent = !!(tab.navViewName || tab.uiSref);
  55179. }
  55180. if (selectedTab && selectedTab.$historyId == tab.$historyId) {
  55181. if (shouldEmitEvent) {
  55182. $ionicHistory.goToHistoryRoot(tab.$historyId);
  55183. }
  55184. } else if (selectedTabIndex !== tabIndex) {
  55185. forEach(self.tabs, function(tab) {
  55186. self.deselect(tab);
  55187. });
  55188. selectedTab = tab;
  55189. selectedTabIndex = tabIndex;
  55190. if (self.$scope && self.$scope.$parent) {
  55191. self.$scope.$parent.$activeHistoryId = tab.$historyId;
  55192. }
  55193. //Use a funny name like $tabSelected so the developer doesn't overwrite the var in a child scope
  55194. tab.$tabSelected = true;
  55195. (tab.onSelect || noop)();
  55196. if (shouldEmitEvent) {
  55197. $scope.$emit('$ionicHistory.change', {
  55198. type: 'tab',
  55199. tabIndex: tabIndex,
  55200. historyId: tab.$historyId,
  55201. navViewName: tab.navViewName,
  55202. hasNavView: !!tab.navViewName,
  55203. title: tab.title,
  55204. url: tab.href,
  55205. uiSref: tab.uiSref
  55206. });
  55207. }
  55208. $scope.$broadcast("tabSelected", { selectedTab: tab, selectedTabIndex: tabIndex});
  55209. }
  55210. };
  55211. self.hasActiveScope = function() {
  55212. for (var x = 0; x < self.tabs.length; x++) {
  55213. if ($ionicHistory.isActiveScope(self.tabs[x])) {
  55214. return true;
  55215. }
  55216. }
  55217. return false;
  55218. };
  55219. self.showBar = function(show) {
  55220. if (arguments.length) {
  55221. if (show) {
  55222. $element.removeClass('tabs-item-hide');
  55223. } else {
  55224. $element.addClass('tabs-item-hide');
  55225. }
  55226. isVisible = !!show;
  55227. }
  55228. return isVisible;
  55229. };
  55230. }]);
  55231. IonicModule
  55232. .controller('$ionicView', [
  55233. '$scope',
  55234. '$element',
  55235. '$attrs',
  55236. '$compile',
  55237. '$rootScope',
  55238. function($scope, $element, $attrs, $compile, $rootScope) {
  55239. var self = this;
  55240. var navElementHtml = {};
  55241. var navViewCtrl;
  55242. var navBarDelegateHandle;
  55243. var hasViewHeaderBar;
  55244. var deregisters = [];
  55245. var viewTitle;
  55246. var deregIonNavBarInit = $scope.$on('ionNavBar.init', function(ev, delegateHandle) {
  55247. // this view has its own ion-nav-bar, remember the navBarDelegateHandle for this view
  55248. ev.stopPropagation();
  55249. navBarDelegateHandle = delegateHandle;
  55250. });
  55251. self.init = function() {
  55252. deregIonNavBarInit();
  55253. var modalCtrl = $element.inheritedData('$ionModalController');
  55254. navViewCtrl = $element.inheritedData('$ionNavViewController');
  55255. // don't bother if inside a modal or there's no parent navView
  55256. if (!navViewCtrl || modalCtrl) return;
  55257. // add listeners for when this view changes
  55258. $scope.$on('$ionicView.beforeEnter', self.beforeEnter);
  55259. $scope.$on('$ionicView.afterEnter', afterEnter);
  55260. $scope.$on('$ionicView.beforeLeave', deregisterFns);
  55261. };
  55262. self.beforeEnter = function(ev, transData) {
  55263. // this event was emitted, starting at intial ion-view, then bubbles up
  55264. // only the first ion-view should do something with it, parent ion-views should ignore
  55265. if (transData && !transData.viewNotified) {
  55266. transData.viewNotified = true;
  55267. if (!$rootScope.$$phase) $scope.$digest();
  55268. viewTitle = isDefined($attrs.viewTitle) ? $attrs.viewTitle : $attrs.title;
  55269. var navBarItems = {};
  55270. for (var n in navElementHtml) {
  55271. navBarItems[n] = generateNavBarItem(navElementHtml[n]);
  55272. }
  55273. navViewCtrl.beforeEnter(extend(transData, {
  55274. title: viewTitle,
  55275. showBack: !attrTrue('hideBackButton'),
  55276. navBarItems: navBarItems,
  55277. navBarDelegate: navBarDelegateHandle || null,
  55278. showNavBar: !attrTrue('hideNavBar'),
  55279. hasHeaderBar: !!hasViewHeaderBar
  55280. }));
  55281. // make sure any existing observers are cleaned up
  55282. deregisterFns();
  55283. }
  55284. };
  55285. function afterEnter() {
  55286. // only listen for title updates after it has entered
  55287. // but also deregister the observe before it leaves
  55288. var viewTitleAttr = isDefined($attrs.viewTitle) && 'viewTitle' || isDefined($attrs.title) && 'title';
  55289. if (viewTitleAttr) {
  55290. titleUpdate($attrs[viewTitleAttr]);
  55291. deregisters.push($attrs.$observe(viewTitleAttr, titleUpdate));
  55292. }
  55293. if (isDefined($attrs.hideBackButton)) {
  55294. deregisters.push($scope.$watch($attrs.hideBackButton, function(val) {
  55295. navViewCtrl.showBackButton(!val);
  55296. }));
  55297. }
  55298. if (isDefined($attrs.hideNavBar)) {
  55299. deregisters.push($scope.$watch($attrs.hideNavBar, function(val) {
  55300. navViewCtrl.showBar(!val);
  55301. }));
  55302. }
  55303. }
  55304. function titleUpdate(newTitle) {
  55305. if (isDefined(newTitle) && newTitle !== viewTitle) {
  55306. viewTitle = newTitle;
  55307. navViewCtrl.title(viewTitle);
  55308. }
  55309. }
  55310. function deregisterFns() {
  55311. // remove all existing $attrs.$observe's
  55312. for (var x = 0; x < deregisters.length; x++) {
  55313. deregisters[x]();
  55314. }
  55315. deregisters = [];
  55316. }
  55317. function generateNavBarItem(html) {
  55318. if (html) {
  55319. // every time a view enters we need to recreate its view buttons if they exist
  55320. return $compile(html)($scope.$new());
  55321. }
  55322. }
  55323. function attrTrue(key) {
  55324. return !!$scope.$eval($attrs[key]);
  55325. }
  55326. self.navElement = function(type, html) {
  55327. navElementHtml[type] = html;
  55328. };
  55329. }]);
  55330. /*
  55331. * We don't document the ionActionSheet directive, we instead document
  55332. * the $ionicActionSheet service
  55333. */
  55334. IonicModule
  55335. .directive('ionActionSheet', ['$document', function($document) {
  55336. return {
  55337. restrict: 'E',
  55338. scope: true,
  55339. replace: true,
  55340. link: function($scope, $element) {
  55341. var keyUp = function(e) {
  55342. if (e.which == 27) {
  55343. $scope.cancel();
  55344. $scope.$apply();
  55345. }
  55346. };
  55347. var backdropClick = function(e) {
  55348. if (e.target == $element[0]) {
  55349. $scope.cancel();
  55350. $scope.$apply();
  55351. }
  55352. };
  55353. $scope.$on('$destroy', function() {
  55354. $element.remove();
  55355. $document.unbind('keyup', keyUp);
  55356. });
  55357. $document.bind('keyup', keyUp);
  55358. $element.bind('click', backdropClick);
  55359. },
  55360. template: '<div class="action-sheet-backdrop">' +
  55361. '<div class="action-sheet-wrapper">' +
  55362. '<div class="action-sheet" ng-class="{\'action-sheet-has-icons\': $actionSheetHasIcon}">' +
  55363. '<div class="action-sheet-group action-sheet-options">' +
  55364. '<div class="action-sheet-title" ng-if="titleText" ng-bind-html="titleText"></div>' +
  55365. '<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>' +
  55366. '<button class="button destructive action-sheet-destructive" ng-if="destructiveText" ng-click="destructiveButtonClicked()" ng-bind-html="destructiveText"></button>' +
  55367. '</div>' +
  55368. '<div class="action-sheet-group action-sheet-cancel" ng-if="cancelText">' +
  55369. '<button class="button" ng-click="cancel()" ng-bind-html="cancelText"></button>' +
  55370. '</div>' +
  55371. '</div>' +
  55372. '</div>' +
  55373. '</div>'
  55374. };
  55375. }]);
  55376. /**
  55377. * @ngdoc directive
  55378. * @name ionCheckbox
  55379. * @module ionic
  55380. * @restrict E
  55381. * @codepen hqcju
  55382. * @description
  55383. * The checkbox is no different than the HTML checkbox input, except it's styled differently.
  55384. *
  55385. * The checkbox behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]).
  55386. *
  55387. * @usage
  55388. * ```html
  55389. * <ion-checkbox ng-model="isChecked">Checkbox Label</ion-checkbox>
  55390. * ```
  55391. */
  55392. IonicModule
  55393. .directive('ionCheckbox', ['$ionicConfig', function($ionicConfig) {
  55394. return {
  55395. restrict: 'E',
  55396. replace: true,
  55397. require: '?ngModel',
  55398. transclude: true,
  55399. template:
  55400. '<label class="item item-checkbox">' +
  55401. '<div class="checkbox checkbox-input-hidden disable-pointer-events">' +
  55402. '<input type="checkbox">' +
  55403. '<i class="checkbox-icon"></i>' +
  55404. '</div>' +
  55405. '<div class="item-content disable-pointer-events" ng-transclude></div>' +
  55406. '</label>',
  55407. compile: function(element, attr) {
  55408. var input = element.find('input');
  55409. forEach({
  55410. 'name': attr.name,
  55411. 'ng-value': attr.ngValue,
  55412. 'ng-model': attr.ngModel,
  55413. 'ng-checked': attr.ngChecked,
  55414. 'ng-disabled': attr.ngDisabled,
  55415. 'ng-true-value': attr.ngTrueValue,
  55416. 'ng-false-value': attr.ngFalseValue,
  55417. 'ng-change': attr.ngChange,
  55418. 'ng-required': attr.ngRequired,
  55419. 'required': attr.required
  55420. }, function(value, name) {
  55421. if (isDefined(value)) {
  55422. input.attr(name, value);
  55423. }
  55424. });
  55425. var checkboxWrapper = element[0].querySelector('.checkbox');
  55426. checkboxWrapper.classList.add('checkbox-' + $ionicConfig.form.checkbox());
  55427. }
  55428. };
  55429. }]);
  55430. /**
  55431. * @ngdoc directive
  55432. * @restrict A
  55433. * @name collectionRepeat
  55434. * @module ionic
  55435. * @codepen 7ec1ec58f2489ab8f359fa1a0fe89c15
  55436. * @description
  55437. * `collection-repeat` allows an app to show huge lists of items much more performantly than
  55438. * `ng-repeat`.
  55439. *
  55440. * It renders into the DOM only as many items as are currently visible.
  55441. *
  55442. * This means that on a phone screen that can fit eight items, only the eight items matching
  55443. * the current scroll position will be rendered.
  55444. *
  55445. * **The Basics**:
  55446. *
  55447. * - The data given to collection-repeat must be an array.
  55448. * - If the `item-height` and `item-width` attributes are not supplied, it will be assumed that
  55449. * every item in the list has the same dimensions as the first item.
  55450. * - Don't use angular one-time binding (`::`) with collection-repeat. The scope of each item is
  55451. * assigned new data and re-digested as you scroll. Bindings need to update, and one-time bindings
  55452. * won't.
  55453. *
  55454. * **Performance Tips**:
  55455. *
  55456. * - The iOS webview has a performance bottleneck when switching out `<img src>` attributes.
  55457. * To increase performance of images on iOS, cache your images in advance and,
  55458. * if possible, lower the number of unique images. We're working on [a solution](https://github.com/ionic-team/ionic/issues/3194).
  55459. *
  55460. * @usage
  55461. * #### Basic Item List ([codepen](http://codepen.io/ionic/pen/0c2c35a34a8b18ad4d793fef0b081693))
  55462. * ```html
  55463. * <ion-content>
  55464. * <ion-item collection-repeat="item in items">
  55465. * {% raw %}{{item}}{% endraw %}
  55466. * </ion-item>
  55467. * </ion-content>
  55468. * ```
  55469. *
  55470. * #### Grid of Images ([codepen](http://codepen.io/ionic/pen/5515d4efd9d66f780e96787387f41664))
  55471. * ```html
  55472. * <ion-content>
  55473. * <img collection-repeat="photo in photos"
  55474. * item-width="33%"
  55475. * item-height="200px"
  55476. * ng-src="{% raw %}{{photo.url}}{% endraw %}">
  55477. * </ion-content>
  55478. * ```
  55479. *
  55480. * #### Horizontal Scroller, Dynamic Item Width ([codepen](http://codepen.io/ionic/pen/67cc56b349124a349acb57a0740e030e))
  55481. * ```html
  55482. * <ion-content>
  55483. * <h2>Available Kittens:</h2>
  55484. * <ion-scroll direction="x" class="available-scroller">
  55485. * <div class="photo" collection-repeat="photo in main.photos"
  55486. * item-height="250" item-width="photo.width + 30">
  55487. * <img ng-src="{% raw %}{{photo.src}}{% endraw %}">
  55488. * </div>
  55489. * </ion-scroll>
  55490. * </ion-content>
  55491. * ```
  55492. *
  55493. * @param {expression} collection-repeat The expression indicating how to enumerate a collection,
  55494. * of the format `variable in expression` – where variable is the user defined loop variable
  55495. * and `expression` is a scope expression giving the collection to enumerate.
  55496. * For example: `album in artist.albums` or `album in artist.albums | orderBy:'name'`.
  55497. * @param {expression=} item-width The width of the repeated element. The expression must return
  55498. * a number (pixels) or a percentage. Defaults to the width of the first item in the list.
  55499. * (previously named collection-item-width)
  55500. * @param {expression=} item-height The height of the repeated element. The expression must return
  55501. * a number (pixels) or a percentage. Defaults to the height of the first item in the list.
  55502. * (previously named collection-item-height)
  55503. * @param {number=} item-render-buffer The number of items to load before and after the visible
  55504. * items in the list. Default 3. Tip: set this higher if you have lots of images to preload, but
  55505. * don't set it too high or you'll see performance loss.
  55506. * @param {boolean=} force-refresh-images Force images to refresh as you scroll. This fixes a problem
  55507. * where, when an element is interchanged as scrolling, its image will still have the old src
  55508. * while the new src loads. Setting this to true comes with a small performance loss.
  55509. */
  55510. IonicModule
  55511. .directive('collectionRepeat', CollectionRepeatDirective)
  55512. .factory('$ionicCollectionManager', RepeatManagerFactory);
  55513. var ONE_PX_TRANSPARENT_IMG_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
  55514. var WIDTH_HEIGHT_REGEX = /height:.*?px;\s*width:.*?px/;
  55515. var DEFAULT_RENDER_BUFFER = 3;
  55516. CollectionRepeatDirective.$inject = ['$ionicCollectionManager', '$parse', '$window', '$$rAF', '$rootScope', '$timeout'];
  55517. function CollectionRepeatDirective($ionicCollectionManager, $parse, $window, $$rAF, $rootScope, $timeout) {
  55518. return {
  55519. restrict: 'A',
  55520. priority: 1000,
  55521. transclude: 'element',
  55522. $$tlb: true,
  55523. require: '^^$ionicScroll',
  55524. link: postLink
  55525. };
  55526. function postLink(scope, element, attr, scrollCtrl, transclude) {
  55527. var scrollView = scrollCtrl.scrollView;
  55528. var node = element[0];
  55529. var containerNode = angular.element('<div class="collection-repeat-container">')[0];
  55530. node.parentNode.replaceChild(containerNode, node);
  55531. if (scrollView.options.scrollingX && scrollView.options.scrollingY) {
  55532. throw new Error("collection-repeat expected a parent x or y scrollView, not " +
  55533. "an xy scrollView.");
  55534. }
  55535. var repeatExpr = attr.collectionRepeat;
  55536. var match = repeatExpr.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  55537. if (!match) {
  55538. throw new Error("collection-repeat expected expression in form of '_item_ in " +
  55539. "_collection_[ track by _id_]' but got '" + attr.collectionRepeat + "'.");
  55540. }
  55541. var keyExpr = match[1];
  55542. var listExpr = match[2];
  55543. var listGetter = $parse(listExpr);
  55544. var heightData = {};
  55545. var widthData = {};
  55546. var computedStyleDimensions = {};
  55547. var data = [];
  55548. var repeatManager;
  55549. // attr.collectionBufferSize is deprecated
  55550. var renderBufferExpr = attr.itemRenderBuffer || attr.collectionBufferSize;
  55551. var renderBuffer = angular.isDefined(renderBufferExpr) ?
  55552. parseInt(renderBufferExpr) :
  55553. DEFAULT_RENDER_BUFFER;
  55554. // attr.collectionItemHeight is deprecated
  55555. var heightExpr = attr.itemHeight || attr.collectionItemHeight;
  55556. // attr.collectionItemWidth is deprecated
  55557. var widthExpr = attr.itemWidth || attr.collectionItemWidth;
  55558. var afterItemsContainer = initAfterItemsContainer();
  55559. var changeValidator = makeChangeValidator();
  55560. initDimensions();
  55561. // Dimensions are refreshed on resize or data change.
  55562. scrollCtrl.$element.on('scroll-resize', refreshDimensions);
  55563. angular.element($window).on('resize', onResize);
  55564. var unlistenToExposeAside = $rootScope.$on('$ionicExposeAside', ionic.animationFrameThrottle(function() {
  55565. scrollCtrl.scrollView.resize();
  55566. onResize();
  55567. }));
  55568. $timeout(refreshDimensions, 0, false);
  55569. function onResize() {
  55570. if (changeValidator.resizeRequiresRefresh(scrollView.__clientWidth, scrollView.__clientHeight)) {
  55571. refreshDimensions();
  55572. }
  55573. }
  55574. scope.$watchCollection(listGetter, function(newValue) {
  55575. data = newValue || (newValue = []);
  55576. if (!angular.isArray(newValue)) {
  55577. throw new Error("collection-repeat expected an array for '" + listExpr + "', " +
  55578. "but got a " + typeof value);
  55579. }
  55580. // Wait for this digest to end before refreshing everything.
  55581. scope.$$postDigest(function() {
  55582. getRepeatManager().setData(data);
  55583. if (changeValidator.dataChangeRequiresRefresh(data)) refreshDimensions();
  55584. });
  55585. });
  55586. scope.$on('$destroy', function() {
  55587. angular.element($window).off('resize', onResize);
  55588. unlistenToExposeAside();
  55589. scrollCtrl.$element && scrollCtrl.$element.off('scroll-resize', refreshDimensions);
  55590. computedStyleNode && computedStyleNode.parentNode &&
  55591. computedStyleNode.parentNode.removeChild(computedStyleNode);
  55592. computedStyleScope && computedStyleScope.$destroy();
  55593. computedStyleScope = computedStyleNode = null;
  55594. repeatManager && repeatManager.destroy();
  55595. repeatManager = null;
  55596. });
  55597. function makeChangeValidator() {
  55598. var self;
  55599. return (self = {
  55600. dataLength: 0,
  55601. width: 0,
  55602. height: 0,
  55603. // A resize triggers a refresh only if we have data, the scrollView has size,
  55604. // and the size has changed.
  55605. resizeRequiresRefresh: function(newWidth, newHeight) {
  55606. var requiresRefresh = self.dataLength && newWidth && newHeight &&
  55607. (newWidth !== self.width || newHeight !== self.height);
  55608. self.width = newWidth;
  55609. self.height = newHeight;
  55610. return !!requiresRefresh;
  55611. },
  55612. // A change in data only triggers a refresh if the data has length, or if the data's
  55613. // length is less than before.
  55614. dataChangeRequiresRefresh: function(newData) {
  55615. var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;
  55616. self.dataLength = newData.length;
  55617. return !!requiresRefresh;
  55618. }
  55619. });
  55620. }
  55621. function getRepeatManager() {
  55622. return repeatManager || (repeatManager = new $ionicCollectionManager({
  55623. afterItemsNode: afterItemsContainer[0],
  55624. containerNode: containerNode,
  55625. heightData: heightData,
  55626. widthData: widthData,
  55627. forceRefreshImages: !!(isDefined(attr.forceRefreshImages) && attr.forceRefreshImages !== 'false'),
  55628. keyExpression: keyExpr,
  55629. renderBuffer: renderBuffer,
  55630. scope: scope,
  55631. scrollView: scrollCtrl.scrollView,
  55632. transclude: transclude
  55633. }));
  55634. }
  55635. function initAfterItemsContainer() {
  55636. var container = angular.element(
  55637. scrollView.__content.querySelector('.collection-repeat-after-container')
  55638. );
  55639. // Put everything in the view after the repeater into a container.
  55640. if (!container.length) {
  55641. var elementIsAfterRepeater = false;
  55642. var afterNodes = [].filter.call(scrollView.__content.childNodes, function(node) {
  55643. if (ionic.DomUtil.contains(node, containerNode)) {
  55644. elementIsAfterRepeater = true;
  55645. return false;
  55646. }
  55647. return elementIsAfterRepeater;
  55648. });
  55649. container = angular.element('<span class="collection-repeat-after-container">');
  55650. if (scrollView.options.scrollingX) {
  55651. container.addClass('horizontal');
  55652. }
  55653. container.append(afterNodes);
  55654. scrollView.__content.appendChild(container[0]);
  55655. }
  55656. return container;
  55657. }
  55658. function initDimensions() {
  55659. //Height and width have four 'modes':
  55660. //1) Computed Mode
  55661. // - Nothing is supplied, so we getComputedStyle() on one element in the list and use
  55662. // that width and height value for the width and height of every item. This is re-computed
  55663. // every resize.
  55664. //2) Constant Mode, Static Integer
  55665. // - The user provides a constant number for width or height, in pixels. We parse it,
  55666. // store it on the `value` field, and it never changes
  55667. //3) Constant Mode, Percent
  55668. // - The user provides a percent string for width or height. The getter for percent is
  55669. // stored on the `getValue()` field, and is re-evaluated once every resize. The result
  55670. // is stored on the `value` field.
  55671. //4) Dynamic Mode
  55672. // - The user provides a dynamic expression for the width or height. This is re-evaluated
  55673. // for every item, stored on the `.getValue()` field.
  55674. if (heightExpr) {
  55675. parseDimensionAttr(heightExpr, heightData);
  55676. } else {
  55677. heightData.computed = true;
  55678. }
  55679. if (widthExpr) {
  55680. parseDimensionAttr(widthExpr, widthData);
  55681. } else {
  55682. widthData.computed = true;
  55683. }
  55684. }
  55685. function refreshDimensions() {
  55686. var hasData = data.length > 0;
  55687. if (hasData && (heightData.computed || widthData.computed)) {
  55688. computeStyleDimensions();
  55689. }
  55690. if (hasData && heightData.computed) {
  55691. heightData.value = computedStyleDimensions.height;
  55692. if (!heightData.value) {
  55693. throw new Error('collection-repeat tried to compute the height of repeated elements "' +
  55694. repeatExpr + '", but was unable to. Please provide the "item-height" attribute. ' +
  55695. 'http://ionicframework.com/docs/api/directive/collectionRepeat/');
  55696. }
  55697. } else if (!heightData.dynamic && heightData.getValue) {
  55698. // If it's a constant with a getter (eg percent), we just refresh .value after resize
  55699. heightData.value = heightData.getValue();
  55700. }
  55701. if (hasData && widthData.computed) {
  55702. widthData.value = computedStyleDimensions.width;
  55703. if (!widthData.value) {
  55704. throw new Error('collection-repeat tried to compute the width of repeated elements "' +
  55705. repeatExpr + '", but was unable to. Please provide the "item-width" attribute. ' +
  55706. 'http://ionicframework.com/docs/api/directive/collectionRepeat/');
  55707. }
  55708. } else if (!widthData.dynamic && widthData.getValue) {
  55709. // If it's a constant with a getter (eg percent), we just refresh .value after resize
  55710. widthData.value = widthData.getValue();
  55711. }
  55712. // Dynamic dimensions aren't updated on resize. Since they're already dynamic anyway,
  55713. // .getValue() will be used.
  55714. getRepeatManager().refreshLayout();
  55715. }
  55716. function parseDimensionAttr(attrValue, dimensionData) {
  55717. if (!attrValue) return;
  55718. var parsedValue;
  55719. // Try to just parse the plain attr value
  55720. try {
  55721. parsedValue = $parse(attrValue);
  55722. } catch (e) {
  55723. // If the parse fails and the value has `px` or `%` in it, surround the attr in
  55724. // quotes, to attempt to let the user provide a simple `attr="100%"` or `attr="100px"`
  55725. if (attrValue.trim().match(/\d+(px|%)$/)) {
  55726. attrValue = '"' + attrValue + '"';
  55727. }
  55728. parsedValue = $parse(attrValue);
  55729. }
  55730. var constantAttrValue = attrValue.replace(/(\'|\"|px|%)/g, '').trim();
  55731. var isConstant = constantAttrValue.length && !/([a-zA-Z]|\$|:|\?)/.test(constantAttrValue);
  55732. dimensionData.attrValue = attrValue;
  55733. // If it's a constant, it's either a percent or just a constant pixel number.
  55734. if (isConstant) {
  55735. // For percents, store the percent getter on .getValue()
  55736. if (attrValue.indexOf('%') > -1) {
  55737. var decimalValue = parseFloat(parsedValue()) / 100;
  55738. dimensionData.getValue = dimensionData === heightData ?
  55739. function() { return Math.floor(decimalValue * scrollView.__clientHeight); } :
  55740. function() { return Math.floor(decimalValue * scrollView.__clientWidth); };
  55741. } else {
  55742. // For static constants, just store the static constant.
  55743. dimensionData.value = parseInt(parsedValue());
  55744. }
  55745. } else {
  55746. dimensionData.dynamic = true;
  55747. dimensionData.getValue = dimensionData === heightData ?
  55748. function heightGetter(scope, locals) {
  55749. var result = parsedValue(scope, locals);
  55750. if (result.charAt && result.charAt(result.length - 1) === '%') {
  55751. return Math.floor(parseFloat(result) / 100 * scrollView.__clientHeight);
  55752. }
  55753. return parseInt(result);
  55754. } :
  55755. function widthGetter(scope, locals) {
  55756. var result = parsedValue(scope, locals);
  55757. if (result.charAt && result.charAt(result.length - 1) === '%') {
  55758. return Math.floor(parseFloat(result) / 100 * scrollView.__clientWidth);
  55759. }
  55760. return parseInt(result);
  55761. };
  55762. }
  55763. }
  55764. var computedStyleNode;
  55765. var computedStyleScope;
  55766. function computeStyleDimensions() {
  55767. if (!computedStyleNode) {
  55768. transclude(computedStyleScope = scope.$new(), function(clone) {
  55769. clone[0].removeAttribute('collection-repeat'); // remove absolute position styling
  55770. computedStyleNode = clone[0];
  55771. });
  55772. }
  55773. computedStyleScope[keyExpr] = (listGetter(scope) || [])[0];
  55774. if (!$rootScope.$$phase) computedStyleScope.$digest();
  55775. containerNode.appendChild(computedStyleNode);
  55776. var style = $window.getComputedStyle(computedStyleNode);
  55777. computedStyleDimensions.width = parseInt(style.width);
  55778. computedStyleDimensions.height = parseInt(style.height);
  55779. containerNode.removeChild(computedStyleNode);
  55780. }
  55781. }
  55782. }
  55783. RepeatManagerFactory.$inject = ['$rootScope', '$window', '$$rAF'];
  55784. function RepeatManagerFactory($rootScope, $window, $$rAF) {
  55785. var EMPTY_DIMENSION = { primaryPos: 0, secondaryPos: 0, primarySize: 0, secondarySize: 0, rowPrimarySize: 0 };
  55786. return function RepeatController(options) {
  55787. var afterItemsNode = options.afterItemsNode;
  55788. var containerNode = options.containerNode;
  55789. var forceRefreshImages = options.forceRefreshImages;
  55790. var heightData = options.heightData;
  55791. var widthData = options.widthData;
  55792. var keyExpression = options.keyExpression;
  55793. var renderBuffer = options.renderBuffer;
  55794. var scope = options.scope;
  55795. var scrollView = options.scrollView;
  55796. var transclude = options.transclude;
  55797. var data = [];
  55798. var getterLocals = {};
  55799. var heightFn = heightData.getValue || function() { return heightData.value; };
  55800. var heightGetter = function(index, value) {
  55801. getterLocals[keyExpression] = value;
  55802. getterLocals.$index = index;
  55803. return heightFn(scope, getterLocals);
  55804. };
  55805. var widthFn = widthData.getValue || function() { return widthData.value; };
  55806. var widthGetter = function(index, value) {
  55807. getterLocals[keyExpression] = value;
  55808. getterLocals.$index = index;
  55809. return widthFn(scope, getterLocals);
  55810. };
  55811. var isVertical = !!scrollView.options.scrollingY;
  55812. // We say it's a grid view if we're either dynamic or not 100% width
  55813. var isGridView = isVertical ?
  55814. (widthData.dynamic || widthData.value !== scrollView.__clientWidth) :
  55815. (heightData.dynamic || heightData.value !== scrollView.__clientHeight);
  55816. var isStaticView = !heightData.dynamic && !widthData.dynamic;
  55817. var PRIMARY = 'PRIMARY';
  55818. var SECONDARY = 'SECONDARY';
  55819. var TRANSLATE_TEMPLATE_STR = isVertical ?
  55820. 'translate3d(SECONDARYpx,PRIMARYpx,0)' :
  55821. 'translate3d(PRIMARYpx,SECONDARYpx,0)';
  55822. var WIDTH_HEIGHT_TEMPLATE_STR = isVertical ?
  55823. 'height: PRIMARYpx; width: SECONDARYpx;' :
  55824. 'height: SECONDARYpx; width: PRIMARYpx;';
  55825. var estimatedHeight;
  55826. var estimatedWidth;
  55827. var repeaterBeforeSize = 0;
  55828. var repeaterAfterSize = 0;
  55829. var renderStartIndex = -1;
  55830. var renderEndIndex = -1;
  55831. var renderAfterBoundary = -1;
  55832. var renderBeforeBoundary = -1;
  55833. var itemsPool = [];
  55834. var itemsLeaving = [];
  55835. var itemsEntering = [];
  55836. var itemsShownMap = {};
  55837. var nextItemId = 0;
  55838. var scrollViewSetDimensions = isVertical ?
  55839. function() { scrollView.setDimensions(null, null, null, view.getContentSize(), true); } :
  55840. function() { scrollView.setDimensions(null, null, view.getContentSize(), null, true); };
  55841. // view is a mix of list/grid methods + static/dynamic methods.
  55842. // See bottom for implementations. Available methods:
  55843. //
  55844. // getEstimatedPrimaryPos(i), getEstimatedSecondaryPos(i), getEstimatedIndex(scrollTop),
  55845. // calculateDimensions(toIndex), getDimensions(index),
  55846. // updateRenderRange(scrollTop, scrollValueEnd), onRefreshLayout(), onRefreshData()
  55847. var view = isVertical ? new VerticalViewType() : new HorizontalViewType();
  55848. (isGridView ? GridViewType : ListViewType).call(view);
  55849. (isStaticView ? StaticViewType : DynamicViewType).call(view);
  55850. var contentSizeStr = isVertical ? 'getContentHeight' : 'getContentWidth';
  55851. var originalGetContentSize = scrollView.options[contentSizeStr];
  55852. scrollView.options[contentSizeStr] = angular.bind(view, view.getContentSize);
  55853. scrollView.__$callback = scrollView.__callback;
  55854. scrollView.__callback = function(transformLeft, transformTop, zoom, wasResize) {
  55855. var scrollValue = view.getScrollValue();
  55856. if (renderStartIndex === -1 ||
  55857. scrollValue + view.scrollPrimarySize > renderAfterBoundary ||
  55858. scrollValue < renderBeforeBoundary) {
  55859. render();
  55860. }
  55861. scrollView.__$callback(transformLeft, transformTop, zoom, wasResize);
  55862. };
  55863. var isLayoutReady = false;
  55864. var isDataReady = false;
  55865. this.refreshLayout = function() {
  55866. if (data.length) {
  55867. estimatedHeight = heightGetter(0, data[0]);
  55868. estimatedWidth = widthGetter(0, data[0]);
  55869. } else {
  55870. // If we don't have any data in our array, just guess.
  55871. estimatedHeight = 100;
  55872. estimatedWidth = 100;
  55873. }
  55874. // Get the size of every element AFTER the repeater. We have to get the margin before and
  55875. // after the first/last element to fix a browser bug with getComputedStyle() not counting
  55876. // the first/last child's margins into height.
  55877. var style = getComputedStyle(afterItemsNode) || {};
  55878. var firstStyle = afterItemsNode.firstElementChild && getComputedStyle(afterItemsNode.firstElementChild) || {};
  55879. var lastStyle = afterItemsNode.lastElementChild && getComputedStyle(afterItemsNode.lastElementChild) || {};
  55880. repeaterAfterSize = (parseInt(style[isVertical ? 'height' : 'width']) || 0) +
  55881. (firstStyle && parseInt(firstStyle[isVertical ? 'marginTop' : 'marginLeft']) || 0) +
  55882. (lastStyle && parseInt(lastStyle[isVertical ? 'marginBottom' : 'marginRight']) || 0);
  55883. // Get the offsetTop of the repeater.
  55884. repeaterBeforeSize = 0;
  55885. var current = containerNode;
  55886. do {
  55887. repeaterBeforeSize += current[isVertical ? 'offsetTop' : 'offsetLeft'];
  55888. } while ( ionic.DomUtil.contains(scrollView.__content, current = current.offsetParent) );
  55889. var containerPrevNode = containerNode.previousElementSibling;
  55890. var beforeStyle = containerPrevNode ? $window.getComputedStyle(containerPrevNode) : {};
  55891. var beforeMargin = parseInt(beforeStyle[isVertical ? 'marginBottom' : 'marginRight'] || 0);
  55892. // Because we position the collection container with position: relative, it doesn't take
  55893. // into account where to position itself relative to the previous element's marginBottom.
  55894. // To compensate, we translate the container up by the previous element's margin.
  55895. containerNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  55896. .replace(PRIMARY, -beforeMargin)
  55897. .replace(SECONDARY, 0);
  55898. repeaterBeforeSize -= beforeMargin;
  55899. if (!scrollView.__clientHeight || !scrollView.__clientWidth) {
  55900. scrollView.__clientWidth = scrollView.__container.clientWidth;
  55901. scrollView.__clientHeight = scrollView.__container.clientHeight;
  55902. }
  55903. (view.onRefreshLayout || angular.noop)();
  55904. view.refreshDirection();
  55905. scrollViewSetDimensions();
  55906. // Create the pool of items for reuse, setting the size to (estimatedItemsOnScreen) * 2,
  55907. // plus the size of the renderBuffer.
  55908. if (!isLayoutReady) {
  55909. var poolSize = Math.max(20, renderBuffer * 3);
  55910. for (var i = 0; i < poolSize; i++) {
  55911. itemsPool.push(new RepeatItem());
  55912. }
  55913. }
  55914. isLayoutReady = true;
  55915. if (isLayoutReady && isDataReady) {
  55916. // If the resize or latest data change caused the scrollValue to
  55917. // now be out of bounds, resize the scrollView.
  55918. if (scrollView.__scrollLeft > scrollView.__maxScrollLeft ||
  55919. scrollView.__scrollTop > scrollView.__maxScrollTop) {
  55920. scrollView.resize();
  55921. }
  55922. forceRerender(true);
  55923. }
  55924. };
  55925. this.setData = function(newData) {
  55926. data = newData;
  55927. (view.onRefreshData || angular.noop)();
  55928. isDataReady = true;
  55929. };
  55930. this.destroy = function() {
  55931. render.destroyed = true;
  55932. itemsPool.forEach(function(item) {
  55933. item.scope.$destroy();
  55934. item.scope = item.element = item.node = item.images = null;
  55935. });
  55936. itemsPool.length = itemsEntering.length = itemsLeaving.length = 0;
  55937. itemsShownMap = {};
  55938. //Restore the scrollView's normal behavior and resize it to normal size.
  55939. scrollView.options[contentSizeStr] = originalGetContentSize;
  55940. scrollView.__callback = scrollView.__$callback;
  55941. scrollView.resize();
  55942. (view.onDestroy || angular.noop)();
  55943. };
  55944. function forceRerender() {
  55945. return render(true);
  55946. }
  55947. function render(forceRerender) {
  55948. if (render.destroyed) return;
  55949. var i;
  55950. var ii;
  55951. var item;
  55952. var dim;
  55953. var scope;
  55954. var scrollValue = view.getScrollValue();
  55955. var scrollValueEnd = scrollValue + view.scrollPrimarySize;
  55956. view.updateRenderRange(scrollValue, scrollValueEnd);
  55957. renderStartIndex = Math.max(0, renderStartIndex - renderBuffer);
  55958. renderEndIndex = Math.min(data.length - 1, renderEndIndex + renderBuffer);
  55959. for (i in itemsShownMap) {
  55960. if (i < renderStartIndex || i > renderEndIndex) {
  55961. item = itemsShownMap[i];
  55962. delete itemsShownMap[i];
  55963. itemsLeaving.push(item);
  55964. item.isShown = false;
  55965. }
  55966. }
  55967. // Render indicies that aren't shown yet
  55968. //
  55969. // NOTE(ajoslin): this may sound crazy, but calling any other functions during this render
  55970. // loop will often push the render time over the edge from less than one frame to over
  55971. // one frame, causing visible jank.
  55972. // DON'T call any other functions inside this loop unless it's vital.
  55973. for (i = renderStartIndex; i <= renderEndIndex; i++) {
  55974. // We only go forward with render if the index is in data, the item isn't already shown,
  55975. // or forceRerender is on.
  55976. if (i >= data.length || (itemsShownMap[i] && !forceRerender)) continue;
  55977. item = itemsShownMap[i] || (itemsShownMap[i] = itemsLeaving.length ? itemsLeaving.pop() :
  55978. itemsPool.length ? itemsPool.shift() :
  55979. new RepeatItem());
  55980. itemsEntering.push(item);
  55981. item.isShown = true;
  55982. scope = item.scope;
  55983. scope.$index = i;
  55984. scope[keyExpression] = data[i];
  55985. scope.$first = (i === 0);
  55986. scope.$last = (i === (data.length - 1));
  55987. scope.$middle = !(scope.$first || scope.$last);
  55988. scope.$odd = !(scope.$even = (i & 1) === 0);
  55989. if (scope.$$disconnected) ionic.Utils.reconnectScope(item.scope);
  55990. dim = view.getDimensions(i);
  55991. if (item.secondaryPos !== dim.secondaryPos || item.primaryPos !== dim.primaryPos) {
  55992. item.node.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  55993. .replace(PRIMARY, (item.primaryPos = dim.primaryPos))
  55994. .replace(SECONDARY, (item.secondaryPos = dim.secondaryPos));
  55995. }
  55996. if (item.secondarySize !== dim.secondarySize || item.primarySize !== dim.primarySize) {
  55997. item.node.style.cssText = item.node.style.cssText
  55998. .replace(WIDTH_HEIGHT_REGEX, WIDTH_HEIGHT_TEMPLATE_STR
  55999. //TODO fix item.primarySize + 1 hack
  56000. .replace(PRIMARY, (item.primarySize = dim.primarySize) + 1)
  56001. .replace(SECONDARY, (item.secondarySize = dim.secondarySize))
  56002. );
  56003. }
  56004. }
  56005. // If we reach the end of the list, render the afterItemsNode - this contains all the
  56006. // elements the developer placed after the collection-repeat
  56007. if (renderEndIndex === data.length - 1) {
  56008. dim = view.getDimensions(data.length - 1) || EMPTY_DIMENSION;
  56009. afterItemsNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR
  56010. .replace(PRIMARY, dim.primaryPos + dim.primarySize)
  56011. .replace(SECONDARY, 0);
  56012. }
  56013. while (itemsLeaving.length) {
  56014. item = itemsLeaving.pop();
  56015. item.scope.$broadcast('$collectionRepeatLeave');
  56016. ionic.Utils.disconnectScope(item.scope);
  56017. itemsPool.push(item);
  56018. item.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';
  56019. item.primaryPos = item.secondaryPos = null;
  56020. }
  56021. if (forceRefreshImages) {
  56022. for (i = 0, ii = itemsEntering.length; i < ii && (item = itemsEntering[i]); i++) {
  56023. if (!item.images) continue;
  56024. for (var j = 0, jj = item.images.length, img; j < jj && (img = item.images[j]); j++) {
  56025. var src = img.src;
  56026. img.src = ONE_PX_TRANSPARENT_IMG_SRC;
  56027. img.src = src;
  56028. }
  56029. }
  56030. }
  56031. if (forceRerender) {
  56032. var rootScopePhase = $rootScope.$$phase;
  56033. while (itemsEntering.length) {
  56034. item = itemsEntering.pop();
  56035. if (!rootScopePhase) item.scope.$digest();
  56036. }
  56037. } else {
  56038. digestEnteringItems();
  56039. }
  56040. }
  56041. function digestEnteringItems() {
  56042. var item;
  56043. if (digestEnteringItems.running) return;
  56044. digestEnteringItems.running = true;
  56045. $$rAF(function process() {
  56046. var rootScopePhase = $rootScope.$$phase;
  56047. while (itemsEntering.length) {
  56048. item = itemsEntering.pop();
  56049. if (item.isShown) {
  56050. if (!rootScopePhase) item.scope.$digest();
  56051. }
  56052. }
  56053. digestEnteringItems.running = false;
  56054. });
  56055. }
  56056. function RepeatItem() {
  56057. var self = this;
  56058. this.scope = scope.$new();
  56059. this.id = 'item' + (nextItemId++);
  56060. transclude(this.scope, function(clone) {
  56061. self.element = clone;
  56062. self.element.data('$$collectionRepeatItem', self);
  56063. // TODO destroy
  56064. self.node = clone[0];
  56065. // Batch style setting to lower repaints
  56066. self.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';
  56067. self.node.style.cssText += ' height: 0px; width: 0px;';
  56068. ionic.Utils.disconnectScope(self.scope);
  56069. containerNode.appendChild(self.node);
  56070. self.images = clone[0].getElementsByTagName('img');
  56071. });
  56072. }
  56073. function VerticalViewType() {
  56074. this.getItemPrimarySize = heightGetter;
  56075. this.getItemSecondarySize = widthGetter;
  56076. this.getScrollValue = function() {
  56077. return Math.max(0, Math.min(scrollView.__scrollTop - repeaterBeforeSize,
  56078. scrollView.__maxScrollTop - repeaterBeforeSize - repeaterAfterSize));
  56079. };
  56080. this.refreshDirection = function() {
  56081. this.scrollPrimarySize = scrollView.__clientHeight;
  56082. this.scrollSecondarySize = scrollView.__clientWidth;
  56083. this.estimatedPrimarySize = estimatedHeight;
  56084. this.estimatedSecondarySize = estimatedWidth;
  56085. this.estimatedItemsAcross = isGridView &&
  56086. Math.floor(scrollView.__clientWidth / estimatedWidth) ||
  56087. 1;
  56088. };
  56089. }
  56090. function HorizontalViewType() {
  56091. this.getItemPrimarySize = widthGetter;
  56092. this.getItemSecondarySize = heightGetter;
  56093. this.getScrollValue = function() {
  56094. return Math.max(0, Math.min(scrollView.__scrollLeft - repeaterBeforeSize,
  56095. scrollView.__maxScrollLeft - repeaterBeforeSize - repeaterAfterSize));
  56096. };
  56097. this.refreshDirection = function() {
  56098. this.scrollPrimarySize = scrollView.__clientWidth;
  56099. this.scrollSecondarySize = scrollView.__clientHeight;
  56100. this.estimatedPrimarySize = estimatedWidth;
  56101. this.estimatedSecondarySize = estimatedHeight;
  56102. this.estimatedItemsAcross = isGridView &&
  56103. Math.floor(scrollView.__clientHeight / estimatedHeight) ||
  56104. 1;
  56105. };
  56106. }
  56107. function GridViewType() {
  56108. this.getEstimatedSecondaryPos = function(index) {
  56109. return (index % this.estimatedItemsAcross) * this.estimatedSecondarySize;
  56110. };
  56111. this.getEstimatedPrimaryPos = function(index) {
  56112. return Math.floor(index / this.estimatedItemsAcross) * this.estimatedPrimarySize;
  56113. };
  56114. this.getEstimatedIndex = function(scrollValue) {
  56115. return Math.floor(scrollValue / this.estimatedPrimarySize) *
  56116. this.estimatedItemsAcross;
  56117. };
  56118. }
  56119. function ListViewType() {
  56120. this.getEstimatedSecondaryPos = function() {
  56121. return 0;
  56122. };
  56123. this.getEstimatedPrimaryPos = function(index) {
  56124. return index * this.estimatedPrimarySize;
  56125. };
  56126. this.getEstimatedIndex = function(scrollValue) {
  56127. return Math.floor((scrollValue) / this.estimatedPrimarySize);
  56128. };
  56129. }
  56130. function StaticViewType() {
  56131. this.getContentSize = function() {
  56132. return this.getEstimatedPrimaryPos(data.length - 1) + this.estimatedPrimarySize +
  56133. repeaterBeforeSize + repeaterAfterSize;
  56134. };
  56135. // static view always returns the same object for getDimensions, to avoid memory allocation
  56136. // while scrolling. This could be dangerous if this was a public function, but it's not.
  56137. // Only we use it.
  56138. var dim = {};
  56139. this.getDimensions = function(index) {
  56140. dim.primaryPos = this.getEstimatedPrimaryPos(index);
  56141. dim.secondaryPos = this.getEstimatedSecondaryPos(index);
  56142. dim.primarySize = this.estimatedPrimarySize;
  56143. dim.secondarySize = this.estimatedSecondarySize;
  56144. return dim;
  56145. };
  56146. this.updateRenderRange = function(scrollValue, scrollValueEnd) {
  56147. renderStartIndex = Math.max(0, this.getEstimatedIndex(scrollValue));
  56148. // Make sure the renderEndIndex takes into account all the items on the row
  56149. renderEndIndex = Math.min(data.length - 1,
  56150. this.getEstimatedIndex(scrollValueEnd) + this.estimatedItemsAcross - 1);
  56151. renderBeforeBoundary = Math.max(0,
  56152. this.getEstimatedPrimaryPos(renderStartIndex));
  56153. renderAfterBoundary = this.getEstimatedPrimaryPos(renderEndIndex) +
  56154. this.estimatedPrimarySize;
  56155. };
  56156. }
  56157. function DynamicViewType() {
  56158. var self = this;
  56159. var debouncedScrollViewSetDimensions = ionic.debounce(scrollViewSetDimensions, 25, true);
  56160. var calculateDimensions = isGridView ? calculateDimensionsGrid : calculateDimensionsList;
  56161. var dimensionsIndex;
  56162. var dimensions = [];
  56163. // Get the dimensions at index. {width, height, left, top}.
  56164. // We start with no dimensions calculated, then any time dimensions are asked for at an
  56165. // index we calculate dimensions up to there.
  56166. function calculateDimensionsList(toIndex) {
  56167. var i, prevDimension, dim;
  56168. for (i = Math.max(0, dimensionsIndex); i <= toIndex && (dim = dimensions[i]); i++) {
  56169. prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;
  56170. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56171. dim.secondarySize = self.scrollSecondarySize;
  56172. dim.primaryPos = prevDimension.primaryPos + prevDimension.primarySize;
  56173. dim.secondaryPos = 0;
  56174. }
  56175. }
  56176. function calculateDimensionsGrid(toIndex) {
  56177. var i, prevDimension, dim;
  56178. for (i = Math.max(dimensionsIndex, 0); i <= toIndex && (dim = dimensions[i]); i++) {
  56179. prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;
  56180. dim.secondarySize = Math.min(
  56181. self.getItemSecondarySize(i, data[i]),
  56182. self.scrollSecondarySize
  56183. );
  56184. dim.secondaryPos = prevDimension.secondaryPos + prevDimension.secondarySize;
  56185. if (i === 0 || dim.secondaryPos + dim.secondarySize > self.scrollSecondarySize) {
  56186. dim.secondaryPos = 0;
  56187. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56188. dim.primaryPos = prevDimension.primaryPos + prevDimension.rowPrimarySize;
  56189. dim.rowStartIndex = i;
  56190. dim.rowPrimarySize = dim.primarySize;
  56191. } else {
  56192. dim.primarySize = self.getItemPrimarySize(i, data[i]);
  56193. dim.primaryPos = prevDimension.primaryPos;
  56194. dim.rowStartIndex = prevDimension.rowStartIndex;
  56195. dimensions[dim.rowStartIndex].rowPrimarySize = dim.rowPrimarySize = Math.max(
  56196. dimensions[dim.rowStartIndex].rowPrimarySize,
  56197. dim.primarySize
  56198. );
  56199. dim.rowPrimarySize = Math.max(dim.primarySize, dim.rowPrimarySize);
  56200. }
  56201. }
  56202. }
  56203. this.getContentSize = function() {
  56204. var dim = dimensions[dimensionsIndex] || EMPTY_DIMENSION;
  56205. return ((dim.primaryPos + dim.primarySize) || 0) +
  56206. this.getEstimatedPrimaryPos(data.length - dimensionsIndex - 1) +
  56207. repeaterBeforeSize + repeaterAfterSize;
  56208. };
  56209. this.onDestroy = function() {
  56210. dimensions.length = 0;
  56211. };
  56212. this.onRefreshData = function() {
  56213. var i;
  56214. var ii;
  56215. // Make sure dimensions has as many items as data.length.
  56216. // This is to be sure we don't have to allocate objects while scrolling.
  56217. for (i = dimensions.length, ii = data.length; i < ii; i++) {
  56218. dimensions.push({});
  56219. }
  56220. dimensionsIndex = -1;
  56221. };
  56222. this.onRefreshLayout = function() {
  56223. dimensionsIndex = -1;
  56224. };
  56225. this.getDimensions = function(index) {
  56226. index = Math.min(index, data.length - 1);
  56227. if (dimensionsIndex < index) {
  56228. // Once we start asking for dimensions near the end of the list, go ahead and calculate
  56229. // everything. This is to make sure when the user gets to the end of the list, the
  56230. // scroll height of the list is 100% accurate (not estimated anymore).
  56231. if (index > data.length * 0.9) {
  56232. calculateDimensions(data.length - 1);
  56233. dimensionsIndex = data.length - 1;
  56234. scrollViewSetDimensions();
  56235. } else {
  56236. calculateDimensions(index);
  56237. dimensionsIndex = index;
  56238. debouncedScrollViewSetDimensions();
  56239. }
  56240. }
  56241. return dimensions[index];
  56242. };
  56243. var oldRenderStartIndex = -1;
  56244. var oldScrollValue = -1;
  56245. this.updateRenderRange = function(scrollValue, scrollValueEnd) {
  56246. var i;
  56247. var len;
  56248. var dim;
  56249. // Calculate more dimensions than we estimate we'll need, to be sure.
  56250. this.getDimensions( this.getEstimatedIndex(scrollValueEnd) * 2 );
  56251. // -- Calculate renderStartIndex
  56252. // base case: start at 0
  56253. if (oldRenderStartIndex === -1 || scrollValue === 0) {
  56254. i = 0;
  56255. // scrolling down
  56256. } else if (scrollValue >= oldScrollValue) {
  56257. for (i = oldRenderStartIndex, len = data.length; i < len; i++) {
  56258. if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize >= scrollValue) {
  56259. break;
  56260. }
  56261. }
  56262. // scrolling up
  56263. } else {
  56264. for (i = oldRenderStartIndex; i >= 0; i--) {
  56265. if ((dim = this.getDimensions(i)) && dim.primaryPos <= scrollValue) {
  56266. // when grid view, make sure the render starts at the beginning of a row.
  56267. i = isGridView ? dim.rowStartIndex : i;
  56268. break;
  56269. }
  56270. }
  56271. }
  56272. renderStartIndex = Math.min(Math.max(0, i), data.length - 1);
  56273. renderBeforeBoundary = renderStartIndex !== -1 ? this.getDimensions(renderStartIndex).primaryPos : -1;
  56274. // -- Calculate renderEndIndex
  56275. var lastRowDim;
  56276. for (i = renderStartIndex + 1, len = data.length; i < len; i++) {
  56277. if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize > scrollValueEnd) {
  56278. // Go all the way to the end of the row if we're in a grid
  56279. if (isGridView) {
  56280. lastRowDim = dim;
  56281. while (i < len - 1 &&
  56282. (dim = this.getDimensions(i + 1)).primaryPos === lastRowDim.primaryPos) {
  56283. i++;
  56284. }
  56285. }
  56286. break;
  56287. }
  56288. }
  56289. renderEndIndex = Math.min(i, data.length - 1);
  56290. renderAfterBoundary = renderEndIndex !== -1 ?
  56291. ((dim = this.getDimensions(renderEndIndex)).primaryPos + (dim.rowPrimarySize || dim.primarySize)) :
  56292. -1;
  56293. oldScrollValue = scrollValue;
  56294. oldRenderStartIndex = renderStartIndex;
  56295. };
  56296. }
  56297. };
  56298. }
  56299. /**
  56300. * @ngdoc directive
  56301. * @name ionContent
  56302. * @module ionic
  56303. * @delegate ionic.service:$ionicScrollDelegate
  56304. * @restrict E
  56305. *
  56306. * @description
  56307. * The ionContent directive provides an easy to use content area that can be configured
  56308. * to use Ionic's custom Scroll View, or the built in overflow scrolling of the browser.
  56309. *
  56310. * While we recommend using the custom Scroll features in Ionic in most cases, sometimes
  56311. * (for performance reasons) only the browser's native overflow scrolling will suffice,
  56312. * and so we've made it easy to toggle between the Ionic scroll implementation and
  56313. * overflow scrolling.
  56314. *
  56315. * You can implement pull-to-refresh with the {@link ionic.directive:ionRefresher}
  56316. * directive, and infinite scrolling with the {@link ionic.directive:ionInfiniteScroll}
  56317. * directive.
  56318. *
  56319. * If there is any dynamic content inside the ion-content, be sure to call `.resize()` with {@link ionic.service:$ionicScrollDelegate}
  56320. * after the content has been added.
  56321. *
  56322. * Be aware that this directive gets its own child scope. If you do not understand why this
  56323. * is important, you can read [https://docs.angularjs.org/guide/scope](https://docs.angularjs.org/guide/scope).
  56324. *
  56325. * @param {string=} delegate-handle The handle used to identify this scrollView
  56326. * with {@link ionic.service:$ionicScrollDelegate}.
  56327. * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.
  56328. * @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.
  56329. * @param {boolean=} padding Whether to add padding to the content.
  56330. * Defaults to true on iOS, false on Android.
  56331. * @param {boolean=} scroll Whether to allow scrolling of content. Defaults to true.
  56332. * @param {boolean=} overflow-scroll Whether to use overflow-scrolling instead of
  56333. * Ionic scroll. See {@link ionic.provider:$ionicConfigProvider} to set this as the global default.
  56334. * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.
  56335. * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.
  56336. * @param {string=} start-x Initial horizontal scroll position. Default 0.
  56337. * @param {string=} start-y Initial vertical scroll position. Default 0.
  56338. * @param {expression=} on-scroll Expression to evaluate when the content is scrolled.
  56339. * @param {expression=} on-scroll-complete Expression to evaluate when a scroll action completes. Has access to 'scrollLeft' and 'scrollTop' locals.
  56340. * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges
  56341. * of the content. Defaults to true on iOS, false on Android.
  56342. * @param {number=} scroll-event-interval Number of milliseconds between each firing of the 'on-scroll' expression. Default 10.
  56343. */
  56344. IonicModule
  56345. .directive('ionContent', [
  56346. '$timeout',
  56347. '$controller',
  56348. '$ionicBind',
  56349. '$ionicConfig',
  56350. function($timeout, $controller, $ionicBind, $ionicConfig) {
  56351. return {
  56352. restrict: 'E',
  56353. require: '^?ionNavView',
  56354. scope: true,
  56355. priority: 800,
  56356. compile: function(element, attr) {
  56357. var innerElement;
  56358. var scrollCtrl;
  56359. element.addClass('scroll-content ionic-scroll');
  56360. if (attr.scroll != 'false') {
  56361. //We cannot use normal transclude here because it breaks element.data()
  56362. //inheritance on compile
  56363. innerElement = jqLite('<div class="scroll"></div>');
  56364. innerElement.append(element.contents());
  56365. element.append(innerElement);
  56366. } else {
  56367. element.addClass('scroll-content-false');
  56368. }
  56369. var nativeScrolling = attr.overflowScroll !== "false" && (attr.overflowScroll === "true" || !$ionicConfig.scrolling.jsScrolling());
  56370. // collection-repeat requires JS scrolling
  56371. if (nativeScrolling) {
  56372. nativeScrolling = !element[0].querySelector('[collection-repeat]');
  56373. }
  56374. return { pre: prelink };
  56375. function prelink($scope, $element, $attr) {
  56376. var parentScope = $scope.$parent;
  56377. $scope.$watch(function() {
  56378. return (parentScope.$hasHeader ? ' has-header' : '') +
  56379. (parentScope.$hasSubheader ? ' has-subheader' : '') +
  56380. (parentScope.$hasFooter ? ' has-footer' : '') +
  56381. (parentScope.$hasSubfooter ? ' has-subfooter' : '') +
  56382. (parentScope.$hasTabs ? ' has-tabs' : '') +
  56383. (parentScope.$hasTabsTop ? ' has-tabs-top' : '');
  56384. }, function(className, oldClassName) {
  56385. $element.removeClass(oldClassName);
  56386. $element.addClass(className);
  56387. });
  56388. //Only this ionContent should use these variables from parent scopes
  56389. $scope.$hasHeader = $scope.$hasSubheader =
  56390. $scope.$hasFooter = $scope.$hasSubfooter =
  56391. $scope.$hasTabs = $scope.$hasTabsTop =
  56392. false;
  56393. $ionicBind($scope, $attr, {
  56394. $onScroll: '&onScroll',
  56395. $onScrollComplete: '&onScrollComplete',
  56396. hasBouncing: '@',
  56397. padding: '@',
  56398. direction: '@',
  56399. scrollbarX: '@',
  56400. scrollbarY: '@',
  56401. startX: '@',
  56402. startY: '@',
  56403. scrollEventInterval: '@'
  56404. });
  56405. $scope.direction = $scope.direction || 'y';
  56406. if (isDefined($attr.padding)) {
  56407. $scope.$watch($attr.padding, function(newVal) {
  56408. (innerElement || $element).toggleClass('padding', !!newVal);
  56409. });
  56410. }
  56411. if ($attr.scroll === "false") {
  56412. //do nothing
  56413. } else {
  56414. var scrollViewOptions = {};
  56415. // determined in compile phase above
  56416. if (nativeScrolling) {
  56417. // use native scrolling
  56418. $element.addClass('overflow-scroll');
  56419. scrollViewOptions = {
  56420. el: $element[0],
  56421. delegateHandle: attr.delegateHandle,
  56422. startX: $scope.$eval($scope.startX) || 0,
  56423. startY: $scope.$eval($scope.startY) || 0,
  56424. nativeScrolling: true
  56425. };
  56426. } else {
  56427. // Use JS scrolling
  56428. scrollViewOptions = {
  56429. el: $element[0],
  56430. delegateHandle: attr.delegateHandle,
  56431. locking: (attr.locking || 'true') === 'true',
  56432. bouncing: $scope.$eval($scope.hasBouncing),
  56433. startX: $scope.$eval($scope.startX) || 0,
  56434. startY: $scope.$eval($scope.startY) || 0,
  56435. scrollbarX: $scope.$eval($scope.scrollbarX) !== false,
  56436. scrollbarY: $scope.$eval($scope.scrollbarY) !== false,
  56437. scrollingX: $scope.direction.indexOf('x') >= 0,
  56438. scrollingY: $scope.direction.indexOf('y') >= 0,
  56439. scrollEventInterval: parseInt($scope.scrollEventInterval, 10) || 10,
  56440. scrollingComplete: onScrollComplete
  56441. };
  56442. }
  56443. // init scroll controller with appropriate options
  56444. scrollCtrl = $controller('$ionicScroll', {
  56445. $scope: $scope,
  56446. scrollViewOptions: scrollViewOptions
  56447. });
  56448. $scope.scrollCtrl = scrollCtrl;
  56449. $scope.$on('$destroy', function() {
  56450. if (scrollViewOptions) {
  56451. scrollViewOptions.scrollingComplete = noop;
  56452. delete scrollViewOptions.el;
  56453. }
  56454. innerElement = null;
  56455. $element = null;
  56456. attr.$$element = null;
  56457. });
  56458. }
  56459. function onScrollComplete() {
  56460. $scope.$onScrollComplete({
  56461. scrollTop: scrollCtrl.scrollView.__scrollTop,
  56462. scrollLeft: scrollCtrl.scrollView.__scrollLeft
  56463. });
  56464. }
  56465. }
  56466. }
  56467. };
  56468. }]);
  56469. /**
  56470. * @ngdoc directive
  56471. * @name exposeAsideWhen
  56472. * @module ionic
  56473. * @restrict A
  56474. * @parent ionic.directive:ionSideMenus
  56475. *
  56476. * @description
  56477. * It is common for a tablet application to hide a menu when in portrait mode, but to show the
  56478. * same menu on the left side when the tablet is in landscape mode. The `exposeAsideWhen` attribute
  56479. * directive can be used to accomplish a similar interface.
  56480. *
  56481. * By default, side menus are hidden underneath its side menu content, and can be opened by either
  56482. * swiping the content left or right, or toggling a button to show the side menu. However, by adding the
  56483. * `exposeAsideWhen` attribute directive to an {@link ionic.directive:ionSideMenu} element directive,
  56484. * a side menu can be given instructions on "when" the menu should be exposed (always viewable). For
  56485. * example, the `expose-aside-when="large"` attribute will keep the side menu hidden when the viewport's
  56486. * width is less than `768px`, but when the viewport's width is `768px` or greater, the menu will then
  56487. * always be shown and can no longer be opened or closed like it could when it was hidden for smaller
  56488. * viewports.
  56489. *
  56490. * Using `large` as the attribute's value is a shortcut value to `(min-width:768px)` since it is
  56491. * the most common use-case. However, for added flexibility, any valid media query could be added
  56492. * as the value, such as `(min-width:600px)` or even multiple queries such as
  56493. * `(min-width:750px) and (max-width:1200px)`.
  56494. * @usage
  56495. * ```html
  56496. * <ion-side-menus>
  56497. * <!-- Center content -->
  56498. * <ion-side-menu-content>
  56499. * </ion-side-menu-content>
  56500. *
  56501. * <!-- Left menu -->
  56502. * <ion-side-menu expose-aside-when="large">
  56503. * </ion-side-menu>
  56504. * </ion-side-menus>
  56505. * ```
  56506. * For a complete side menu example, see the
  56507. * {@link ionic.directive:ionSideMenus} documentation.
  56508. */
  56509. IonicModule.directive('exposeAsideWhen', ['$window', function($window) {
  56510. return {
  56511. restrict: 'A',
  56512. require: '^ionSideMenus',
  56513. link: function($scope, $element, $attr, sideMenuCtrl) {
  56514. var prevInnerWidth = $window.innerWidth;
  56515. var prevInnerHeight = $window.innerHeight;
  56516. ionic.on('resize', function() {
  56517. if (prevInnerWidth === $window.innerWidth && prevInnerHeight === $window.innerHeight) {
  56518. return;
  56519. }
  56520. prevInnerWidth = $window.innerWidth;
  56521. prevInnerHeight = $window.innerHeight;
  56522. onResize();
  56523. }, $window);
  56524. function checkAsideExpose() {
  56525. var mq = $attr.exposeAsideWhen == 'large' ? '(min-width:768px)' : $attr.exposeAsideWhen;
  56526. sideMenuCtrl.exposeAside($window.matchMedia(mq).matches);
  56527. sideMenuCtrl.activeAsideResizing(false);
  56528. }
  56529. function onResize() {
  56530. sideMenuCtrl.activeAsideResizing(true);
  56531. debouncedCheck();
  56532. }
  56533. var debouncedCheck = ionic.debounce(function() {
  56534. $scope.$apply(checkAsideExpose);
  56535. }, 300, false);
  56536. $scope.$evalAsync(checkAsideExpose);
  56537. }
  56538. };
  56539. }]);
  56540. var GESTURE_DIRECTIVES = 'onHold onTap onDoubleTap onTouch onRelease onDragStart onDrag onDragEnd onDragUp onDragRight onDragDown onDragLeft onSwipe onSwipeUp onSwipeRight onSwipeDown onSwipeLeft'.split(' ');
  56541. GESTURE_DIRECTIVES.forEach(function(name) {
  56542. IonicModule.directive(name, gestureDirective(name));
  56543. });
  56544. /**
  56545. * @ngdoc directive
  56546. * @name onHold
  56547. * @module ionic
  56548. * @restrict A
  56549. *
  56550. * @description
  56551. * Touch stays at the same location for 500ms. Similar to long touch events available for AngularJS and jQuery.
  56552. *
  56553. * @usage
  56554. * ```html
  56555. * <button on-hold="onHold()" class="button">Test</button>
  56556. * ```
  56557. */
  56558. /**
  56559. * @ngdoc directive
  56560. * @name onTap
  56561. * @module ionic
  56562. * @restrict A
  56563. *
  56564. * @description
  56565. * Quick touch at a location. If the duration of the touch goes
  56566. * longer than 250ms it is no longer a tap gesture.
  56567. *
  56568. * @usage
  56569. * ```html
  56570. * <button on-tap="onTap()" class="button">Test</button>
  56571. * ```
  56572. */
  56573. /**
  56574. * @ngdoc directive
  56575. * @name onDoubleTap
  56576. * @module ionic
  56577. * @restrict A
  56578. *
  56579. * @description
  56580. * Double tap touch at a location.
  56581. *
  56582. * @usage
  56583. * ```html
  56584. * <button on-double-tap="onDoubleTap()" class="button">Test</button>
  56585. * ```
  56586. */
  56587. /**
  56588. * @ngdoc directive
  56589. * @name onTouch
  56590. * @module ionic
  56591. * @restrict A
  56592. *
  56593. * @description
  56594. * Called immediately when the user first begins a touch. This
  56595. * gesture does not wait for a touchend/mouseup.
  56596. *
  56597. * @usage
  56598. * ```html
  56599. * <button on-touch="onTouch()" class="button">Test</button>
  56600. * ```
  56601. */
  56602. /**
  56603. * @ngdoc directive
  56604. * @name onRelease
  56605. * @module ionic
  56606. * @restrict A
  56607. *
  56608. * @description
  56609. * Called when the user ends a touch.
  56610. *
  56611. * @usage
  56612. * ```html
  56613. * <button on-release="onRelease()" class="button">Test</button>
  56614. * ```
  56615. */
  56616. /**
  56617. * @ngdoc directive
  56618. * @name onDragStart
  56619. * @module ionic
  56620. * @restrict A
  56621. *
  56622. * @description
  56623. * Called when a drag gesture has started.
  56624. *
  56625. * @usage
  56626. * ```html
  56627. * <button on-drag-start="onDragStart()" class="button">Test</button>
  56628. * ```
  56629. */
  56630. /**
  56631. * @ngdoc directive
  56632. * @name onDrag
  56633. * @module ionic
  56634. * @restrict A
  56635. *
  56636. * @description
  56637. * Move with one touch around on the page. Blocking the scrolling when
  56638. * moving left and right is a good practice. When all the drag events are
  56639. * blocking you disable scrolling on that area.
  56640. *
  56641. * @usage
  56642. * ```html
  56643. * <button on-drag="onDrag()" class="button">Test</button>
  56644. * ```
  56645. */
  56646. /**
  56647. * @ngdoc directive
  56648. * @name onDragEnd
  56649. * @module ionic
  56650. * @restrict A
  56651. *
  56652. * @description
  56653. * Called when a drag gesture has ended.
  56654. *
  56655. * @usage
  56656. * ```html
  56657. * <button on-drag-end="onDragEnd()" class="button">Test</button>
  56658. * ```
  56659. */
  56660. /**
  56661. * @ngdoc directive
  56662. * @name onDragUp
  56663. * @module ionic
  56664. * @restrict A
  56665. *
  56666. * @description
  56667. * Called when the element is dragged up.
  56668. *
  56669. * @usage
  56670. * ```html
  56671. * <button on-drag-up="onDragUp()" class="button">Test</button>
  56672. * ```
  56673. */
  56674. /**
  56675. * @ngdoc directive
  56676. * @name onDragRight
  56677. * @module ionic
  56678. * @restrict A
  56679. *
  56680. * @description
  56681. * Called when the element is dragged to the right.
  56682. *
  56683. * @usage
  56684. * ```html
  56685. * <button on-drag-right="onDragRight()" class="button">Test</button>
  56686. * ```
  56687. */
  56688. /**
  56689. * @ngdoc directive
  56690. * @name onDragDown
  56691. * @module ionic
  56692. * @restrict A
  56693. *
  56694. * @description
  56695. * Called when the element is dragged down.
  56696. *
  56697. * @usage
  56698. * ```html
  56699. * <button on-drag-down="onDragDown()" class="button">Test</button>
  56700. * ```
  56701. */
  56702. /**
  56703. * @ngdoc directive
  56704. * @name onDragLeft
  56705. * @module ionic
  56706. * @restrict A
  56707. *
  56708. * @description
  56709. * Called when the element is dragged to the left.
  56710. *
  56711. * @usage
  56712. * ```html
  56713. * <button on-drag-left="onDragLeft()" class="button">Test</button>
  56714. * ```
  56715. */
  56716. /**
  56717. * @ngdoc directive
  56718. * @name onSwipe
  56719. * @module ionic
  56720. * @restrict A
  56721. *
  56722. * @description
  56723. * Called when a moving touch has a high velocity in any direction.
  56724. *
  56725. * @usage
  56726. * ```html
  56727. * <button on-swipe="onSwipe()" class="button">Test</button>
  56728. * ```
  56729. */
  56730. /**
  56731. * @ngdoc directive
  56732. * @name onSwipeUp
  56733. * @module ionic
  56734. * @restrict A
  56735. *
  56736. * @description
  56737. * Called when a moving touch has a high velocity moving up.
  56738. *
  56739. * @usage
  56740. * ```html
  56741. * <button on-swipe-up="onSwipeUp()" class="button">Test</button>
  56742. * ```
  56743. */
  56744. /**
  56745. * @ngdoc directive
  56746. * @name onSwipeRight
  56747. * @module ionic
  56748. * @restrict A
  56749. *
  56750. * @description
  56751. * Called when a moving touch has a high velocity moving to the right.
  56752. *
  56753. * @usage
  56754. * ```html
  56755. * <button on-swipe-right="onSwipeRight()" class="button">Test</button>
  56756. * ```
  56757. */
  56758. /**
  56759. * @ngdoc directive
  56760. * @name onSwipeDown
  56761. * @module ionic
  56762. * @restrict A
  56763. *
  56764. * @description
  56765. * Called when a moving touch has a high velocity moving down.
  56766. *
  56767. * @usage
  56768. * ```html
  56769. * <button on-swipe-down="onSwipeDown()" class="button">Test</button>
  56770. * ```
  56771. */
  56772. /**
  56773. * @ngdoc directive
  56774. * @name onSwipeLeft
  56775. * @module ionic
  56776. * @restrict A
  56777. *
  56778. * @description
  56779. * Called when a moving touch has a high velocity moving to the left.
  56780. *
  56781. * @usage
  56782. * ```html
  56783. * <button on-swipe-left="onSwipeLeft()" class="button">Test</button>
  56784. * ```
  56785. */
  56786. function gestureDirective(directiveName) {
  56787. return ['$ionicGesture', '$parse', function($ionicGesture, $parse) {
  56788. var eventType = directiveName.substr(2).toLowerCase();
  56789. return function(scope, element, attr) {
  56790. var fn = $parse( attr[directiveName] );
  56791. var listener = function(ev) {
  56792. scope.$apply(function() {
  56793. fn(scope, {
  56794. $event: ev
  56795. });
  56796. });
  56797. };
  56798. var gesture = $ionicGesture.on(eventType, listener, element);
  56799. scope.$on('$destroy', function() {
  56800. $ionicGesture.off(gesture, eventType, listener);
  56801. });
  56802. };
  56803. }];
  56804. }
  56805. IonicModule
  56806. //.directive('ionHeaderBar', tapScrollToTopDirective())
  56807. /**
  56808. * @ngdoc directive
  56809. * @name ionHeaderBar
  56810. * @module ionic
  56811. * @restrict E
  56812. *
  56813. * @description
  56814. * Adds a fixed header bar above some content.
  56815. *
  56816. * Can also be a subheader (lower down) if the 'bar-subheader' class is applied.
  56817. * See [the header CSS docs](/docs/components/#subheader).
  56818. *
  56819. * @param {string=} align-title How to align the title. By default the title
  56820. * will be aligned the same as how the platform aligns its titles (iOS centers
  56821. * titles, Android aligns them left).
  56822. * Available: 'left', 'right', or 'center'. Defaults to the same as the platform.
  56823. * @param {boolean=} no-tap-scroll By default, the header bar will scroll the
  56824. * content to the top when tapped. Set no-tap-scroll to true to disable this
  56825. * behavior.
  56826. * Available: true or false. Defaults to false.
  56827. *
  56828. * @usage
  56829. * ```html
  56830. * <ion-header-bar align-title="left" class="bar-positive">
  56831. * <div class="buttons">
  56832. * <button class="button" ng-click="doSomething()">Left Button</button>
  56833. * </div>
  56834. * <h1 class="title">Title!</h1>
  56835. * <div class="buttons">
  56836. * <button class="button">Right Button</button>
  56837. * </div>
  56838. * </ion-header-bar>
  56839. * <ion-content class="has-header">
  56840. * Some content!
  56841. * </ion-content>
  56842. * ```
  56843. */
  56844. .directive('ionHeaderBar', headerFooterBarDirective(true))
  56845. /**
  56846. * @ngdoc directive
  56847. * @name ionFooterBar
  56848. * @module ionic
  56849. * @restrict E
  56850. *
  56851. * @description
  56852. * Adds a fixed footer bar below some content.
  56853. *
  56854. * Can also be a subfooter (higher up) if the 'bar-subfooter' class is applied.
  56855. * See [the footer CSS docs](/docs/components/#footer).
  56856. *
  56857. * Note: If you use ionFooterBar in combination with ng-if, the surrounding content
  56858. * will not align correctly. This will be fixed soon.
  56859. *
  56860. * @param {string=} align-title Where to align the title.
  56861. * Available: 'left', 'right', or 'center'. Defaults to 'center'.
  56862. *
  56863. * @usage
  56864. * ```html
  56865. * <ion-content class="has-footer">
  56866. * Some content!
  56867. * </ion-content>
  56868. * <ion-footer-bar align-title="left" class="bar-assertive">
  56869. * <div class="buttons">
  56870. * <button class="button">Left Button</button>
  56871. * </div>
  56872. * <h1 class="title">Title!</h1>
  56873. * <div class="buttons" ng-click="doSomething()">
  56874. * <button class="button">Right Button</button>
  56875. * </div>
  56876. * </ion-footer-bar>
  56877. * ```
  56878. */
  56879. .directive('ionFooterBar', headerFooterBarDirective(false));
  56880. function tapScrollToTopDirective() { //eslint-disable-line no-unused-vars
  56881. return ['$ionicScrollDelegate', function($ionicScrollDelegate) {
  56882. return {
  56883. restrict: 'E',
  56884. link: function($scope, $element, $attr) {
  56885. if ($attr.noTapScroll == 'true') {
  56886. return;
  56887. }
  56888. ionic.on('tap', onTap, $element[0]);
  56889. $scope.$on('$destroy', function() {
  56890. ionic.off('tap', onTap, $element[0]);
  56891. });
  56892. function onTap(e) {
  56893. var depth = 3;
  56894. var current = e.target;
  56895. //Don't scroll to top in certain cases
  56896. while (depth-- && current) {
  56897. if (current.classList.contains('button') ||
  56898. current.tagName.match(/input|textarea|select/i) ||
  56899. current.isContentEditable) {
  56900. return;
  56901. }
  56902. current = current.parentNode;
  56903. }
  56904. var touch = e.gesture && e.gesture.touches[0] || e.detail.touches[0];
  56905. var bounds = $element[0].getBoundingClientRect();
  56906. if (ionic.DomUtil.rectContains(
  56907. touch.pageX, touch.pageY,
  56908. bounds.left, bounds.top - 20,
  56909. bounds.left + bounds.width, bounds.top + bounds.height
  56910. )) {
  56911. $ionicScrollDelegate.scrollTop(true);
  56912. }
  56913. }
  56914. }
  56915. };
  56916. }];
  56917. }
  56918. function headerFooterBarDirective(isHeader) {
  56919. return ['$document', '$timeout', function($document, $timeout) {
  56920. return {
  56921. restrict: 'E',
  56922. controller: '$ionicHeaderBar',
  56923. compile: function(tElement) {
  56924. tElement.addClass(isHeader ? 'bar bar-header' : 'bar bar-footer');
  56925. // top style tabs? if so, remove bottom border for seamless display
  56926. $timeout(function() {
  56927. if (isHeader && $document[0].getElementsByClassName('tabs-top').length) tElement.addClass('has-tabs-top');
  56928. });
  56929. return { pre: prelink };
  56930. function prelink($scope, $element, $attr, ctrl) {
  56931. if (isHeader) {
  56932. $scope.$watch(function() { return $element[0].className; }, function(value) {
  56933. var isShown = value.indexOf('ng-hide') === -1;
  56934. var isSubheader = value.indexOf('bar-subheader') !== -1;
  56935. $scope.$hasHeader = isShown && !isSubheader;
  56936. $scope.$hasSubheader = isShown && isSubheader;
  56937. $scope.$emit('$ionicSubheader', $scope.$hasSubheader);
  56938. });
  56939. $scope.$on('$destroy', function() {
  56940. delete $scope.$hasHeader;
  56941. delete $scope.$hasSubheader;
  56942. });
  56943. ctrl.align();
  56944. $scope.$on('$ionicHeader.align', function() {
  56945. ionic.requestAnimationFrame(function() {
  56946. ctrl.align();
  56947. });
  56948. });
  56949. } else {
  56950. $scope.$watch(function() { return $element[0].className; }, function(value) {
  56951. var isShown = value.indexOf('ng-hide') === -1;
  56952. var isSubfooter = value.indexOf('bar-subfooter') !== -1;
  56953. $scope.$hasFooter = isShown && !isSubfooter;
  56954. $scope.$hasSubfooter = isShown && isSubfooter;
  56955. });
  56956. $scope.$on('$destroy', function() {
  56957. delete $scope.$hasFooter;
  56958. delete $scope.$hasSubfooter;
  56959. });
  56960. $scope.$watch('$hasTabs', function(val) {
  56961. $element.toggleClass('has-tabs', !!val);
  56962. });
  56963. ctrl.align();
  56964. $scope.$on('$ionicFooter.align', function() {
  56965. ionic.requestAnimationFrame(function() {
  56966. ctrl.align();
  56967. });
  56968. });
  56969. }
  56970. }
  56971. }
  56972. };
  56973. }];
  56974. }
  56975. /**
  56976. * @ngdoc directive
  56977. * @name ionInfiniteScroll
  56978. * @module ionic
  56979. * @parent ionic.directive:ionContent, ionic.directive:ionScroll
  56980. * @restrict E
  56981. *
  56982. * @description
  56983. * The ionInfiniteScroll directive allows you to call a function whenever
  56984. * the user gets to the bottom of the page or near the bottom of the page.
  56985. *
  56986. * The expression you pass in for `on-infinite` is called when the user scrolls
  56987. * greater than `distance` away from the bottom of the content. Once `on-infinite`
  56988. * is done loading new data, it should broadcast the `scroll.infiniteScrollComplete`
  56989. * event from your controller (see below example).
  56990. *
  56991. * @param {expression} on-infinite What to call when the scroller reaches the
  56992. * bottom.
  56993. * @param {string=} distance The distance from the bottom that the scroll must
  56994. * reach to trigger the on-infinite expression. Default: 1%.
  56995. * @param {string=} spinner The {@link ionic.directive:ionSpinner} to show while loading. The SVG
  56996. * {@link ionic.directive:ionSpinner} is now the default, replacing rotating font icons.
  56997. * @param {string=} icon The icon to show while loading. Default: 'ion-load-d'. This is depreciated
  56998. * in favor of the SVG {@link ionic.directive:ionSpinner}.
  56999. * @param {boolean=} immediate-check Whether to check the infinite scroll bounds immediately on load.
  57000. *
  57001. * @usage
  57002. * ```html
  57003. * <ion-content ng-controller="MyController">
  57004. * <ion-list>
  57005. * ....
  57006. * ....
  57007. * </ion-list>
  57008. *
  57009. * <ion-infinite-scroll
  57010. * on-infinite="loadMore()"
  57011. * distance="1%">
  57012. * </ion-infinite-scroll>
  57013. * </ion-content>
  57014. * ```
  57015. * ```js
  57016. * function MyController($scope, $http) {
  57017. * $scope.items = [];
  57018. * $scope.loadMore = function() {
  57019. * $http.get('/more-items').success(function(items) {
  57020. * useItems(items);
  57021. * $scope.$broadcast('scroll.infiniteScrollComplete');
  57022. * });
  57023. * };
  57024. *
  57025. * $scope.$on('$stateChangeSuccess', function() {
  57026. * $scope.loadMore();
  57027. * });
  57028. * }
  57029. * ```
  57030. *
  57031. * An easy to way to stop infinite scroll once there is no more data to load
  57032. * is to use angular's `ng-if` directive:
  57033. *
  57034. * ```html
  57035. * <ion-infinite-scroll
  57036. * ng-if="moreDataCanBeLoaded()"
  57037. * icon="ion-loading-c"
  57038. * on-infinite="loadMoreData()">
  57039. * </ion-infinite-scroll>
  57040. * ```
  57041. */
  57042. IonicModule
  57043. .directive('ionInfiniteScroll', ['$timeout', function($timeout) {
  57044. return {
  57045. restrict: 'E',
  57046. require: ['?^$ionicScroll', 'ionInfiniteScroll'],
  57047. template: function($element, $attrs) {
  57048. if ($attrs.icon) return '<i class="icon {{icon()}} icon-refreshing {{scrollingType}}"></i>';
  57049. return '<ion-spinner icon="{{spinner()}}"></ion-spinner>';
  57050. },
  57051. scope: true,
  57052. controller: '$ionInfiniteScroll',
  57053. link: function($scope, $element, $attrs, ctrls) {
  57054. var infiniteScrollCtrl = ctrls[1];
  57055. var scrollCtrl = infiniteScrollCtrl.scrollCtrl = ctrls[0];
  57056. var jsScrolling = infiniteScrollCtrl.jsScrolling = !scrollCtrl.isNative();
  57057. // if this view is not beneath a scrollCtrl, it can't be injected, proceed w/ native scrolling
  57058. if (jsScrolling) {
  57059. infiniteScrollCtrl.scrollView = scrollCtrl.scrollView;
  57060. $scope.scrollingType = 'js-scrolling';
  57061. //bind to JS scroll events
  57062. scrollCtrl.$element.on('scroll', infiniteScrollCtrl.checkBounds);
  57063. } else {
  57064. // grabbing the scrollable element, to determine dimensions, and current scroll pos
  57065. var scrollEl = ionic.DomUtil.getParentOrSelfWithClass($element[0].parentNode, 'overflow-scroll');
  57066. infiniteScrollCtrl.scrollEl = scrollEl;
  57067. // if there's no scroll controller, and no overflow scroll div, infinite scroll wont work
  57068. if (!scrollEl) {
  57069. throw 'Infinite scroll must be used inside a scrollable div';
  57070. }
  57071. //bind to native scroll events
  57072. infiniteScrollCtrl.scrollEl.addEventListener('scroll', infiniteScrollCtrl.checkBounds);
  57073. }
  57074. // Optionally check bounds on start after scrollView is fully rendered
  57075. var doImmediateCheck = isDefined($attrs.immediateCheck) ? $scope.$eval($attrs.immediateCheck) : true;
  57076. if (doImmediateCheck) {
  57077. $timeout(function() { infiniteScrollCtrl.checkBounds(); });
  57078. }
  57079. }
  57080. };
  57081. }]);
  57082. /**
  57083. * @ngdoc directive
  57084. * @name ionInput
  57085. * @parent ionic.directive:ionList
  57086. * @module ionic
  57087. * @restrict E
  57088. * Creates a text input group that can easily be focused
  57089. *
  57090. * @usage
  57091. *
  57092. * ```html
  57093. * <ion-list>
  57094. * <ion-input>
  57095. * <input type="text" placeholder="First Name">
  57096. * </ion-input>
  57097. *
  57098. * <ion-input>
  57099. * <ion-label>Username</ion-label>
  57100. * <input type="text">
  57101. * </ion-input>
  57102. * </ion-list>
  57103. * ```
  57104. */
  57105. var labelIds = -1;
  57106. IonicModule
  57107. .directive('ionInput', [function() {
  57108. return {
  57109. restrict: 'E',
  57110. controller: ['$scope', '$element', function($scope, $element) {
  57111. this.$scope = $scope;
  57112. this.$element = $element;
  57113. this.setInputAriaLabeledBy = function(id) {
  57114. var inputs = $element[0].querySelectorAll('input,textarea');
  57115. inputs.length && inputs[0].setAttribute('aria-labelledby', id);
  57116. };
  57117. this.focus = function() {
  57118. var inputs = $element[0].querySelectorAll('input,textarea');
  57119. inputs.length && inputs[0].focus();
  57120. };
  57121. }]
  57122. };
  57123. }]);
  57124. /**
  57125. * @ngdoc directive
  57126. * @name ionLabel
  57127. * @parent ionic.directive:ionList
  57128. * @module ionic
  57129. * @restrict E
  57130. *
  57131. * New in Ionic 1.2. It is strongly recommended that you use `<ion-label>` in place
  57132. * of any `<label>` elements for maximum cross-browser support and performance.
  57133. *
  57134. * Creates a label for a form input.
  57135. *
  57136. * @usage
  57137. *
  57138. * ```html
  57139. * <ion-list>
  57140. * <ion-input>
  57141. * <ion-label>Username</ion-label>
  57142. * <input type="text">
  57143. * </ion-input>
  57144. * </ion-list>
  57145. * ```
  57146. */
  57147. IonicModule
  57148. .directive('ionLabel', [function() {
  57149. return {
  57150. restrict: 'E',
  57151. require: '?^ionInput',
  57152. compile: function() {
  57153. return function link($scope, $element, $attrs, ionInputCtrl) {
  57154. var element = $element[0];
  57155. $element.addClass('input-label');
  57156. $element.attr('aria-label', $element.text());
  57157. var id = element.id || '_label-' + ++labelIds;
  57158. if (!element.id) {
  57159. $element.attr('id', id);
  57160. }
  57161. if (ionInputCtrl) {
  57162. ionInputCtrl.setInputAriaLabeledBy(id);
  57163. $element.on('click', function() {
  57164. ionInputCtrl.focus();
  57165. });
  57166. }
  57167. };
  57168. }
  57169. };
  57170. }]);
  57171. /**
  57172. * Input label adds accessibility to <span class="input-label">.
  57173. */
  57174. IonicModule
  57175. .directive('inputLabel', [function() {
  57176. return {
  57177. restrict: 'C',
  57178. require: '?^ionInput',
  57179. compile: function() {
  57180. return function link($scope, $element, $attrs, ionInputCtrl) {
  57181. var element = $element[0];
  57182. $element.attr('aria-label', $element.text());
  57183. var id = element.id || '_label-' + ++labelIds;
  57184. if (!element.id) {
  57185. $element.attr('id', id);
  57186. }
  57187. if (ionInputCtrl) {
  57188. ionInputCtrl.setInputAriaLabeledBy(id);
  57189. }
  57190. };
  57191. }
  57192. };
  57193. }]);
  57194. /**
  57195. * @ngdoc directive
  57196. * @name ionItem
  57197. * @parent ionic.directive:ionList
  57198. * @module ionic
  57199. * @restrict E
  57200. * Creates a list-item that can easily be swiped,
  57201. * deleted, reordered, edited, and more.
  57202. *
  57203. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57204. *
  57205. * Can be assigned any item class name. See the
  57206. * [list CSS documentation](/docs/components/#list).
  57207. *
  57208. * @usage
  57209. *
  57210. * ```html
  57211. * <ion-list>
  57212. * <ion-item>Hello!</ion-item>
  57213. * <ion-item href="#/detail">
  57214. * Link to detail page
  57215. * </ion-item>
  57216. * </ion-list>
  57217. * ```
  57218. */
  57219. IonicModule
  57220. .directive('ionItem', ['$$rAF', function($$rAF) {
  57221. return {
  57222. restrict: 'E',
  57223. controller: ['$scope', '$element', function($scope, $element) {
  57224. this.$scope = $scope;
  57225. this.$element = $element;
  57226. }],
  57227. scope: true,
  57228. compile: function($element, $attrs) {
  57229. var isAnchor = isDefined($attrs.href) ||
  57230. isDefined($attrs.ngHref) ||
  57231. isDefined($attrs.uiSref);
  57232. var isComplexItem = isAnchor ||
  57233. //Lame way of testing, but we have to know at compile what to do with the element
  57234. /ion-(delete|option|reorder)-button/i.test($element.html());
  57235. if (isComplexItem) {
  57236. var innerElement = jqLite(isAnchor ? '<a></a>' : '<div></div>');
  57237. innerElement.addClass('item-content');
  57238. if (isDefined($attrs.href) || isDefined($attrs.ngHref)) {
  57239. innerElement.attr('ng-href', '{{$href()}}');
  57240. if (isDefined($attrs.target)) {
  57241. innerElement.attr('target', '{{$target()}}');
  57242. }
  57243. }
  57244. innerElement.append($element.contents());
  57245. $element.addClass('item item-complex')
  57246. .append(innerElement);
  57247. } else {
  57248. $element.addClass('item');
  57249. }
  57250. return function link($scope, $element, $attrs) {
  57251. $scope.$href = function() {
  57252. return $attrs.href || $attrs.ngHref;
  57253. };
  57254. $scope.$target = function() {
  57255. return $attrs.target;
  57256. };
  57257. var content = $element[0].querySelector('.item-content');
  57258. if (content) {
  57259. $scope.$on('$collectionRepeatLeave', function() {
  57260. if (content && content.$$ionicOptionsOpen) {
  57261. content.style[ionic.CSS.TRANSFORM] = '';
  57262. content.style[ionic.CSS.TRANSITION] = 'none';
  57263. $$rAF(function() {
  57264. content.style[ionic.CSS.TRANSITION] = '';
  57265. });
  57266. content.$$ionicOptionsOpen = false;
  57267. }
  57268. });
  57269. }
  57270. };
  57271. }
  57272. };
  57273. }]);
  57274. var ITEM_TPL_DELETE_BUTTON =
  57275. '<div class="item-left-edit item-delete enable-pointer-events">' +
  57276. '</div>';
  57277. /**
  57278. * @ngdoc directive
  57279. * @name ionDeleteButton
  57280. * @parent ionic.directive:ionItem
  57281. * @module ionic
  57282. * @restrict E
  57283. * Creates a delete button inside a list item, that is visible when the
  57284. * {@link ionic.directive:ionList ionList parent's} `show-delete` evaluates to true or
  57285. * `$ionicListDelegate.showDelete(true)` is called.
  57286. *
  57287. * Takes any ionicon as a class.
  57288. *
  57289. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57290. *
  57291. * @usage
  57292. *
  57293. * ```html
  57294. * <ion-list show-delete="shouldShowDelete">
  57295. * <ion-item>
  57296. * <ion-delete-button class="ion-minus-circled"></ion-delete-button>
  57297. * Hello, list item!
  57298. * </ion-item>
  57299. * </ion-list>
  57300. * <ion-toggle ng-model="shouldShowDelete">
  57301. * Show Delete?
  57302. * </ion-toggle>
  57303. * ```
  57304. */
  57305. IonicModule
  57306. .directive('ionDeleteButton', function() {
  57307. function stopPropagation(ev) {
  57308. ev.stopPropagation();
  57309. }
  57310. return {
  57311. restrict: 'E',
  57312. require: ['^^ionItem', '^?ionList'],
  57313. //Run before anything else, so we can move it before other directives process
  57314. //its location (eg ngIf relies on the location of the directive in the dom)
  57315. priority: Number.MAX_VALUE,
  57316. compile: function($element, $attr) {
  57317. //Add the classes we need during the compile phase, so that they stay
  57318. //even if something else like ngIf removes the element and re-addss it
  57319. $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);
  57320. return function($scope, $element, $attr, ctrls) {
  57321. var itemCtrl = ctrls[0];
  57322. var listCtrl = ctrls[1];
  57323. var container = jqLite(ITEM_TPL_DELETE_BUTTON);
  57324. container.append($element);
  57325. itemCtrl.$element.append(container).addClass('item-left-editable');
  57326. //Don't bubble click up to main .item
  57327. $element.on('click', stopPropagation);
  57328. init();
  57329. $scope.$on('$ionic.reconnectScope', init);
  57330. function init() {
  57331. listCtrl = listCtrl || $element.controller('ionList');
  57332. if (listCtrl && listCtrl.showDelete()) {
  57333. container.addClass('visible active');
  57334. }
  57335. }
  57336. };
  57337. }
  57338. };
  57339. });
  57340. IonicModule
  57341. .directive('itemFloatingLabel', function() {
  57342. return {
  57343. restrict: 'C',
  57344. link: function(scope, element) {
  57345. var el = element[0];
  57346. var input = el.querySelector('input, textarea');
  57347. var inputLabel = el.querySelector('.input-label');
  57348. if (!input || !inputLabel) return;
  57349. var onInput = function() {
  57350. if (input.value) {
  57351. inputLabel.classList.add('has-input');
  57352. } else {
  57353. inputLabel.classList.remove('has-input');
  57354. }
  57355. };
  57356. input.addEventListener('input', onInput);
  57357. var ngModelCtrl = jqLite(input).controller('ngModel');
  57358. if (ngModelCtrl) {
  57359. ngModelCtrl.$render = function() {
  57360. input.value = ngModelCtrl.$viewValue || '';
  57361. onInput();
  57362. };
  57363. }
  57364. scope.$on('$destroy', function() {
  57365. input.removeEventListener('input', onInput);
  57366. });
  57367. }
  57368. };
  57369. });
  57370. var ITEM_TPL_OPTION_BUTTONS =
  57371. '<div class="item-options invisible">' +
  57372. '</div>';
  57373. /**
  57374. * @ngdoc directive
  57375. * @name ionOptionButton
  57376. * @parent ionic.directive:ionItem
  57377. * @module ionic
  57378. * @restrict E
  57379. * @description
  57380. * Creates an option button inside a list item, that is visible when the item is swiped
  57381. * to the left by the user. Swiped open option buttons can be hidden with
  57382. * {@link ionic.service:$ionicListDelegate#closeOptionButtons $ionicListDelegate.closeOptionButtons}.
  57383. *
  57384. * Can be assigned any button class.
  57385. *
  57386. * See {@link ionic.directive:ionList} for a complete example & explanation.
  57387. *
  57388. * @usage
  57389. *
  57390. * ```html
  57391. * <ion-list>
  57392. * <ion-item>
  57393. * I love kittens!
  57394. * <ion-option-button class="button-positive">Share</ion-option-button>
  57395. * <ion-option-button class="button-assertive">Edit</ion-option-button>
  57396. * </ion-item>
  57397. * </ion-list>
  57398. * ```
  57399. */
  57400. IonicModule.directive('ionOptionButton', [function() {
  57401. function stopPropagation(e) {
  57402. e.stopPropagation();
  57403. }
  57404. return {
  57405. restrict: 'E',
  57406. require: '^ionItem',
  57407. priority: Number.MAX_VALUE,
  57408. compile: function($element, $attr) {
  57409. $attr.$set('class', ($attr['class'] || '') + ' button', true);
  57410. return function($scope, $element, $attr, itemCtrl) {
  57411. if (!itemCtrl.optionsContainer) {
  57412. itemCtrl.optionsContainer = jqLite(ITEM_TPL_OPTION_BUTTONS);
  57413. itemCtrl.$element.prepend(itemCtrl.optionsContainer);
  57414. }
  57415. itemCtrl.optionsContainer.prepend($element);
  57416. itemCtrl.$element.addClass('item-right-editable');
  57417. //Don't bubble click up to main .item
  57418. $element.on('click', stopPropagation);
  57419. };
  57420. }
  57421. };
  57422. }]);
  57423. var ITEM_TPL_REORDER_BUTTON =
  57424. '<div data-prevent-scroll="true" class="item-right-edit item-reorder enable-pointer-events">' +
  57425. '</div>';
  57426. /**
  57427. * @ngdoc directive
  57428. * @name ionReorderButton
  57429. * @parent ionic.directive:ionItem
  57430. * @module ionic
  57431. * @restrict E
  57432. * Creates a reorder button inside a list item, that is visible when the
  57433. * {@link ionic.directive:ionList ionList parent's} `show-reorder` evaluates to true or
  57434. * `$ionicListDelegate.showReorder(true)` is called.
  57435. *
  57436. * Can be dragged to reorder items in the list. Takes any ionicon class.
  57437. *
  57438. * 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.
  57439. *
  57440. * 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.
  57441. *
  57442. * Look at {@link ionic.directive:ionList} for more examples.
  57443. *
  57444. * @usage
  57445. *
  57446. * ```html
  57447. * <ion-list ng-controller="MyCtrl" show-reorder="true">
  57448. * <ion-item ng-repeat="item in items">
  57449. * Item {{item}}
  57450. * <ion-reorder-button class="ion-navicon"
  57451. * on-reorder="moveItem(item, $fromIndex, $toIndex)">
  57452. * </ion-reorder-button>
  57453. * </ion-item>
  57454. * </ion-list>
  57455. * ```
  57456. * ```js
  57457. * function MyCtrl($scope) {
  57458. * $scope.items = [1, 2, 3, 4];
  57459. * $scope.moveItem = function(item, fromIndex, toIndex) {
  57460. * //Move the item in the array
  57461. * $scope.items.splice(fromIndex, 1);
  57462. * $scope.items.splice(toIndex, 0, item);
  57463. * };
  57464. * }
  57465. * ```
  57466. *
  57467. * @param {expression=} on-reorder Expression to call when an item is reordered.
  57468. * Parameters given: $fromIndex, $toIndex.
  57469. */
  57470. IonicModule
  57471. .directive('ionReorderButton', ['$parse', function($parse) {
  57472. return {
  57473. restrict: 'E',
  57474. require: ['^ionItem', '^?ionList'],
  57475. priority: Number.MAX_VALUE,
  57476. compile: function($element, $attr) {
  57477. $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);
  57478. $element[0].setAttribute('data-prevent-scroll', true);
  57479. return function($scope, $element, $attr, ctrls) {
  57480. var itemCtrl = ctrls[0];
  57481. var listCtrl = ctrls[1];
  57482. var onReorderFn = $parse($attr.onReorder);
  57483. $scope.$onReorder = function(oldIndex, newIndex) {
  57484. onReorderFn($scope, {
  57485. $fromIndex: oldIndex,
  57486. $toIndex: newIndex
  57487. });
  57488. };
  57489. // prevent clicks from bubbling up to the item
  57490. if (!$attr.ngClick && !$attr.onClick && !$attr.onclick) {
  57491. $element[0].onclick = function(e) {
  57492. e.stopPropagation();
  57493. return false;
  57494. };
  57495. }
  57496. var container = jqLite(ITEM_TPL_REORDER_BUTTON);
  57497. container.append($element);
  57498. itemCtrl.$element.append(container).addClass('item-right-editable');
  57499. if (listCtrl && listCtrl.showReorder()) {
  57500. container.addClass('visible active');
  57501. }
  57502. };
  57503. }
  57504. };
  57505. }]);
  57506. /**
  57507. * @ngdoc directive
  57508. * @name keyboardAttach
  57509. * @module ionic
  57510. * @restrict A
  57511. *
  57512. * @description
  57513. * keyboard-attach is an attribute directive which will cause an element to float above
  57514. * the keyboard when the keyboard shows. Currently only supports the
  57515. * [ion-footer-bar]({{ page.versionHref }}/api/directive/ionFooterBar/) directive.
  57516. *
  57517. * ### Notes
  57518. * - This directive requires the
  57519. * [Ionic Keyboard Plugin](https://github.com/ionic-team/ionic-plugins-keyboard).
  57520. * - On Android not in fullscreen mode, i.e. you have
  57521. * `<preference name="Fullscreen" value="false" />` or no preference in your `config.xml` file,
  57522. * this directive is unnecessary since it is the default behavior.
  57523. * - On iOS, if there is an input in your footer, you will need to set
  57524. * `cordova.plugins.Keyboard.disableScroll(true)`.
  57525. *
  57526. * @usage
  57527. *
  57528. * ```html
  57529. * <ion-footer-bar align-title="left" keyboard-attach class="bar-assertive">
  57530. * <h1 class="title">Title!</h1>
  57531. * </ion-footer-bar>
  57532. * ```
  57533. */
  57534. IonicModule
  57535. .directive('keyboardAttach', function() {
  57536. return function(scope, element) {
  57537. ionic.on('native.keyboardshow', onShow, window);
  57538. ionic.on('native.keyboardhide', onHide, window);
  57539. //deprecated
  57540. ionic.on('native.showkeyboard', onShow, window);
  57541. ionic.on('native.hidekeyboard', onHide, window);
  57542. var scrollCtrl;
  57543. function onShow(e) {
  57544. if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {
  57545. return;
  57546. }
  57547. //for testing
  57548. var keyboardHeight = e.keyboardHeight || (e.detail && e.detail.keyboardHeight);
  57549. element.css('bottom', keyboardHeight + "px");
  57550. scrollCtrl = element.controller('$ionicScroll');
  57551. if (scrollCtrl) {
  57552. scrollCtrl.scrollView.__container.style.bottom = keyboardHeight + keyboardAttachGetClientHeight(element[0]) + "px";
  57553. }
  57554. }
  57555. function onHide() {
  57556. if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {
  57557. return;
  57558. }
  57559. element.css('bottom', '');
  57560. if (scrollCtrl) {
  57561. scrollCtrl.scrollView.__container.style.bottom = '';
  57562. }
  57563. }
  57564. scope.$on('$destroy', function() {
  57565. ionic.off('native.keyboardshow', onShow, window);
  57566. ionic.off('native.keyboardhide', onHide, window);
  57567. //deprecated
  57568. ionic.off('native.showkeyboard', onShow, window);
  57569. ionic.off('native.hidekeyboard', onHide, window);
  57570. });
  57571. };
  57572. });
  57573. function keyboardAttachGetClientHeight(element) {
  57574. return element.clientHeight;
  57575. }
  57576. /**
  57577. * @ngdoc directive
  57578. * @name ionList
  57579. * @module ionic
  57580. * @delegate ionic.service:$ionicListDelegate
  57581. * @codepen JsHjf
  57582. * @restrict E
  57583. * @description
  57584. * The List is a widely used interface element in almost any mobile app, and can include
  57585. * content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.
  57586. *
  57587. * Both the list, which contains items, and the list items themselves can be any HTML
  57588. * element. The containing element requires the `list` class and each list item requires
  57589. * the `item` class.
  57590. *
  57591. * However, using the ionList and ionItem directives make it easy to support various
  57592. * interaction modes such as swipe to edit, drag to reorder, and removing items.
  57593. *
  57594. * Related: {@link ionic.directive:ionItem}, {@link ionic.directive:ionOptionButton}
  57595. * {@link ionic.directive:ionReorderButton}, {@link ionic.directive:ionDeleteButton}, [`list CSS documentation`](/docs/components/#list).
  57596. *
  57597. * @usage
  57598. *
  57599. * Basic Usage:
  57600. *
  57601. * ```html
  57602. * <ion-list>
  57603. * <ion-item ng-repeat="item in items">
  57604. * {% raw %}Hello, {{item}}!{% endraw %}
  57605. * </ion-item>
  57606. * </ion-list>
  57607. * ```
  57608. *
  57609. * Advanced Usage: Thumbnails, Delete buttons, Reordering, Swiping
  57610. *
  57611. * ```html
  57612. * <ion-list ng-controller="MyCtrl"
  57613. * show-delete="shouldShowDelete"
  57614. * show-reorder="shouldShowReorder"
  57615. * can-swipe="listCanSwipe">
  57616. * <ion-item ng-repeat="item in items"
  57617. * class="item-thumbnail-left">
  57618. *
  57619. * {% raw %}<img ng-src="{{item.img}}">
  57620. * <h2>{{item.title}}</h2>
  57621. * <p>{{item.description}}</p>{% endraw %}
  57622. * <ion-option-button class="button-positive"
  57623. * ng-click="share(item)">
  57624. * Share
  57625. * </ion-option-button>
  57626. * <ion-option-button class="button-info"
  57627. * ng-click="edit(item)">
  57628. * Edit
  57629. * </ion-option-button>
  57630. * <ion-delete-button class="ion-minus-circled"
  57631. * ng-click="items.splice($index, 1)">
  57632. * </ion-delete-button>
  57633. * <ion-reorder-button class="ion-navicon"
  57634. * on-reorder="reorderItem(item, $fromIndex, $toIndex)">
  57635. * </ion-reorder-button>
  57636. *
  57637. * </ion-item>
  57638. * </ion-list>
  57639. * ```
  57640. *
  57641. *```javascript
  57642. * app.controller('MyCtrl', function($scope) {
  57643. * $scope.shouldShowDelete = false;
  57644. * $scope.shouldShowReorder = false;
  57645. * $scope.listCanSwipe = true
  57646. * });
  57647. *```
  57648. *
  57649. * @param {string=} delegate-handle The handle used to identify this list with
  57650. * {@link ionic.service:$ionicListDelegate}.
  57651. * @param type {string=} The type of list to use (list-inset or card)
  57652. * @param show-delete {boolean=} Whether the delete buttons for the items in the list are
  57653. * currently shown or hidden.
  57654. * @param show-reorder {boolean=} Whether the reorder buttons for the items in the list are
  57655. * currently shown or hidden.
  57656. * @param can-swipe {boolean=} Whether the items in the list are allowed to be swiped to reveal
  57657. * option buttons. Default: true.
  57658. */
  57659. IonicModule
  57660. .directive('ionList', [
  57661. '$timeout',
  57662. function($timeout) {
  57663. return {
  57664. restrict: 'E',
  57665. require: ['ionList', '^?$ionicScroll'],
  57666. controller: '$ionicList',
  57667. compile: function($element, $attr) {
  57668. var listEl = jqLite('<div class="list">')
  57669. .append($element.contents())
  57670. .addClass($attr.type);
  57671. $element.append(listEl);
  57672. return function($scope, $element, $attrs, ctrls) {
  57673. var listCtrl = ctrls[0];
  57674. var scrollCtrl = ctrls[1];
  57675. // Wait for child elements to render...
  57676. $timeout(init);
  57677. function init() {
  57678. var listView = listCtrl.listView = new ionic.views.ListView({
  57679. el: $element[0],
  57680. listEl: $element.children()[0],
  57681. scrollEl: scrollCtrl && scrollCtrl.element,
  57682. scrollView: scrollCtrl && scrollCtrl.scrollView,
  57683. onReorder: function(el, oldIndex, newIndex) {
  57684. var itemScope = jqLite(el).scope();
  57685. if (itemScope && itemScope.$onReorder) {
  57686. // Make sure onReorder is called in apply cycle,
  57687. // but also make sure it has no conflicts by doing
  57688. // $evalAsync
  57689. $timeout(function() {
  57690. itemScope.$onReorder(oldIndex, newIndex);
  57691. });
  57692. }
  57693. },
  57694. canSwipe: function() {
  57695. return listCtrl.canSwipeItems();
  57696. }
  57697. });
  57698. $scope.$on('$destroy', function() {
  57699. if (listView) {
  57700. listView.deregister && listView.deregister();
  57701. listView = null;
  57702. }
  57703. });
  57704. if (isDefined($attr.canSwipe)) {
  57705. $scope.$watch('!!(' + $attr.canSwipe + ')', function(value) {
  57706. listCtrl.canSwipeItems(value);
  57707. });
  57708. }
  57709. if (isDefined($attr.showDelete)) {
  57710. $scope.$watch('!!(' + $attr.showDelete + ')', function(value) {
  57711. listCtrl.showDelete(value);
  57712. });
  57713. }
  57714. if (isDefined($attr.showReorder)) {
  57715. $scope.$watch('!!(' + $attr.showReorder + ')', function(value) {
  57716. listCtrl.showReorder(value);
  57717. });
  57718. }
  57719. $scope.$watch(function() {
  57720. return listCtrl.showDelete();
  57721. }, function(isShown, wasShown) {
  57722. //Only use isShown=false if it was already shown
  57723. if (!isShown && !wasShown) { return; }
  57724. if (isShown) listCtrl.closeOptionButtons();
  57725. listCtrl.canSwipeItems(!isShown);
  57726. $element.children().toggleClass('list-left-editing', isShown);
  57727. $element.toggleClass('disable-pointer-events', isShown);
  57728. var deleteButton = jqLite($element[0].getElementsByClassName('item-delete'));
  57729. setButtonShown(deleteButton, listCtrl.showDelete);
  57730. });
  57731. $scope.$watch(function() {
  57732. return listCtrl.showReorder();
  57733. }, function(isShown, wasShown) {
  57734. //Only use isShown=false if it was already shown
  57735. if (!isShown && !wasShown) { return; }
  57736. if (isShown) listCtrl.closeOptionButtons();
  57737. listCtrl.canSwipeItems(!isShown);
  57738. $element.children().toggleClass('list-right-editing', isShown);
  57739. $element.toggleClass('disable-pointer-events', isShown);
  57740. var reorderButton = jqLite($element[0].getElementsByClassName('item-reorder'));
  57741. setButtonShown(reorderButton, listCtrl.showReorder);
  57742. });
  57743. function setButtonShown(el, shown) {
  57744. shown() && el.addClass('visible') || el.removeClass('active');
  57745. ionic.requestAnimationFrame(function() {
  57746. shown() && el.addClass('active') || el.removeClass('visible');
  57747. });
  57748. }
  57749. }
  57750. };
  57751. }
  57752. };
  57753. }]);
  57754. /**
  57755. * @ngdoc directive
  57756. * @name menuClose
  57757. * @module ionic
  57758. * @restrict AC
  57759. *
  57760. * @description
  57761. * `menu-close` is an attribute directive that closes a currently opened side menu.
  57762. * Note that by default, navigation transitions will not animate between views when
  57763. * the menu is open. Additionally, this directive will reset the entering view's
  57764. * history stack, making the new page the root of the history stack. This is done
  57765. * to replicate the user experience seen in most side menu implementations, which is
  57766. * to not show the back button at the root of the stack and show only the
  57767. * menu button. We recommend that you also use the `enable-menu-with-back-views="false"`
  57768. * {@link ionic.directive:ionSideMenus} attribute when using the menuClose directive.
  57769. *
  57770. * @usage
  57771. * Below is an example of a link within a side menu. Tapping this link would
  57772. * automatically close the currently opened menu.
  57773. *
  57774. * ```html
  57775. * <a menu-close href="#/home" class="item">Home</a>
  57776. * ```
  57777. *
  57778. * Note that if your destination state uses a resolve and that resolve asynchronously
  57779. * takes longer than a standard transition (300ms), you'll need to set the
  57780. * `nextViewOptions` manually as your resolve completes.
  57781. *
  57782. * ```js
  57783. * $ionicHistory.nextViewOptions({
  57784. * historyRoot: true,
  57785. * disableAnimate: true,
  57786. * expire: 300
  57787. * });
  57788. * ```
  57789. */
  57790. IonicModule
  57791. .directive('menuClose', ['$ionicHistory', '$timeout', function($ionicHistory, $timeout) {
  57792. return {
  57793. restrict: 'AC',
  57794. link: function($scope, $element) {
  57795. $element.bind('click', function() {
  57796. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57797. if (sideMenuCtrl) {
  57798. $ionicHistory.nextViewOptions({
  57799. historyRoot: true,
  57800. disableAnimate: true,
  57801. expire: 300
  57802. });
  57803. // if no transition in 300ms, reset nextViewOptions
  57804. // the expire should take care of it, but will be cancelled in some
  57805. // cases. This directive is an exception to the rules of history.js
  57806. $timeout( function() {
  57807. $ionicHistory.nextViewOptions({
  57808. historyRoot: false,
  57809. disableAnimate: false
  57810. });
  57811. }, 300);
  57812. sideMenuCtrl.close();
  57813. }
  57814. });
  57815. }
  57816. };
  57817. }]);
  57818. /**
  57819. * @ngdoc directive
  57820. * @name menuToggle
  57821. * @module ionic
  57822. * @restrict AC
  57823. *
  57824. * @description
  57825. * Toggle a side menu on the given side.
  57826. *
  57827. * @usage
  57828. * Below is an example of a link within a nav bar. Tapping this button
  57829. * would open the given side menu, and tapping it again would close it.
  57830. *
  57831. * ```html
  57832. * <ion-nav-bar>
  57833. * <ion-nav-buttons side="left">
  57834. * <!-- Toggle left side menu -->
  57835. * <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  57836. * </ion-nav-buttons>
  57837. * <ion-nav-buttons side="right">
  57838. * <!-- Toggle right side menu -->
  57839. * <button menu-toggle="right" class="button button-icon icon ion-navicon"></button>
  57840. * </ion-nav-buttons>
  57841. * </ion-nav-bar>
  57842. * ```
  57843. *
  57844. * ### Button Hidden On Child Views
  57845. * By default, the menu toggle button will only appear on a root
  57846. * level side-menu page. Navigating in to child views will hide the menu-
  57847. * toggle button. They can be made visible on child pages by setting the
  57848. * enable-menu-with-back-views attribute of the {@link ionic.directive:ionSideMenus}
  57849. * directive to true.
  57850. *
  57851. * ```html
  57852. * <ion-side-menus enable-menu-with-back-views="true">
  57853. * ```
  57854. */
  57855. IonicModule
  57856. .directive('menuToggle', function() {
  57857. return {
  57858. restrict: 'AC',
  57859. link: function($scope, $element, $attr) {
  57860. $scope.$on('$ionicView.beforeEnter', function(ev, viewData) {
  57861. if (viewData.enableBack) {
  57862. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57863. if (!sideMenuCtrl.enableMenuWithBackViews()) {
  57864. $element.addClass('hide');
  57865. }
  57866. } else {
  57867. $element.removeClass('hide');
  57868. }
  57869. });
  57870. $element.bind('click', function() {
  57871. var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');
  57872. sideMenuCtrl && sideMenuCtrl.toggle($attr.menuToggle);
  57873. });
  57874. }
  57875. };
  57876. });
  57877. /*
  57878. * We don't document the ionModal directive, we instead document
  57879. * the $ionicModal service
  57880. */
  57881. IonicModule
  57882. .directive('ionModal', [function() {
  57883. return {
  57884. restrict: 'E',
  57885. transclude: true,
  57886. replace: true,
  57887. controller: [function() {}],
  57888. template: '<div class="modal-backdrop">' +
  57889. '<div class="modal-backdrop-bg"></div>' +
  57890. '<div class="modal-wrapper" ng-transclude></div>' +
  57891. '</div>'
  57892. };
  57893. }]);
  57894. IonicModule
  57895. .directive('ionModalView', function() {
  57896. return {
  57897. restrict: 'E',
  57898. compile: function(element) {
  57899. element.addClass('modal');
  57900. }
  57901. };
  57902. });
  57903. /**
  57904. * @ngdoc directive
  57905. * @name ionNavBackButton
  57906. * @module ionic
  57907. * @restrict E
  57908. * @parent ionNavBar
  57909. * @description
  57910. * Creates a back button inside an {@link ionic.directive:ionNavBar}.
  57911. *
  57912. * The back button will appear when the user is able to go back in the current navigation stack. By
  57913. * default, the markup of the back button is automatically built using platform-appropriate defaults
  57914. * (iOS back button icon on iOS and Android icon on Android).
  57915. *
  57916. * Additionally, the button is automatically set to `$ionicGoBack()` on click/tap. By default, the
  57917. * app will navigate back one view when the back button is clicked. More advanced behavior is also
  57918. * possible, as outlined below.
  57919. *
  57920. * @usage
  57921. *
  57922. * Recommended markup for default settings:
  57923. *
  57924. * ```html
  57925. * <ion-nav-bar>
  57926. * <ion-nav-back-button>
  57927. * </ion-nav-back-button>
  57928. * </ion-nav-bar>
  57929. * ```
  57930. *
  57931. * With custom inner markup, and automatically adds a default click action:
  57932. *
  57933. * ```html
  57934. * <ion-nav-bar>
  57935. * <ion-nav-back-button class="button-clear">
  57936. * <i class="ion-arrow-left-c"></i> Back
  57937. * </ion-nav-back-button>
  57938. * </ion-nav-bar>
  57939. * ```
  57940. *
  57941. * With custom inner markup and custom click action, using {@link ionic.service:$ionicHistory}:
  57942. *
  57943. * ```html
  57944. * <ion-nav-bar ng-controller="MyCtrl">
  57945. * <ion-nav-back-button class="button-clear"
  57946. * ng-click="myGoBack()">
  57947. * <i class="ion-arrow-left-c"></i> Back
  57948. * </ion-nav-back-button>
  57949. * </ion-nav-bar>
  57950. * ```
  57951. * ```js
  57952. * function MyCtrl($scope, $ionicHistory) {
  57953. * $scope.myGoBack = function() {
  57954. * $ionicHistory.goBack();
  57955. * };
  57956. * }
  57957. * ```
  57958. */
  57959. IonicModule
  57960. .directive('ionNavBackButton', ['$ionicConfig', '$document', function($ionicConfig, $document) {
  57961. return {
  57962. restrict: 'E',
  57963. require: '^ionNavBar',
  57964. compile: function(tElement, tAttrs) {
  57965. // clone the back button, but as a <div>
  57966. var buttonEle = $document[0].createElement('button');
  57967. for (var n in tAttrs.$attr) {
  57968. buttonEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);
  57969. }
  57970. if (!tAttrs.ngClick) {
  57971. buttonEle.setAttribute('ng-click', '$ionicGoBack()');
  57972. }
  57973. buttonEle.className = 'button back-button hide buttons ' + (tElement.attr('class') || '');
  57974. buttonEle.innerHTML = tElement.html() || '';
  57975. var childNode;
  57976. var hasIcon = hasIconClass(tElement[0]);
  57977. var hasInnerText;
  57978. var hasButtonText;
  57979. var hasPreviousTitle;
  57980. for (var x = 0; x < tElement[0].childNodes.length; x++) {
  57981. childNode = tElement[0].childNodes[x];
  57982. if (childNode.nodeType === 1) {
  57983. if (hasIconClass(childNode)) {
  57984. hasIcon = true;
  57985. } else if (childNode.classList.contains('default-title')) {
  57986. hasButtonText = true;
  57987. } else if (childNode.classList.contains('previous-title')) {
  57988. hasPreviousTitle = true;
  57989. }
  57990. } else if (!hasInnerText && childNode.nodeType === 3) {
  57991. hasInnerText = !!childNode.nodeValue.trim();
  57992. }
  57993. }
  57994. function hasIconClass(ele) {
  57995. return /ion-|icon/.test(ele.className);
  57996. }
  57997. var defaultIcon = $ionicConfig.backButton.icon();
  57998. if (!hasIcon && defaultIcon && defaultIcon !== 'none') {
  57999. buttonEle.innerHTML = '<i class="icon ' + defaultIcon + '"></i> ' + buttonEle.innerHTML;
  58000. buttonEle.className += ' button-clear';
  58001. }
  58002. if (!hasInnerText) {
  58003. var buttonTextEle = $document[0].createElement('span');
  58004. buttonTextEle.className = 'back-text';
  58005. if (!hasButtonText && $ionicConfig.backButton.text()) {
  58006. buttonTextEle.innerHTML += '<span class="default-title">' + $ionicConfig.backButton.text() + '</span>';
  58007. }
  58008. if (!hasPreviousTitle && $ionicConfig.backButton.previousTitleText()) {
  58009. buttonTextEle.innerHTML += '<span class="previous-title"></span>';
  58010. }
  58011. buttonEle.appendChild(buttonTextEle);
  58012. }
  58013. tElement.attr('class', 'hide');
  58014. tElement.empty();
  58015. return {
  58016. pre: function($scope, $element, $attr, navBarCtrl) {
  58017. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58018. navBarCtrl.navElement('backButton', buttonEle.outerHTML);
  58019. buttonEle = null;
  58020. }
  58021. };
  58022. }
  58023. };
  58024. }]);
  58025. /**
  58026. * @ngdoc directive
  58027. * @name ionNavBar
  58028. * @module ionic
  58029. * @delegate ionic.service:$ionicNavBarDelegate
  58030. * @restrict E
  58031. *
  58032. * @description
  58033. * If we have an {@link ionic.directive:ionNavView} directive, we can also create an
  58034. * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.
  58035. *
  58036. * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.
  58037. *
  58038. * We can add buttons depending on the currently visible view using
  58039. * {@link ionic.directive:ionNavButtons}.
  58040. *
  58041. * Note that the ion-nav-bar element will only work correctly if your content has an
  58042. * ionView around it.
  58043. *
  58044. * @usage
  58045. *
  58046. * ```html
  58047. * <body ng-app="starter">
  58048. * <!-- The nav bar that will be updated as we navigate -->
  58049. * <ion-nav-bar class="bar-positive">
  58050. * </ion-nav-bar>
  58051. *
  58052. * <!-- where the initial view template will be rendered -->
  58053. * <ion-nav-view>
  58054. * <ion-view>
  58055. * <ion-content>Hello!</ion-content>
  58056. * </ion-view>
  58057. * </ion-nav-view>
  58058. * </body>
  58059. * ```
  58060. *
  58061. * @param {string=} delegate-handle The handle used to identify this navBar
  58062. * with {@link ionic.service:$ionicNavBarDelegate}.
  58063. * @param align-title {string=} Where to align the title of the navbar.
  58064. * Available: 'left', 'right', 'center'. Defaults to 'center'.
  58065. * @param {boolean=} no-tap-scroll By default, the navbar will scroll the content
  58066. * to the top when tapped. Set no-tap-scroll to true to disable this behavior.
  58067. *
  58068. */
  58069. IonicModule
  58070. .directive('ionNavBar', function() {
  58071. return {
  58072. restrict: 'E',
  58073. controller: '$ionicNavBar',
  58074. scope: true,
  58075. link: function($scope, $element, $attr, ctrl) {
  58076. ctrl.init();
  58077. }
  58078. };
  58079. });
  58080. /**
  58081. * @ngdoc directive
  58082. * @name ionNavButtons
  58083. * @module ionic
  58084. * @restrict E
  58085. * @parent ionNavView
  58086. *
  58087. * @description
  58088. * Use nav buttons to set the buttons on your {@link ionic.directive:ionNavBar}
  58089. * from within an {@link ionic.directive:ionView}. This gives each
  58090. * view template the ability to specify which buttons should show in the nav bar,
  58091. * overriding any default buttons already placed in the nav bar.
  58092. *
  58093. * Any buttons you declare will be positioned on the navbar's corresponding side. Primary
  58094. * buttons generally map to the left side of the header, and secondary buttons are
  58095. * generally on the right side. However, their exact locations are platform-specific.
  58096. * For example, in iOS, the primary buttons are on the far left of the header, and
  58097. * secondary buttons are on the far right, with the header title centered between them.
  58098. * For Android, however, both groups of buttons are on the far right of the header,
  58099. * with the header title aligned left.
  58100. *
  58101. * We recommend always using `primary` and `secondary`, so the buttons correctly map
  58102. * to the side familiar to users of each platform. However, in cases where buttons should
  58103. * always be on an exact side, both `left` and `right` sides are still available. For
  58104. * example, a toggle button for a left side menu should be on the left side; in this case,
  58105. * we'd recommend using `side="left"`, so it's always on the left, no matter the platform.
  58106. *
  58107. * ***Note*** that `ion-nav-buttons` must be immediate descendants of the `ion-view` or
  58108. * `ion-nav-bar` element (basically, don't wrap it in another div).
  58109. *
  58110. * @usage
  58111. * ```html
  58112. * <ion-nav-bar>
  58113. * </ion-nav-bar>
  58114. * <ion-nav-view>
  58115. * <ion-view>
  58116. * <ion-nav-buttons side="primary">
  58117. * <button class="button" ng-click="doSomething()">
  58118. * I'm a button on the primary of the navbar!
  58119. * </button>
  58120. * </ion-nav-buttons>
  58121. * <ion-content>
  58122. * Some super content here!
  58123. * </ion-content>
  58124. * </ion-view>
  58125. * </ion-nav-view>
  58126. * ```
  58127. *
  58128. * @param {string} side The side to place the buttons in the
  58129. * {@link ionic.directive:ionNavBar}. Available sides: `primary`, `secondary`, `left`, and `right`.
  58130. */
  58131. IonicModule
  58132. .directive('ionNavButtons', ['$document', function($document) {
  58133. return {
  58134. require: '^ionNavBar',
  58135. restrict: 'E',
  58136. compile: function(tElement, tAttrs) {
  58137. var side = 'left';
  58138. if (/^primary|secondary|right$/i.test(tAttrs.side || '')) {
  58139. side = tAttrs.side.toLowerCase();
  58140. }
  58141. var spanEle = $document[0].createElement('span');
  58142. spanEle.className = side + '-buttons';
  58143. spanEle.innerHTML = tElement.html();
  58144. var navElementType = side + 'Buttons';
  58145. tElement.attr('class', 'hide');
  58146. tElement.empty();
  58147. return {
  58148. pre: function($scope, $element, $attrs, navBarCtrl) {
  58149. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58150. var parentViewCtrl = $element.parent().data('$ionViewController');
  58151. if (parentViewCtrl) {
  58152. // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view
  58153. parentViewCtrl.navElement(navElementType, spanEle.outerHTML);
  58154. } else {
  58155. // these are buttons for all views that do not have their own ion-nav-buttons
  58156. navBarCtrl.navElement(navElementType, spanEle.outerHTML);
  58157. }
  58158. spanEle = null;
  58159. }
  58160. };
  58161. }
  58162. };
  58163. }]);
  58164. /**
  58165. * @ngdoc directive
  58166. * @name navDirection
  58167. * @module ionic
  58168. * @restrict A
  58169. *
  58170. * @description
  58171. * The direction which the nav view transition should animate. Available options
  58172. * are: `forward`, `back`, `enter`, `exit`, `swap`.
  58173. *
  58174. * @usage
  58175. *
  58176. * ```html
  58177. * <a nav-direction="forward" href="#/home">Home</a>
  58178. * ```
  58179. */
  58180. IonicModule
  58181. .directive('navDirection', ['$ionicViewSwitcher', function($ionicViewSwitcher) {
  58182. return {
  58183. restrict: 'A',
  58184. priority: 1000,
  58185. link: function($scope, $element, $attr) {
  58186. $element.bind('click', function() {
  58187. $ionicViewSwitcher.nextDirection($attr.navDirection);
  58188. });
  58189. }
  58190. };
  58191. }]);
  58192. /**
  58193. * @ngdoc directive
  58194. * @name ionNavTitle
  58195. * @module ionic
  58196. * @restrict E
  58197. * @parent ionNavView
  58198. *
  58199. * @description
  58200. *
  58201. * The nav title directive replaces an {@link ionic.directive:ionNavBar} title text with
  58202. * custom HTML from within an {@link ionic.directive:ionView} template. This gives each
  58203. * view the ability to specify its own custom title element, such as an image or any HTML,
  58204. * rather than being text-only. Alternatively, text-only titles can be updated using the
  58205. * `view-title` {@link ionic.directive:ionView} attribute.
  58206. *
  58207. * Note that `ion-nav-title` must be an immediate descendant of the `ion-view` or
  58208. * `ion-nav-bar` element (basically don't wrap it in another div).
  58209. *
  58210. * @usage
  58211. * ```html
  58212. * <ion-nav-bar>
  58213. * </ion-nav-bar>
  58214. * <ion-nav-view>
  58215. * <ion-view>
  58216. * <ion-nav-title>
  58217. * <img src="logo.svg">
  58218. * </ion-nav-title>
  58219. * <ion-content>
  58220. * Some super content here!
  58221. * </ion-content>
  58222. * </ion-view>
  58223. * </ion-nav-view>
  58224. * ```
  58225. *
  58226. */
  58227. IonicModule
  58228. .directive('ionNavTitle', ['$document', function($document) {
  58229. return {
  58230. require: '^ionNavBar',
  58231. restrict: 'E',
  58232. compile: function(tElement, tAttrs) {
  58233. var navElementType = 'title';
  58234. var spanEle = $document[0].createElement('span');
  58235. for (var n in tAttrs.$attr) {
  58236. spanEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);
  58237. }
  58238. spanEle.classList.add('nav-bar-title');
  58239. spanEle.innerHTML = tElement.html();
  58240. tElement.attr('class', 'hide');
  58241. tElement.empty();
  58242. return {
  58243. pre: function($scope, $element, $attrs, navBarCtrl) {
  58244. // only register the plain HTML, the navBarCtrl takes care of scope/compile/link
  58245. var parentViewCtrl = $element.parent().data('$ionViewController');
  58246. if (parentViewCtrl) {
  58247. // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view
  58248. parentViewCtrl.navElement(navElementType, spanEle.outerHTML);
  58249. } else {
  58250. // these are buttons for all views that do not have their own ion-nav-buttons
  58251. navBarCtrl.navElement(navElementType, spanEle.outerHTML);
  58252. }
  58253. spanEle = null;
  58254. }
  58255. };
  58256. }
  58257. };
  58258. }]);
  58259. /**
  58260. * @ngdoc directive
  58261. * @name navTransition
  58262. * @module ionic
  58263. * @restrict A
  58264. *
  58265. * @description
  58266. * The transition type which the nav view transition should use when it animates.
  58267. * Current, options are `ios`, `android`, and `none`. More options coming soon.
  58268. *
  58269. * @usage
  58270. *
  58271. * ```html
  58272. * <a nav-transition="none" href="#/home">Home</a>
  58273. * ```
  58274. */
  58275. IonicModule
  58276. .directive('navTransition', ['$ionicViewSwitcher', function($ionicViewSwitcher) {
  58277. return {
  58278. restrict: 'A',
  58279. priority: 1000,
  58280. link: function($scope, $element, $attr) {
  58281. $element.bind('click', function() {
  58282. $ionicViewSwitcher.nextTransition($attr.navTransition);
  58283. });
  58284. }
  58285. };
  58286. }]);
  58287. /**
  58288. * @ngdoc directive
  58289. * @name ionNavView
  58290. * @module ionic
  58291. * @restrict E
  58292. * @codepen odqCz
  58293. *
  58294. * @description
  58295. * As a user navigates throughout your app, Ionic is able to keep track of their
  58296. * navigation history. By knowing their history, transitions between views
  58297. * correctly enter and exit using the platform's transition style. An additional
  58298. * benefit to Ionic's navigation system is its ability to manage multiple
  58299. * histories. For example, each tab can have it's own navigation history stack.
  58300. *
  58301. * Ionic uses the AngularUI Router module so app interfaces can be organized
  58302. * into various "states". Like Angular's core $route service, URLs can be used
  58303. * to control the views. However, the AngularUI Router provides a more powerful
  58304. * state manager in that states are bound to named, nested, and parallel views,
  58305. * allowing more than one template to be rendered on the same page.
  58306. * Additionally, each state is not required to be bound to a URL, and data can
  58307. * be pushed to each state which allows much flexibility.
  58308. *
  58309. * The ionNavView directive is used to render templates in your application. Each template
  58310. * is part of a state. States are usually mapped to a url, and are defined programatically
  58311. * using angular-ui-router (see [their docs](https://github.com/angular-ui/ui-router/wiki),
  58312. * and remember to replace ui-view with ion-nav-view in examples).
  58313. *
  58314. * @usage
  58315. * In this example, we will create a navigation view that contains our different states for the app.
  58316. *
  58317. * To do this, in our markup we use ionNavView top level directive. To display a header bar we use
  58318. * the {@link ionic.directive:ionNavBar} directive that updates as we navigate through the
  58319. * navigation stack.
  58320. *
  58321. * Next, we need to setup our states that will be rendered.
  58322. *
  58323. * ```js
  58324. * var app = angular.module('myApp', ['ionic']);
  58325. * app.config(function($stateProvider) {
  58326. * $stateProvider
  58327. * .state('index', {
  58328. * url: '/',
  58329. * templateUrl: 'home.html'
  58330. * })
  58331. * .state('music', {
  58332. * url: '/music',
  58333. * templateUrl: 'music.html'
  58334. * });
  58335. * });
  58336. * ```
  58337. * Then on app start, $stateProvider will look at the url, see if it matches the index state,
  58338. * and then try to load home.html into the `<ion-nav-view>`.
  58339. *
  58340. * Pages are loaded by the URLs given. One simple way to create templates in Angular is to put
  58341. * them directly into your HTML file and use the `<script type="text/ng-template">` syntax.
  58342. * So here is one way to put home.html into our app:
  58343. *
  58344. * ```html
  58345. * <script id="home" type="text/ng-template">
  58346. * <!-- The title of the ion-view will be shown on the navbar -->
  58347. * <ion-view view-title="Home">
  58348. * <ion-content ng-controller="HomeCtrl">
  58349. * <!-- The content of the page -->
  58350. * <a href="#/music">Go to music page!</a>
  58351. * </ion-content>
  58352. * </ion-view>
  58353. * </script>
  58354. * ```
  58355. *
  58356. * This is good to do because the template will be cached for very fast loading, instead of
  58357. * having to fetch them from the network.
  58358. *
  58359. * ## Caching
  58360. *
  58361. * By default, views are cached to improve performance. When a view is navigated away from, its
  58362. * element is left in the DOM, and its scope is disconnected from the `$watch` cycle. When
  58363. * navigating to a view that is already cached, its scope is then reconnected, and the existing
  58364. * element that was left in the DOM becomes the active view. This also allows for the scroll
  58365. * position of previous views to be maintained.
  58366. *
  58367. * Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of
  58368. * 10 views, and not only can this be configured, but apps can also explicitly state which views
  58369. * should and should not be cached.
  58370. *
  58371. * Note that because we are caching these views, *we aren’t destroying scopes*. Instead, scopes
  58372. * are being disconnected from the watch cycle. Because scopes are not being destroyed and
  58373. * recreated, controllers are not loading again on a subsequent viewing. If the app/controller
  58374. * needs to know when a view has entered or has left, then view events emitted from the
  58375. * {@link ionic.directive:ionView} scope, such as `$ionicView.enter`, may be useful.
  58376. *
  58377. * By default, when navigating back in the history, the "forward" views are removed from the cache.
  58378. * If you navigate forward to the same view again, it'll create a new DOM element and controller
  58379. * instance. Basically, any forward views are reset each time. This can be configured using the
  58380. * {@link ionic.provider:$ionicConfigProvider}:
  58381. *
  58382. * ```js
  58383. * $ionicConfigProvider.views.forwardCache(true);
  58384. * ```
  58385. *
  58386. * #### Disable cache globally
  58387. *
  58388. * The {@link ionic.provider:$ionicConfigProvider} can be used to set the maximum allowable views
  58389. * which can be cached, but this can also be use to disable all caching by setting it to 0.
  58390. *
  58391. * ```js
  58392. * $ionicConfigProvider.views.maxCache(0);
  58393. * ```
  58394. *
  58395. * #### Disable cache within state provider
  58396. *
  58397. * ```js
  58398. * $stateProvider.state('myState', {
  58399. * cache: false,
  58400. * url : '/myUrl',
  58401. * templateUrl : 'my-template.html'
  58402. * })
  58403. * ```
  58404. *
  58405. * #### Disable cache with an attribute
  58406. *
  58407. * ```html
  58408. * <ion-view cache-view="false" view-title="My Title!">
  58409. * ...
  58410. * </ion-view>
  58411. * ```
  58412. *
  58413. *
  58414. * ## AngularUI Router
  58415. *
  58416. * Please visit [AngularUI Router's docs](https://github.com/angular-ui/ui-router/wiki) for
  58417. * more info. Below is a great video by the AngularUI Router team that may help to explain
  58418. * how it all works:
  58419. *
  58420. * <iframe width="560" height="315" src="//www.youtube.com/embed/dqJRoh8MnBo"
  58421. * frameborder="0" allowfullscreen></iframe>
  58422. *
  58423. * Note: We do not recommend using [resolve](https://github.com/angular-ui/ui-router/wiki#resolve)
  58424. * of AngularUI Router. The recommended approach is to execute any logic needed before beginning the state transition.
  58425. *
  58426. * @param {string=} name A view name. The name should be unique amongst the other views in the
  58427. * same state. You can have views of the same name that live in different states. For more
  58428. * information, see ui-router's
  58429. * [ui-view documentation](http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view).
  58430. */
  58431. IonicModule
  58432. .directive('ionNavView', [
  58433. '$state',
  58434. '$ionicConfig',
  58435. function($state, $ionicConfig) {
  58436. // IONIC's fork of Angular UI Router, v0.2.10
  58437. // the navView handles registering views in the history and how to transition between them
  58438. return {
  58439. restrict: 'E',
  58440. terminal: true,
  58441. priority: 2000,
  58442. transclude: true,
  58443. controller: '$ionicNavView',
  58444. compile: function(tElement, tAttrs, transclude) {
  58445. // a nav view element is a container for numerous views
  58446. tElement.addClass('view-container');
  58447. ionic.DomUtil.cachedAttr(tElement, 'nav-view-transition', $ionicConfig.views.transition());
  58448. return function($scope, $element, $attr, navViewCtrl) {
  58449. var latestLocals;
  58450. // Put in the compiled initial view
  58451. transclude($scope, function(clone) {
  58452. $element.append(clone);
  58453. });
  58454. var viewData = navViewCtrl.init();
  58455. // listen for $stateChangeSuccess
  58456. $scope.$on('$stateChangeSuccess', function() {
  58457. updateView(false);
  58458. });
  58459. $scope.$on('$viewContentLoading', function() {
  58460. updateView(false);
  58461. });
  58462. // initial load, ready go
  58463. updateView(true);
  58464. function updateView(firstTime) {
  58465. // get the current local according to the $state
  58466. var viewLocals = $state.$current && $state.$current.locals[viewData.name];
  58467. // do not update THIS nav-view if its is not the container for the given state
  58468. // if the viewLocals are the same as THIS latestLocals, then nothing to do
  58469. if (!viewLocals || (!firstTime && viewLocals === latestLocals)) return;
  58470. // update the latestLocals
  58471. latestLocals = viewLocals;
  58472. viewData.state = viewLocals.$$state;
  58473. // register, update and transition to the new view
  58474. navViewCtrl.register(viewLocals);
  58475. }
  58476. };
  58477. }
  58478. };
  58479. }]);
  58480. IonicModule
  58481. .config(['$provide', function($provide) {
  58482. $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
  58483. // drop the default ngClick directive
  58484. $delegate.shift();
  58485. return $delegate;
  58486. }]);
  58487. }])
  58488. /**
  58489. * @private
  58490. */
  58491. .factory('$ionicNgClick', ['$parse', function($parse) {
  58492. return function(scope, element, clickExpr) {
  58493. var clickHandler = angular.isFunction(clickExpr) ?
  58494. clickExpr :
  58495. $parse(clickExpr);
  58496. element.on('click', function(event) {
  58497. scope.$apply(function() {
  58498. clickHandler(scope, {$event: (event)});
  58499. });
  58500. });
  58501. // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click
  58502. // something else nearby.
  58503. element.onclick = noop;
  58504. };
  58505. }])
  58506. .directive('ngClick', ['$ionicNgClick', function($ionicNgClick) {
  58507. return function(scope, element, attr) {
  58508. $ionicNgClick(scope, element, attr.ngClick);
  58509. };
  58510. }])
  58511. .directive('ionStopEvent', function() {
  58512. return {
  58513. restrict: 'A',
  58514. link: function(scope, element, attr) {
  58515. element.bind(attr.ionStopEvent, eventStopPropagation);
  58516. }
  58517. };
  58518. });
  58519. function eventStopPropagation(e) {
  58520. e.stopPropagation();
  58521. }
  58522. /**
  58523. * @ngdoc directive
  58524. * @name ionPane
  58525. * @module ionic
  58526. * @restrict E
  58527. *
  58528. * @description A simple container that fits content, with no side effects. Adds the 'pane' class to the element.
  58529. */
  58530. IonicModule
  58531. .directive('ionPane', function() {
  58532. return {
  58533. restrict: 'E',
  58534. link: function(scope, element) {
  58535. element.addClass('pane');
  58536. }
  58537. };
  58538. });
  58539. /*
  58540. * We don't document the ionPopover directive, we instead document
  58541. * the $ionicPopover service
  58542. */
  58543. IonicModule
  58544. .directive('ionPopover', [function() {
  58545. return {
  58546. restrict: 'E',
  58547. transclude: true,
  58548. replace: true,
  58549. controller: [function() {}],
  58550. template: '<div class="popover-backdrop">' +
  58551. '<div class="popover-wrapper" ng-transclude></div>' +
  58552. '</div>'
  58553. };
  58554. }]);
  58555. IonicModule
  58556. .directive('ionPopoverView', function() {
  58557. return {
  58558. restrict: 'E',
  58559. compile: function(element) {
  58560. element.append(jqLite('<div class="popover-arrow">'));
  58561. element.addClass('popover');
  58562. }
  58563. };
  58564. });
  58565. /**
  58566. * @ngdoc directive
  58567. * @name ionRadio
  58568. * @module ionic
  58569. * @restrict E
  58570. * @codepen saoBG
  58571. * @description
  58572. * The radio directive is no different than the HTML radio input, except it's styled differently.
  58573. *
  58574. * Radio behaves like [AngularJS radio](http://docs.angularjs.org/api/ng/input/input[radio]).
  58575. *
  58576. * @usage
  58577. * ```html
  58578. * <ion-radio ng-model="choice" ng-value="'A'">Choose A</ion-radio>
  58579. * <ion-radio ng-model="choice" ng-value="'B'">Choose B</ion-radio>
  58580. * <ion-radio ng-model="choice" ng-value="'C'">Choose C</ion-radio>
  58581. * ```
  58582. *
  58583. * @param {string=} name The name of the radio input.
  58584. * @param {expression=} value The value of the radio input.
  58585. * @param {boolean=} disabled The state of the radio input.
  58586. * @param {string=} icon The icon to use when the radio input is selected.
  58587. * @param {expression=} ng-value Angular equivalent of the value attribute.
  58588. * @param {expression=} ng-model The angular model for the radio input.
  58589. * @param {boolean=} ng-disabled Angular equivalent of the disabled attribute.
  58590. * @param {expression=} ng-change Triggers given expression when radio input's model changes
  58591. */
  58592. IonicModule
  58593. .directive('ionRadio', function() {
  58594. return {
  58595. restrict: 'E',
  58596. replace: true,
  58597. require: '?ngModel',
  58598. transclude: true,
  58599. template:
  58600. '<label class="item item-radio">' +
  58601. '<input type="radio" name="radio-group">' +
  58602. '<div class="radio-content">' +
  58603. '<div class="item-content disable-pointer-events" ng-transclude></div>' +
  58604. '<i class="radio-icon disable-pointer-events icon ion-checkmark"></i>' +
  58605. '</div>' +
  58606. '</label>',
  58607. compile: function(element, attr) {
  58608. if (attr.icon) {
  58609. var iconElm = element.find('i');
  58610. iconElm.removeClass('ion-checkmark').addClass(attr.icon);
  58611. }
  58612. var input = element.find('input');
  58613. forEach({
  58614. 'name': attr.name,
  58615. 'value': attr.value,
  58616. 'disabled': attr.disabled,
  58617. 'ng-value': attr.ngValue,
  58618. 'ng-model': attr.ngModel,
  58619. 'ng-disabled': attr.ngDisabled,
  58620. 'ng-change': attr.ngChange,
  58621. 'ng-required': attr.ngRequired,
  58622. 'required': attr.required
  58623. }, function(value, name) {
  58624. if (isDefined(value)) {
  58625. input.attr(name, value);
  58626. }
  58627. });
  58628. return function(scope, element, attr) {
  58629. scope.getValue = function() {
  58630. return scope.ngValue || attr.value;
  58631. };
  58632. };
  58633. }
  58634. };
  58635. });
  58636. /**
  58637. * @ngdoc directive
  58638. * @name ionRefresher
  58639. * @module ionic
  58640. * @restrict E
  58641. * @parent ionic.directive:ionContent, ionic.directive:ionScroll
  58642. * @description
  58643. * Allows you to add pull-to-refresh to a scrollView.
  58644. *
  58645. * Place it as the first child of your {@link ionic.directive:ionContent} or
  58646. * {@link ionic.directive:ionScroll} element.
  58647. *
  58648. * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event
  58649. * from your controller.
  58650. *
  58651. * @usage
  58652. *
  58653. * ```html
  58654. * <ion-content ng-controller="MyController">
  58655. * <ion-refresher
  58656. * pulling-text="Pull to refresh..."
  58657. * on-refresh="doRefresh()">
  58658. * </ion-refresher>
  58659. * <ion-list>
  58660. * <ion-item ng-repeat="item in items"></ion-item>
  58661. * </ion-list>
  58662. * </ion-content>
  58663. * ```
  58664. * ```js
  58665. * angular.module('testApp', ['ionic'])
  58666. * .controller('MyController', function($scope, $http) {
  58667. * $scope.items = [1,2,3];
  58668. * $scope.doRefresh = function() {
  58669. * $http.get('/new-items')
  58670. * .success(function(newItems) {
  58671. * $scope.items = newItems;
  58672. * })
  58673. * .finally(function() {
  58674. * // Stop the ion-refresher from spinning
  58675. * $scope.$broadcast('scroll.refreshComplete');
  58676. * });
  58677. * };
  58678. * });
  58679. * ```
  58680. *
  58681. * @param {expression=} on-refresh Called when the user pulls down enough and lets go
  58682. * of the refresher.
  58683. * @param {expression=} on-pulling Called when the user starts to pull down
  58684. * on the refresher.
  58685. * @param {string=} pulling-text The text to display while the user is pulling down.
  58686. * @param {string=} pulling-icon The icon to display while the user is pulling down.
  58687. * Default: 'ion-android-arrow-down'.
  58688. * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display
  58689. * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}
  58690. * is now the default, replacing rotating font icons. Set to `none` to disable both the
  58691. * spinner and the icon.
  58692. * @param {string=} refreshing-icon The font icon to display after user lets go of the
  58693. * refresher. This is deprecated in favor of the SVG {@link ionic.directive:ionSpinner}.
  58694. * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling
  58695. * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.
  58696. *
  58697. */
  58698. IonicModule
  58699. .directive('ionRefresher', [function() {
  58700. return {
  58701. restrict: 'E',
  58702. replace: true,
  58703. require: ['?^$ionicScroll', 'ionRefresher'],
  58704. controller: '$ionicRefresher',
  58705. template:
  58706. '<div class="scroll-refresher invisible" collection-repeat-ignore>' +
  58707. '<div class="ionic-refresher-content" ' +
  58708. 'ng-class="{\'ionic-refresher-with-text\': pullingText || refreshingText}">' +
  58709. '<div class="icon-pulling" ng-class="{\'pulling-rotation-disabled\':disablePullingRotation}">' +
  58710. '<i class="icon {{pullingIcon}}"></i>' +
  58711. '</div>' +
  58712. '<div class="text-pulling" ng-bind-html="pullingText"></div>' +
  58713. '<div class="icon-refreshing">' +
  58714. '<ion-spinner ng-if="showSpinner" icon="{{spinner}}"></ion-spinner>' +
  58715. '<i ng-if="showIcon" class="icon {{refreshingIcon}}"></i>' +
  58716. '</div>' +
  58717. '<div class="text-refreshing" ng-bind-html="refreshingText"></div>' +
  58718. '</div>' +
  58719. '</div>',
  58720. link: function($scope, $element, $attrs, ctrls) {
  58721. // JS Scrolling uses the scroll controller
  58722. var scrollCtrl = ctrls[0],
  58723. refresherCtrl = ctrls[1];
  58724. if (!scrollCtrl || scrollCtrl.isNative()) {
  58725. // Kick off native scrolling
  58726. refresherCtrl.init();
  58727. } else {
  58728. $element[0].classList.add('js-scrolling');
  58729. scrollCtrl._setRefresher(
  58730. $scope,
  58731. $element[0],
  58732. refresherCtrl.getRefresherDomMethods()
  58733. );
  58734. $scope.$on('scroll.refreshComplete', function() {
  58735. $scope.$evalAsync(function() {
  58736. if(scrollCtrl.scrollView){
  58737. scrollCtrl.scrollView.finishPullToRefresh();
  58738. }
  58739. });
  58740. });
  58741. }
  58742. }
  58743. };
  58744. }]);
  58745. /**
  58746. * @ngdoc directive
  58747. * @name ionScroll
  58748. * @module ionic
  58749. * @delegate ionic.service:$ionicScrollDelegate
  58750. * @codepen mwFuh
  58751. * @restrict E
  58752. *
  58753. * @description
  58754. * Creates a scrollable container for all content inside.
  58755. *
  58756. * @usage
  58757. *
  58758. * Basic usage:
  58759. *
  58760. * ```html
  58761. * <ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px">
  58762. * <div style="width: 5000px; height: 5000px; background: url('https://upload.wikimedia.org/wikipedia/commons/a/ad/Europe_geological_map-en.jpg') repeat"></div>
  58763. * </ion-scroll>
  58764. * ```
  58765. *
  58766. * Note that it's important to set the height of the scroll box as well as the height of the inner
  58767. * content to enable scrolling. This makes it possible to have full control over scrollable areas.
  58768. *
  58769. * If you'd just like to have a center content scrolling area, use {@link ionic.directive:ionContent} instead.
  58770. *
  58771. * @param {string=} delegate-handle The handle used to identify this scrollView
  58772. * with {@link ionic.service:$ionicScrollDelegate}.
  58773. * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.
  58774. * @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.
  58775. * @param {boolean=} paging Whether to scroll with paging.
  58776. * @param {expression=} on-refresh Called on pull-to-refresh, triggered by an {@link ionic.directive:ionRefresher}.
  58777. * @param {expression=} on-scroll Called whenever the user scrolls.
  58778. * @param {expression=} on-scroll-complete Called whenever the scrolling paging is completed.
  58779. * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.
  58780. * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.
  58781. * @param {boolean=} zooming Whether to support pinch-to-zoom
  58782. * @param {integer=} min-zoom The smallest zoom amount allowed (default is 0.5)
  58783. * @param {integer=} max-zoom The largest zoom amount allowed (default is 3)
  58784. * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges
  58785. * of the content. Defaults to true on iOS, false on Android.
  58786. */
  58787. IonicModule
  58788. .directive('ionScroll', [
  58789. '$timeout',
  58790. '$controller',
  58791. '$ionicBind',
  58792. '$ionicConfig',
  58793. function($timeout, $controller, $ionicBind, $ionicConfig) {
  58794. return {
  58795. restrict: 'E',
  58796. scope: true,
  58797. controller: function() {},
  58798. compile: function(element, attr) {
  58799. element.addClass('scroll-view ionic-scroll');
  58800. //We cannot transclude here because it breaks element.data() inheritance on compile
  58801. var innerElement = jqLite('<div class="scroll"></div>');
  58802. innerElement.append(element.contents());
  58803. element.append(innerElement);
  58804. var nativeScrolling = attr.overflowScroll !== "false" && (attr.overflowScroll === "true" || !$ionicConfig.scrolling.jsScrolling());
  58805. return { pre: prelink };
  58806. function prelink($scope, $element, $attr) {
  58807. $ionicBind($scope, $attr, {
  58808. direction: '@',
  58809. paging: '@',
  58810. $onScroll: '&onScroll',
  58811. $onScrollComplete: '&onScrollComplete',
  58812. scroll: '@',
  58813. scrollbarX: '@',
  58814. scrollbarY: '@',
  58815. zooming: '@',
  58816. minZoom: '@',
  58817. maxZoom: '@'
  58818. });
  58819. $scope.direction = $scope.direction || 'y';
  58820. if (isDefined($attr.padding)) {
  58821. $scope.$watch($attr.padding, function(newVal) {
  58822. innerElement.toggleClass('padding', !!newVal);
  58823. });
  58824. }
  58825. if ($scope.$eval($scope.paging) === true) {
  58826. innerElement.addClass('scroll-paging');
  58827. }
  58828. if (!$scope.direction) { $scope.direction = 'y'; }
  58829. var isPaging = $scope.$eval($scope.paging) === true;
  58830. if (nativeScrolling) {
  58831. $element.addClass('overflow-scroll');
  58832. }
  58833. $element.addClass('scroll-' + $scope.direction);
  58834. var scrollViewOptions = {
  58835. el: $element[0],
  58836. delegateHandle: $attr.delegateHandle,
  58837. locking: ($attr.locking || 'true') === 'true',
  58838. bouncing: $scope.$eval($attr.hasBouncing),
  58839. paging: isPaging,
  58840. scrollbarX: $scope.$eval($scope.scrollbarX) !== false,
  58841. scrollbarY: $scope.$eval($scope.scrollbarY) !== false,
  58842. scrollingX: $scope.direction.indexOf('x') >= 0,
  58843. scrollingY: $scope.direction.indexOf('y') >= 0,
  58844. zooming: $scope.$eval($scope.zooming) === true,
  58845. maxZoom: $scope.$eval($scope.maxZoom) || 3,
  58846. minZoom: $scope.$eval($scope.minZoom) || 0.5,
  58847. preventDefault: true,
  58848. nativeScrolling: nativeScrolling,
  58849. scrollingComplete: onScrollComplete
  58850. };
  58851. if (isPaging) {
  58852. scrollViewOptions.speedMultiplier = 0.8;
  58853. scrollViewOptions.bouncing = false;
  58854. }
  58855. var scrollCtrl = $controller('$ionicScroll', {
  58856. $scope: $scope,
  58857. scrollViewOptions: scrollViewOptions
  58858. });
  58859. function onScrollComplete() {
  58860. $scope.$onScrollComplete && $scope.$onScrollComplete({
  58861. scrollTop: scrollCtrl.scrollView.__scrollTop,
  58862. scrollLeft: scrollCtrl.scrollView.__scrollLeft
  58863. });
  58864. }
  58865. }
  58866. }
  58867. };
  58868. }]);
  58869. /**
  58870. * @ngdoc directive
  58871. * @name ionSideMenu
  58872. * @module ionic
  58873. * @restrict E
  58874. * @parent ionic.directive:ionSideMenus
  58875. *
  58876. * @description
  58877. * A container for a side menu, sibling to an {@link ionic.directive:ionSideMenuContent} directive.
  58878. *
  58879. * @usage
  58880. * ```html
  58881. * <ion-side-menu
  58882. * side="left"
  58883. * width="myWidthValue + 20"
  58884. * is-enabled="shouldLeftSideMenuBeEnabled()">
  58885. * </ion-side-menu>
  58886. * ```
  58887. * For a complete side menu example, see the
  58888. * {@link ionic.directive:ionSideMenus} documentation.
  58889. *
  58890. * @param {string} side Which side the side menu is currently on. Allowed values: 'left' or 'right'.
  58891. * @param {boolean=} is-enabled Whether this side menu is enabled.
  58892. * @param {number=} width How many pixels wide the side menu should be. Defaults to 275.
  58893. */
  58894. IonicModule
  58895. .directive('ionSideMenu', function() {
  58896. return {
  58897. restrict: 'E',
  58898. require: '^ionSideMenus',
  58899. scope: true,
  58900. compile: function(element, attr) {
  58901. angular.isUndefined(attr.isEnabled) && attr.$set('isEnabled', 'true');
  58902. angular.isUndefined(attr.width) && attr.$set('width', '275');
  58903. element.addClass('menu menu-' + attr.side);
  58904. return function($scope, $element, $attr, sideMenuCtrl) {
  58905. $scope.side = $attr.side || 'left';
  58906. var sideMenu = sideMenuCtrl[$scope.side] = new ionic.views.SideMenu({
  58907. width: attr.width,
  58908. el: $element[0],
  58909. isEnabled: true
  58910. });
  58911. $scope.$watch($attr.width, function(val) {
  58912. var numberVal = +val;
  58913. if (numberVal && numberVal == val) {
  58914. sideMenu.setWidth(+val);
  58915. }
  58916. });
  58917. $scope.$watch($attr.isEnabled, function(val) {
  58918. sideMenu.setIsEnabled(!!val);
  58919. });
  58920. };
  58921. }
  58922. };
  58923. });
  58924. /**
  58925. * @ngdoc directive
  58926. * @name ionSideMenuContent
  58927. * @module ionic
  58928. * @restrict E
  58929. * @parent ionic.directive:ionSideMenus
  58930. *
  58931. * @description
  58932. * A container for the main visible content, sibling to one or more
  58933. * {@link ionic.directive:ionSideMenu} directives.
  58934. *
  58935. * @usage
  58936. * ```html
  58937. * <ion-side-menu-content
  58938. * edge-drag-threshold="true"
  58939. * drag-content="true">
  58940. * </ion-side-menu-content>
  58941. * ```
  58942. * For a complete side menu example, see the
  58943. * {@link ionic.directive:ionSideMenus} documentation.
  58944. *
  58945. * @param {boolean=} drag-content Whether the content can be dragged. Default true.
  58946. * @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:
  58947. * - 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.
  58948. * - If true is given, the default number of pixels (25) is used as the maximum allowed distance.
  58949. * - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.
  58950. *
  58951. */
  58952. IonicModule
  58953. .directive('ionSideMenuContent', [
  58954. '$timeout',
  58955. '$ionicGesture',
  58956. '$window',
  58957. function($timeout, $ionicGesture, $window) {
  58958. return {
  58959. restrict: 'EA', //DEPRECATED 'A'
  58960. require: '^ionSideMenus',
  58961. scope: true,
  58962. compile: function(element, attr) {
  58963. element.addClass('menu-content pane');
  58964. return { pre: prelink };
  58965. function prelink($scope, $element, $attr, sideMenuCtrl) {
  58966. var startCoord = null;
  58967. var primaryScrollAxis = null;
  58968. if (isDefined(attr.dragContent)) {
  58969. $scope.$watch(attr.dragContent, function(value) {
  58970. sideMenuCtrl.canDragContent(value);
  58971. });
  58972. } else {
  58973. sideMenuCtrl.canDragContent(true);
  58974. }
  58975. if (isDefined(attr.edgeDragThreshold)) {
  58976. $scope.$watch(attr.edgeDragThreshold, function(value) {
  58977. sideMenuCtrl.edgeDragThreshold(value);
  58978. });
  58979. }
  58980. // Listen for taps on the content to close the menu
  58981. function onContentTap(gestureEvt) {
  58982. if (sideMenuCtrl.getOpenAmount() !== 0) {
  58983. sideMenuCtrl.close();
  58984. gestureEvt.gesture.srcEvent.preventDefault();
  58985. startCoord = null;
  58986. primaryScrollAxis = null;
  58987. } else if (!startCoord) {
  58988. startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  58989. }
  58990. }
  58991. function onDragX(e) {
  58992. if (!sideMenuCtrl.isDraggableTarget(e)) return;
  58993. if (getPrimaryScrollAxis(e) == 'x') {
  58994. sideMenuCtrl._handleDrag(e);
  58995. e.gesture.srcEvent.preventDefault();
  58996. }
  58997. }
  58998. function onDragY(e) {
  58999. if (getPrimaryScrollAxis(e) == 'x') {
  59000. e.gesture.srcEvent.preventDefault();
  59001. }
  59002. }
  59003. function onDragRelease(e) {
  59004. sideMenuCtrl._endDrag(e);
  59005. startCoord = null;
  59006. primaryScrollAxis = null;
  59007. }
  59008. function getPrimaryScrollAxis(gestureEvt) {
  59009. // gets whether the user is primarily scrolling on the X or Y
  59010. // If a majority of the drag has been on the Y since the start of
  59011. // the drag, but the X has moved a little bit, it's still a Y drag
  59012. if (primaryScrollAxis) {
  59013. // we already figured out which way they're scrolling
  59014. return primaryScrollAxis;
  59015. }
  59016. if (gestureEvt && gestureEvt.gesture) {
  59017. if (!startCoord) {
  59018. // get the starting point
  59019. startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  59020. } else {
  59021. // we already have a starting point, figure out which direction they're going
  59022. var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);
  59023. var xDistance = Math.abs(endCoord.x - startCoord.x);
  59024. var yDistance = Math.abs(endCoord.y - startCoord.y);
  59025. var scrollAxis = (xDistance < yDistance ? 'y' : 'x');
  59026. if (Math.max(xDistance, yDistance) > 30) {
  59027. // ok, we pretty much know which way they're going
  59028. // let's lock it in
  59029. primaryScrollAxis = scrollAxis;
  59030. }
  59031. return scrollAxis;
  59032. }
  59033. }
  59034. return 'y';
  59035. }
  59036. var content = {
  59037. element: element[0],
  59038. onDrag: function() {},
  59039. endDrag: function() {},
  59040. setCanScroll: function(canScroll) {
  59041. var c = $element[0].querySelector('.scroll');
  59042. if (!c) {
  59043. return;
  59044. }
  59045. var content = angular.element(c.parentElement);
  59046. if (!content) {
  59047. return;
  59048. }
  59049. // freeze our scroll container if we have one
  59050. var scrollScope = content.scope();
  59051. scrollScope.scrollCtrl && scrollScope.scrollCtrl.freezeScrollShut(!canScroll);
  59052. },
  59053. getTranslateX: function() {
  59054. return $scope.sideMenuContentTranslateX || 0;
  59055. },
  59056. setTranslateX: ionic.animationFrameThrottle(function(amount) {
  59057. var xTransform = content.offsetX + amount;
  59058. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + xTransform + 'px,0,0)';
  59059. $timeout(function() {
  59060. $scope.sideMenuContentTranslateX = amount;
  59061. });
  59062. }),
  59063. setMarginLeft: ionic.animationFrameThrottle(function(amount) {
  59064. if (amount) {
  59065. amount = parseInt(amount, 10);
  59066. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px,0,0)';
  59067. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59068. content.offsetX = amount;
  59069. } else {
  59070. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59071. $element[0].style.width = '';
  59072. content.offsetX = 0;
  59073. }
  59074. }),
  59075. setMarginRight: ionic.animationFrameThrottle(function(amount) {
  59076. if (amount) {
  59077. amount = parseInt(amount, 10);
  59078. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59079. content.offsetX = amount;
  59080. } else {
  59081. $element[0].style.width = '';
  59082. content.offsetX = 0;
  59083. }
  59084. // reset incase left gets grabby
  59085. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59086. }),
  59087. setMarginLeftAndRight: ionic.animationFrameThrottle(function(amountLeft, amountRight) {
  59088. amountLeft = amountLeft && parseInt(amountLeft, 10) || 0;
  59089. amountRight = amountRight && parseInt(amountRight, 10) || 0;
  59090. var amount = amountLeft + amountRight;
  59091. if (amount > 0) {
  59092. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amountLeft + 'px,0,0)';
  59093. $element[0].style.width = ($window.innerWidth - amount) + 'px';
  59094. content.offsetX = amountLeft;
  59095. } else {
  59096. $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59097. $element[0].style.width = '';
  59098. content.offsetX = 0;
  59099. }
  59100. // reset incase left gets grabby
  59101. //$element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';
  59102. }),
  59103. enableAnimation: function() {
  59104. $scope.animationEnabled = true;
  59105. $element[0].classList.add('menu-animated');
  59106. },
  59107. disableAnimation: function() {
  59108. $scope.animationEnabled = false;
  59109. $element[0].classList.remove('menu-animated');
  59110. },
  59111. offsetX: 0
  59112. };
  59113. sideMenuCtrl.setContent(content);
  59114. // add gesture handlers
  59115. var gestureOpts = { stop_browser_behavior: false };
  59116. gestureOpts.prevent_default_directions = ['left', 'right'];
  59117. var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element, gestureOpts);
  59118. var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element, gestureOpts);
  59119. var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element, gestureOpts);
  59120. var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element, gestureOpts);
  59121. var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element, gestureOpts);
  59122. var releaseGesture = $ionicGesture.on('release', onDragRelease, $element, gestureOpts);
  59123. // Cleanup
  59124. $scope.$on('$destroy', function() {
  59125. if (content) {
  59126. content.element = null;
  59127. content = null;
  59128. }
  59129. $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);
  59130. $ionicGesture.off(dragRightGesture, 'dragright', onDragX);
  59131. $ionicGesture.off(dragUpGesture, 'dragup', onDragY);
  59132. $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);
  59133. $ionicGesture.off(releaseGesture, 'release', onDragRelease);
  59134. $ionicGesture.off(contentTapGesture, 'tap', onContentTap);
  59135. });
  59136. }
  59137. }
  59138. };
  59139. }]);
  59140. IonicModule
  59141. /**
  59142. * @ngdoc directive
  59143. * @name ionSideMenus
  59144. * @module ionic
  59145. * @delegate ionic.service:$ionicSideMenuDelegate
  59146. * @restrict E
  59147. *
  59148. * @description
  59149. * A container element for side menu(s) and the main content. Allows the left and/or right side menu
  59150. * to be toggled by dragging the main content area side to side.
  59151. *
  59152. * To automatically close an opened menu, you can add the {@link ionic.directive:menuClose} attribute
  59153. * directive. The `menu-close` attribute is usually added to links and buttons within
  59154. * `ion-side-menu-content`, so that when the element is clicked, the opened side menu will
  59155. * automatically close.
  59156. *
  59157. * "Burger Icon" toggles can be added to the header with the {@link ionic.directive:menuToggle}
  59158. * attribute directive. Clicking the toggle will open and close the side menu like the `menu-close`
  59159. * directive. The side menu will automatically hide on child pages, but can be overridden with the
  59160. * enable-menu-with-back-views attribute mentioned below.
  59161. *
  59162. * By default, side menus are hidden underneath their side menu content and can be opened by swiping
  59163. * the content left or right or by toggling a button to show the side menu. Additionally, by adding the
  59164. * {@link ionic.directive:exposeAsideWhen} attribute directive to an
  59165. * {@link ionic.directive:ionSideMenu} element directive, a side menu can be given instructions about
  59166. * "when" the menu should be exposed (always viewable).
  59167. *
  59168. * ![Side Menu](http://ionicframework.com.s3.amazonaws.com/docs/controllers/sidemenu.gif)
  59169. *
  59170. * For more information on side menus, check out:
  59171. *
  59172. * - {@link ionic.directive:ionSideMenuContent}
  59173. * - {@link ionic.directive:ionSideMenu}
  59174. * - {@link ionic.directive:menuToggle}
  59175. * - {@link ionic.directive:menuClose}
  59176. * - {@link ionic.directive:exposeAsideWhen}
  59177. *
  59178. * @usage
  59179. * To use side menus, add an `<ion-side-menus>` parent element. This will encompass all pages that have a
  59180. * side menu, and have at least 2 child elements: 1 `<ion-side-menu-content>` for the center content,
  59181. * and one or more `<ion-side-menu>` directives for each side menu(left/right) that you wish to place.
  59182. *
  59183. * ```html
  59184. * <ion-side-menus>
  59185. * <!-- Left menu -->
  59186. * <ion-side-menu side="left">
  59187. * </ion-side-menu>
  59188. *
  59189. * <ion-side-menu-content>
  59190. * <!-- Main content, usually <ion-nav-view> -->
  59191. * </ion-side-menu-content>
  59192. *
  59193. * <!-- Right menu -->
  59194. * <ion-side-menu side="right">
  59195. * </ion-side-menu>
  59196. *
  59197. * </ion-side-menus>
  59198. * ```
  59199. * ```js
  59200. * function ContentController($scope, $ionicSideMenuDelegate) {
  59201. * $scope.toggleLeft = function() {
  59202. * $ionicSideMenuDelegate.toggleLeft();
  59203. * };
  59204. * }
  59205. * ```
  59206. *
  59207. * @param {bool=} enable-menu-with-back-views Determines whether the side menu is enabled when the
  59208. * back button is showing. When set to `false`, any {@link ionic.directive:menuToggle} will be hidden,
  59209. * and the user cannot swipe to open the menu. When going back to the root page of the side menu (the
  59210. * page without a back button visible), then any menuToggle buttons will show again, and menus will be
  59211. * enabled again.
  59212. * @param {string=} delegate-handle The handle used to identify this side menu
  59213. * with {@link ionic.service:$ionicSideMenuDelegate}.
  59214. *
  59215. */
  59216. .directive('ionSideMenus', ['$ionicBody', function($ionicBody) {
  59217. return {
  59218. restrict: 'ECA',
  59219. controller: '$ionicSideMenus',
  59220. compile: function(element, attr) {
  59221. attr.$set('class', (attr['class'] || '') + ' view');
  59222. return { pre: prelink };
  59223. function prelink($scope, $element, $attrs, ctrl) {
  59224. ctrl.enableMenuWithBackViews($scope.$eval($attrs.enableMenuWithBackViews));
  59225. $scope.$on('$ionicExposeAside', function(evt, isAsideExposed) {
  59226. if (!$scope.$exposeAside) $scope.$exposeAside = {};
  59227. $scope.$exposeAside.active = isAsideExposed;
  59228. $ionicBody.enableClass(isAsideExposed, 'aside-open');
  59229. });
  59230. $scope.$on('$ionicView.beforeEnter', function(ev, d) {
  59231. if (d.historyId) {
  59232. $scope.$activeHistoryId = d.historyId;
  59233. }
  59234. });
  59235. $scope.$on('$destroy', function() {
  59236. $ionicBody.removeClass('menu-open', 'aside-open');
  59237. });
  59238. }
  59239. }
  59240. };
  59241. }]);
  59242. /**
  59243. * @ngdoc directive
  59244. * @name ionSlideBox
  59245. * @module ionic
  59246. * @codepen AjgEB
  59247. * @deprecated will be removed in the next Ionic release in favor of the new ion-slides component.
  59248. * Don't depend on the internal behavior of this widget.
  59249. * @delegate ionic.service:$ionicSlideBoxDelegate
  59250. * @restrict E
  59251. * @description
  59252. * The Slide Box is a multi-page container where each page can be swiped or dragged between:
  59253. *
  59254. *
  59255. * @usage
  59256. * ```html
  59257. * <ion-slide-box on-slide-changed="slideHasChanged($index)">
  59258. * <ion-slide>
  59259. * <div class="box blue"><h1>BLUE</h1></div>
  59260. * </ion-slide>
  59261. * <ion-slide>
  59262. * <div class="box yellow"><h1>YELLOW</h1></div>
  59263. * </ion-slide>
  59264. * <ion-slide>
  59265. * <div class="box pink"><h1>PINK</h1></div>
  59266. * </ion-slide>
  59267. * </ion-slide-box>
  59268. * ```
  59269. *
  59270. * @param {string=} delegate-handle The handle used to identify this slideBox
  59271. * with {@link ionic.service:$ionicSlideBoxDelegate}.
  59272. * @param {boolean=} does-continue Whether the slide box should loop.
  59273. * @param {boolean=} auto-play Whether the slide box should automatically slide. Default true if does-continue is true.
  59274. * @param {number=} slide-interval How many milliseconds to wait to change slides (if does-continue is true). Defaults to 4000.
  59275. * @param {boolean=} show-pager Whether a pager should be shown for this slide box. Accepts expressions via `show-pager="{{shouldShow()}}"`. Defaults to true.
  59276. * @param {expression=} pager-click Expression to call when a pager is clicked (if show-pager is true). Is passed the 'index' variable.
  59277. * @param {expression=} on-slide-changed Expression called whenever the slide is changed. Is passed an '$index' variable.
  59278. * @param {expression=} active-slide Model to bind the current slide index to.
  59279. */
  59280. IonicModule
  59281. .directive('ionSlideBox', [
  59282. '$animate',
  59283. '$timeout',
  59284. '$compile',
  59285. '$ionicSlideBoxDelegate',
  59286. '$ionicHistory',
  59287. '$ionicScrollDelegate',
  59288. function($animate, $timeout, $compile, $ionicSlideBoxDelegate, $ionicHistory, $ionicScrollDelegate) {
  59289. return {
  59290. restrict: 'E',
  59291. replace: true,
  59292. transclude: true,
  59293. scope: {
  59294. autoPlay: '=',
  59295. doesContinue: '@',
  59296. slideInterval: '@',
  59297. showPager: '@',
  59298. pagerClick: '&',
  59299. disableScroll: '@',
  59300. onSlideChanged: '&',
  59301. activeSlide: '=?',
  59302. bounce: '@'
  59303. },
  59304. controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
  59305. var _this = this;
  59306. var continuous = $scope.$eval($scope.doesContinue) === true;
  59307. var bouncing = ($scope.$eval($scope.bounce) !== false); //Default to true
  59308. var shouldAutoPlay = isDefined($attrs.autoPlay) ? !!$scope.autoPlay : false;
  59309. var slideInterval = shouldAutoPlay ? $scope.$eval($scope.slideInterval) || 4000 : 0;
  59310. var slider = new ionic.views.Slider({
  59311. el: $element[0],
  59312. auto: slideInterval,
  59313. continuous: continuous,
  59314. startSlide: $scope.activeSlide,
  59315. bouncing: bouncing,
  59316. slidesChanged: function() {
  59317. $scope.currentSlide = slider.currentIndex();
  59318. // Try to trigger a digest
  59319. $timeout(function() {});
  59320. },
  59321. callback: function(slideIndex) {
  59322. $scope.currentSlide = slideIndex;
  59323. $scope.onSlideChanged({ index: $scope.currentSlide, $index: $scope.currentSlide});
  59324. $scope.$parent.$broadcast('slideBox.slideChanged', slideIndex);
  59325. $scope.activeSlide = slideIndex;
  59326. // Try to trigger a digest
  59327. $timeout(function() {});
  59328. },
  59329. onDrag: function() {
  59330. freezeAllScrolls(true);
  59331. },
  59332. onDragEnd: function() {
  59333. freezeAllScrolls(false);
  59334. }
  59335. });
  59336. function freezeAllScrolls(shouldFreeze) {
  59337. if (shouldFreeze && !_this.isScrollFreeze) {
  59338. $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);
  59339. } else if (!shouldFreeze && _this.isScrollFreeze) {
  59340. $ionicScrollDelegate.freezeAllScrolls(false);
  59341. }
  59342. _this.isScrollFreeze = shouldFreeze;
  59343. }
  59344. slider.enableSlide($scope.$eval($attrs.disableScroll) !== true);
  59345. $scope.$watch('activeSlide', function(nv) {
  59346. if (isDefined(nv)) {
  59347. slider.slide(nv);
  59348. }
  59349. });
  59350. $scope.$on('slideBox.nextSlide', function() {
  59351. slider.next();
  59352. });
  59353. $scope.$on('slideBox.prevSlide', function() {
  59354. slider.prev();
  59355. });
  59356. $scope.$on('slideBox.setSlide', function(e, index) {
  59357. slider.slide(index);
  59358. });
  59359. //Exposed for testing
  59360. this.__slider = slider;
  59361. var deregisterInstance = $ionicSlideBoxDelegate._registerInstance(
  59362. slider, $attrs.delegateHandle, function() {
  59363. return $ionicHistory.isActiveScope($scope);
  59364. }
  59365. );
  59366. $scope.$on('$destroy', function() {
  59367. deregisterInstance();
  59368. slider.kill();
  59369. });
  59370. this.slidesCount = function() {
  59371. return slider.slidesCount();
  59372. };
  59373. this.onPagerClick = function(index) {
  59374. $scope.pagerClick({index: index});
  59375. };
  59376. $timeout(function() {
  59377. slider.load();
  59378. });
  59379. }],
  59380. template: '<div class="slider">' +
  59381. '<div class="slider-slides" ng-transclude>' +
  59382. '</div>' +
  59383. '</div>',
  59384. link: function($scope, $element, $attr) {
  59385. // Disable ngAnimate for slidebox and its children
  59386. $animate.enabled($element, false);
  59387. // if showPager is undefined, show the pager
  59388. if (!isDefined($attr.showPager)) {
  59389. $scope.showPager = true;
  59390. getPager().toggleClass('hide', !true);
  59391. }
  59392. $attr.$observe('showPager', function(show) {
  59393. if (show === undefined) return;
  59394. show = $scope.$eval(show);
  59395. getPager().toggleClass('hide', !show);
  59396. });
  59397. var pager;
  59398. function getPager() {
  59399. if (!pager) {
  59400. var childScope = $scope.$new();
  59401. pager = jqLite('<ion-pager></ion-pager>');
  59402. $element.append(pager);
  59403. pager = $compile(pager)(childScope);
  59404. }
  59405. return pager;
  59406. }
  59407. }
  59408. };
  59409. }])
  59410. .directive('ionSlide', function() {
  59411. return {
  59412. restrict: 'E',
  59413. require: '?^ionSlideBox',
  59414. compile: function(element) {
  59415. element.addClass('slider-slide');
  59416. }
  59417. };
  59418. })
  59419. .directive('ionPager', function() {
  59420. return {
  59421. restrict: 'E',
  59422. replace: true,
  59423. require: '^ionSlideBox',
  59424. 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>',
  59425. link: function($scope, $element, $attr, slideBox) {
  59426. var selectPage = function(index) {
  59427. var children = $element[0].children;
  59428. var length = children.length;
  59429. for (var i = 0; i < length; i++) {
  59430. if (i == index) {
  59431. children[i].classList.add('active');
  59432. } else {
  59433. children[i].classList.remove('active');
  59434. }
  59435. }
  59436. };
  59437. $scope.pagerClick = function(index) {
  59438. slideBox.onPagerClick(index);
  59439. };
  59440. $scope.numSlides = function() {
  59441. return new Array(slideBox.slidesCount());
  59442. };
  59443. $scope.$watch('currentSlide', function(v) {
  59444. selectPage(v);
  59445. });
  59446. }
  59447. };
  59448. });
  59449. /**
  59450. * @ngdoc directive
  59451. * @name ionSlides
  59452. * @module ionic
  59453. * @restrict E
  59454. * @description
  59455. * The Slides component is a powerful multi-page container where each page can be swiped or dragged between.
  59456. *
  59457. * Note: this is a new version of the Ionic Slide Box based on the [Swiper](http://www.idangero.us/swiper/#.Vmc1J-ODFBc) widget from
  59458. * [idangerous](http://www.idangero.us/).
  59459. *
  59460. * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)
  59461. *
  59462. * @usage
  59463. * ```html
  59464. * <ion-content scroll="false">
  59465. * <ion-slides options="options" slider="data.slider">
  59466. * <ion-slide-page>
  59467. * <div class="box blue"><h1>BLUE</h1></div>
  59468. * </ion-slide-page>
  59469. * <ion-slide-page>
  59470. * <div class="box yellow"><h1>YELLOW</h1></div>
  59471. * </ion-slide-page>
  59472. * <ion-slide-page>
  59473. * <div class="box pink"><h1>PINK</h1></div>
  59474. * </ion-slide-page>
  59475. * </ion-slides>
  59476. * </ion-content>
  59477. * ```
  59478. *
  59479. * ```js
  59480. * $scope.options = {
  59481. * loop: false,
  59482. * effect: 'fade',
  59483. * speed: 500,
  59484. * }
  59485. *
  59486. * $scope.$on("$ionicSlides.sliderInitialized", function(event, data){
  59487. * // data.slider is the instance of Swiper
  59488. * $scope.slider = data.slider;
  59489. * });
  59490. *
  59491. * $scope.$on("$ionicSlides.slideChangeStart", function(event, data){
  59492. * console.log('Slide change is beginning');
  59493. * });
  59494. *
  59495. * $scope.$on("$ionicSlides.slideChangeEnd", function(event, data){
  59496. * // note: the indexes are 0-based
  59497. * $scope.activeIndex = data.slider.activeIndex;
  59498. * $scope.previousIndex = data.slider.previousIndex;
  59499. * });
  59500. *
  59501. * ```
  59502. *
  59503. * ## Slide Events
  59504. *
  59505. * The slides component dispatches events when the active slide changes
  59506. *
  59507. * <table class="table">
  59508. * <tr>
  59509. * <td><code>$ionicSlides.slideChangeStart</code></td>
  59510. * <td>This event is emitted when a slide change begins</td>
  59511. * </tr>
  59512. * <tr>
  59513. * <td><code>$ionicSlides.slideChangeEnd</code></td>
  59514. * <td>This event is emitted when a slide change completes</td>
  59515. * </tr>
  59516. * <tr>
  59517. * <td><code>$ionicSlides.sliderInitialized</code></td>
  59518. * <td>This event is emitted when the slider is initialized. It provides access to an instance of the slider.</td>
  59519. * </tr>
  59520. * </table>
  59521. *
  59522. *
  59523. * ## Updating Slides Dynamically
  59524. * When applying data to the slider at runtime, typically everything will work as expected.
  59525. *
  59526. * In the event that the slides are looped, use the `updateLoop` method on the slider to ensure the slides update correctly.
  59527. *
  59528. * ```
  59529. * $scope.$on("$ionicSlides.sliderInitialized", function(event, data){
  59530. * // grab an instance of the slider
  59531. * $scope.slider = data.slider;
  59532. * });
  59533. *
  59534. * function dataChangeHandler(){
  59535. * // call this function when data changes, such as an HTTP request, etc
  59536. * if ( $scope.slider ){
  59537. * $scope.slider.updateLoop();
  59538. * }
  59539. * }
  59540. * ```
  59541. *
  59542. */
  59543. IonicModule
  59544. .directive('ionSlides', [
  59545. '$animate',
  59546. '$timeout',
  59547. '$compile',
  59548. function($animate, $timeout, $compile) {
  59549. return {
  59550. restrict: 'E',
  59551. transclude: true,
  59552. scope: {
  59553. options: '=',
  59554. slider: '='
  59555. },
  59556. template: '<div class="swiper-container">' +
  59557. '<div class="swiper-wrapper" ng-transclude>' +
  59558. '</div>' +
  59559. '<div ng-hide="!showPager" class="swiper-pagination"></div>' +
  59560. '</div>',
  59561. controller: ['$scope', '$element', function($scope, $element) {
  59562. var _this = this;
  59563. this.update = function() {
  59564. $timeout(function() {
  59565. if (!_this.__slider) {
  59566. return;
  59567. }
  59568. _this.__slider.update();
  59569. if (_this._options.loop) {
  59570. _this.__slider.createLoop();
  59571. }
  59572. var slidesLength = _this.__slider.slides.length;
  59573. // Don't allow pager to show with > 10 slides
  59574. if (slidesLength > 10) {
  59575. $scope.showPager = false;
  59576. }
  59577. // When slide index is greater than total then slide to last index
  59578. if (_this.__slider.activeIndex > slidesLength - 1) {
  59579. _this.__slider.slideTo(slidesLength - 1);
  59580. }
  59581. });
  59582. };
  59583. this.rapidUpdate = ionic.debounce(function() {
  59584. _this.update();
  59585. }, 50);
  59586. this.getSlider = function() {
  59587. return _this.__slider;
  59588. };
  59589. var options = $scope.options || {};
  59590. var newOptions = angular.extend({
  59591. pagination: $element.children().children()[1],
  59592. paginationClickable: true,
  59593. lazyLoading: true,
  59594. preloadImages: false
  59595. }, options);
  59596. this._options = newOptions;
  59597. $timeout(function() {
  59598. var slider = new ionic.views.Swiper($element.children()[0], newOptions, $scope, $compile);
  59599. $scope.$emit("$ionicSlides.sliderInitialized", { slider: slider });
  59600. _this.__slider = slider;
  59601. $scope.slider = _this.__slider;
  59602. $scope.$on('$destroy', function() {
  59603. slider.destroy();
  59604. _this.__slider = null;
  59605. });
  59606. });
  59607. $timeout(function() {
  59608. // if it's a loop, render the slides again just incase
  59609. _this.rapidUpdate();
  59610. }, 200);
  59611. }],
  59612. link: function($scope) {
  59613. $scope.showPager = true;
  59614. // Disable ngAnimate for slidebox and its children
  59615. //$animate.enabled(false, $element);
  59616. }
  59617. };
  59618. }])
  59619. .directive('ionSlidePage', [function() {
  59620. return {
  59621. restrict: 'E',
  59622. require: '?^ionSlides',
  59623. transclude: true,
  59624. replace: true,
  59625. template: '<div class="swiper-slide" ng-transclude></div>',
  59626. link: function($scope, $element, $attr, ionSlidesCtrl) {
  59627. ionSlidesCtrl.rapidUpdate();
  59628. $scope.$on('$destroy', function() {
  59629. ionSlidesCtrl.rapidUpdate();
  59630. });
  59631. }
  59632. };
  59633. }]);
  59634. /**
  59635. * @ngdoc directive
  59636. * @name ionSpinner
  59637. * @module ionic
  59638. * @restrict E
  59639. *
  59640. * @description
  59641. * The `ionSpinner` directive provides a variety of animated spinners.
  59642. * Spinners enables you to give your users feedback that the app is
  59643. * processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.
  59644. * By default, the {@link ionic.directive:ionRefresher} feature uses this spinner, rather
  59645. * than rotating font icons (previously included in [ionicons](http://ionicons.com/)).
  59646. * While font icons are great for simple or stationary graphics, they're not suited to
  59647. * provide great animations, which is why Ionic uses SVG instead.
  59648. *
  59649. * Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner
  59650. * for the platform on which it's running. Under the hood, the `ionSpinner` directive dynamically
  59651. * builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs
  59652. * within 3KB.
  59653. *
  59654. * <style>
  59655. * .spinner-table {
  59656. * max-width: 280px;
  59657. * }
  59658. * .spinner-table tbody > tr > th, .spinner-table tbody > tr > td {
  59659. * vertical-align: middle;
  59660. * width: 42px;
  59661. * height: 42px;
  59662. * }
  59663. * .spinner {
  59664. * stroke: #444;
  59665. * fill: #444; }
  59666. * .spinner svg {
  59667. * width: 28px;
  59668. * height: 28px; }
  59669. * .spinner.spinner-inverse {
  59670. * stroke: #fff;
  59671. * fill: #fff; }
  59672. *
  59673. * .spinner-android {
  59674. * stroke: #4b8bf4; }
  59675. *
  59676. * .spinner-ios, .spinner-ios-small {
  59677. * stroke: #69717d; }
  59678. *
  59679. * .spinner-spiral .stop1 {
  59680. * stop-color: #fff;
  59681. * stop-opacity: 0; }
  59682. * .spinner-spiral.spinner-inverse .stop1 {
  59683. * stop-color: #000; }
  59684. * .spinner-spiral.spinner-inverse .stop2 {
  59685. * stop-color: #fff; }
  59686. * </style>
  59687. *
  59688. * <script src="http://code.ionicframework.com/nightly/js/ionic.bundle.min.js"></script>
  59689. * <table class="table spinner-table" ng-app="ionic">
  59690. * <tr>
  59691. * <th>
  59692. * <code>android</code>
  59693. * </th>
  59694. * <td>
  59695. * <ion-spinner icon="android"></ion-spinner>
  59696. * </td>
  59697. * </tr>
  59698. * <tr>
  59699. * <th>
  59700. * <code>ios</code>
  59701. * </th>
  59702. * <td>
  59703. * <ion-spinner icon="ios"></ion-spinner>
  59704. * </td>
  59705. * </tr>
  59706. * <tr>
  59707. * <th>
  59708. * <code>ios-small</code>
  59709. * </th>
  59710. * <td>
  59711. * <ion-spinner icon="ios-small"></ion-spinner>
  59712. * </td>
  59713. * </tr>
  59714. * <tr>
  59715. * <th>
  59716. * <code>bubbles</code>
  59717. * </th>
  59718. * <td>
  59719. * <ion-spinner icon="bubbles"></ion-spinner>
  59720. * </td>
  59721. * </tr>
  59722. * <tr>
  59723. * <th>
  59724. * <code>circles</code>
  59725. * </th>
  59726. * <td>
  59727. * <ion-spinner icon="circles"></ion-spinner>
  59728. * </td>
  59729. * </tr>
  59730. * <tr>
  59731. * <th>
  59732. * <code>crescent</code>
  59733. * </th>
  59734. * <td>
  59735. * <ion-spinner icon="crescent"></ion-spinner>
  59736. * </td>
  59737. * </tr>
  59738. * <tr>
  59739. * <th>
  59740. * <code>dots</code>
  59741. * </th>
  59742. * <td>
  59743. * <ion-spinner icon="dots"></ion-spinner>
  59744. * </td>
  59745. * </tr>
  59746. * <tr>
  59747. * <th>
  59748. * <code>lines</code>
  59749. * </th>
  59750. * <td>
  59751. * <ion-spinner icon="lines"></ion-spinner>
  59752. * </td>
  59753. * </tr>
  59754. * <tr>
  59755. * <th>
  59756. * <code>ripple</code>
  59757. * </th>
  59758. * <td>
  59759. * <ion-spinner icon="ripple"></ion-spinner>
  59760. * </td>
  59761. * </tr>
  59762. * <tr>
  59763. * <th>
  59764. * <code>spiral</code>
  59765. * </th>
  59766. * <td>
  59767. * <ion-spinner icon="spiral"></ion-spinner>
  59768. * </td>
  59769. * </tr>
  59770. * </table>
  59771. *
  59772. * Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript
  59773. * so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,
  59774. * and scaled to any size.
  59775. *
  59776. *
  59777. * @usage
  59778. * The following code would use the default spinner for the platform it's running from. If it's neither
  59779. * iOS or Android, it'll default to use `ios`.
  59780. *
  59781. * ```html
  59782. * <ion-spinner></ion-spinner>
  59783. * ```
  59784. *
  59785. * By setting the `icon` attribute, you can specify which spinner to use, no matter what
  59786. * the platform is.
  59787. *
  59788. * ```html
  59789. * <ion-spinner icon="spiral"></ion-spinner>
  59790. * ```
  59791. *
  59792. * ## Spinner Colors
  59793. * Like with most of Ionic's other components, spinners can also be styled using
  59794. * Ionic's standard color naming convention. For example:
  59795. *
  59796. * ```html
  59797. * <ion-spinner class="spinner-energized"></ion-spinner>
  59798. * ```
  59799. *
  59800. *
  59801. * ## Styling SVG with CSS
  59802. * One cool thing about SVG is its ability to be styled with CSS! Some of the properties
  59803. * have different names, for example, SVG uses the term `stroke` instead of `border`, and
  59804. * `fill` instead of `background-color`.
  59805. *
  59806. * ```css
  59807. * .spinner svg {
  59808. * width: 28px;
  59809. * height: 28px;
  59810. * stroke: #444;
  59811. * fill: #444;
  59812. * }
  59813. * ```
  59814. *
  59815. */
  59816. IonicModule
  59817. .directive('ionSpinner', function() {
  59818. return {
  59819. restrict: 'E',
  59820. controller: '$ionicSpinner',
  59821. link: function($scope, $element, $attrs, ctrl) {
  59822. var spinnerName = ctrl.init();
  59823. $element.addClass('spinner spinner-' + spinnerName);
  59824. $element.on('$destroy', function onDestroy() {
  59825. ctrl.stop();
  59826. });
  59827. }
  59828. };
  59829. });
  59830. /**
  59831. * @ngdoc directive
  59832. * @name ionTab
  59833. * @module ionic
  59834. * @restrict E
  59835. * @parent ionic.directive:ionTabs
  59836. *
  59837. * @description
  59838. * Contains a tab's content. The content only exists while the given tab is selected.
  59839. *
  59840. * Each ionTab has its own view history.
  59841. *
  59842. * @usage
  59843. * ```html
  59844. * <ion-tab
  59845. * title="Tab!"
  59846. * icon="my-icon"
  59847. * href="#/tab/tab-link"
  59848. * on-select="onTabSelected()"
  59849. * on-deselect="onTabDeselected()">
  59850. * </ion-tab>
  59851. * ```
  59852. * For a complete, working tab bar example, see the {@link ionic.directive:ionTabs} documentation.
  59853. *
  59854. * @param {string} title The title of the tab.
  59855. * @param {string=} href The link that this tab will navigate to when tapped.
  59856. * @param {string=} icon The icon of the tab. If given, this will become the default for icon-on and icon-off.
  59857. * @param {string=} icon-on The icon of the tab while it is selected.
  59858. * @param {string=} icon-off The icon of the tab while it is not selected.
  59859. * @param {expression=} badge The badge to put on this tab (usually a number).
  59860. * @param {expression=} badge-style The style of badge to put on this tab (eg: badge-positive).
  59861. * @param {expression=} on-select Called when this tab is selected.
  59862. * @param {expression=} on-deselect Called when this tab is deselected.
  59863. * @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()}.
  59864. * @param {expression=} hidden Whether the tab is to be hidden or not.
  59865. * @param {expression=} disabled Whether the tab is to be disabled or not.
  59866. */
  59867. IonicModule
  59868. .directive('ionTab', [
  59869. '$compile',
  59870. '$ionicConfig',
  59871. '$ionicBind',
  59872. '$ionicViewSwitcher',
  59873. function($compile, $ionicConfig, $ionicBind, $ionicViewSwitcher) {
  59874. //Returns ' key="value"' if value exists
  59875. function attrStr(k, v) {
  59876. return isDefined(v) ? ' ' + k + '="' + v + '"' : '';
  59877. }
  59878. return {
  59879. restrict: 'E',
  59880. require: ['^ionTabs', 'ionTab'],
  59881. controller: '$ionicTab',
  59882. scope: true,
  59883. compile: function(element, attr) {
  59884. //We create the tabNavTemplate in the compile phase so that the
  59885. //attributes we pass down won't be interpolated yet - we want
  59886. //to pass down the 'raw' versions of the attributes
  59887. var tabNavTemplate = '<ion-tab-nav' +
  59888. attrStr('ng-click', attr.ngClick) +
  59889. attrStr('title', attr.title) +
  59890. attrStr('icon', attr.icon) +
  59891. attrStr('icon-on', attr.iconOn) +
  59892. attrStr('icon-off', attr.iconOff) +
  59893. attrStr('badge', attr.badge) +
  59894. attrStr('badge-style', attr.badgeStyle) +
  59895. attrStr('hidden', attr.hidden) +
  59896. attrStr('disabled', attr.disabled) +
  59897. attrStr('class', attr['class']) +
  59898. '></ion-tab-nav>';
  59899. //Remove the contents of the element so we can compile them later, if tab is selected
  59900. var tabContentEle = document.createElement('div');
  59901. for (var x = 0; x < element[0].children.length; x++) {
  59902. tabContentEle.appendChild(element[0].children[x].cloneNode(true));
  59903. }
  59904. var childElementCount = tabContentEle.childElementCount;
  59905. element.empty();
  59906. var navViewName, isNavView;
  59907. if (childElementCount) {
  59908. if (tabContentEle.children[0].tagName === 'ION-NAV-VIEW') {
  59909. // get the name if it's a nav-view
  59910. navViewName = tabContentEle.children[0].getAttribute('name');
  59911. tabContentEle.children[0].classList.add('view-container');
  59912. isNavView = true;
  59913. }
  59914. if (childElementCount === 1) {
  59915. // make the 1 child element the primary tab content container
  59916. tabContentEle = tabContentEle.children[0];
  59917. }
  59918. if (!isNavView) tabContentEle.classList.add('pane');
  59919. tabContentEle.classList.add('tab-content');
  59920. }
  59921. return function link($scope, $element, $attr, ctrls) {
  59922. var childScope;
  59923. var childElement;
  59924. var tabsCtrl = ctrls[0];
  59925. var tabCtrl = ctrls[1];
  59926. var isTabContentAttached = false;
  59927. $scope.$tabSelected = false;
  59928. $ionicBind($scope, $attr, {
  59929. onSelect: '&',
  59930. onDeselect: '&',
  59931. title: '@',
  59932. uiSref: '@',
  59933. href: '@'
  59934. });
  59935. tabsCtrl.add($scope);
  59936. $scope.$on('$destroy', function() {
  59937. if (!$scope.$tabsDestroy) {
  59938. // if the containing ionTabs directive is being destroyed
  59939. // then don't bother going through the controllers remove
  59940. // method, since remove will reset the active tab as each tab
  59941. // is being destroyed, causing unnecessary view loads and transitions
  59942. tabsCtrl.remove($scope);
  59943. }
  59944. tabNavElement.isolateScope().$destroy();
  59945. tabNavElement.remove();
  59946. tabNavElement = tabContentEle = childElement = null;
  59947. });
  59948. //Remove title attribute so browser-tooltip does not apear
  59949. $element[0].removeAttribute('title');
  59950. if (navViewName) {
  59951. tabCtrl.navViewName = $scope.navViewName = navViewName;
  59952. }
  59953. $scope.$on('$stateChangeSuccess', selectIfMatchesState);
  59954. selectIfMatchesState();
  59955. function selectIfMatchesState() {
  59956. if (tabCtrl.tabMatchesState()) {
  59957. tabsCtrl.select($scope, false);
  59958. }
  59959. }
  59960. var tabNavElement = jqLite(tabNavTemplate);
  59961. tabNavElement.data('$ionTabsController', tabsCtrl);
  59962. tabNavElement.data('$ionTabController', tabCtrl);
  59963. tabsCtrl.$tabsElement.append($compile(tabNavElement)($scope));
  59964. function tabSelected(isSelected) {
  59965. if (isSelected && childElementCount) {
  59966. // this tab is being selected
  59967. // check if the tab is already in the DOM
  59968. // only do this if the tab has child elements
  59969. if (!isTabContentAttached) {
  59970. // tab should be selected and is NOT in the DOM
  59971. // create a new scope and append it
  59972. childScope = $scope.$new();
  59973. childElement = jqLite(tabContentEle);
  59974. $ionicViewSwitcher.viewEleIsActive(childElement, true);
  59975. tabsCtrl.$element.append(childElement);
  59976. $compile(childElement)(childScope);
  59977. isTabContentAttached = true;
  59978. }
  59979. // remove the hide class so the tabs content shows up
  59980. $ionicViewSwitcher.viewEleIsActive(childElement, true);
  59981. } else if (isTabContentAttached && childElement) {
  59982. // this tab should NOT be selected, and it is already in the DOM
  59983. if ($ionicConfig.views.maxCache() > 0) {
  59984. // keep the tabs in the DOM, only css hide it
  59985. $ionicViewSwitcher.viewEleIsActive(childElement, false);
  59986. } else {
  59987. // do not keep tabs in the DOM
  59988. destroyTab();
  59989. }
  59990. }
  59991. }
  59992. function destroyTab() {
  59993. childScope && childScope.$destroy();
  59994. isTabContentAttached && childElement && childElement.remove();
  59995. tabContentEle.innerHTML = '';
  59996. isTabContentAttached = childScope = childElement = null;
  59997. }
  59998. $scope.$watch('$tabSelected', tabSelected);
  59999. $scope.$on('$ionicView.afterEnter', function() {
  60000. $ionicViewSwitcher.viewEleIsActive(childElement, $scope.$tabSelected);
  60001. });
  60002. $scope.$on('$ionicView.clearCache', function() {
  60003. if (!$scope.$tabSelected) {
  60004. destroyTab();
  60005. }
  60006. });
  60007. };
  60008. }
  60009. };
  60010. }]);
  60011. IonicModule
  60012. .directive('ionTabNav', [function() {
  60013. return {
  60014. restrict: 'E',
  60015. replace: true,
  60016. require: ['^ionTabs', '^ionTab'],
  60017. template:
  60018. '<a ng-class="{\'has-badge\':badge, \'tab-hidden\':isHidden(), \'tab-item-active\': isTabActive()}" ' +
  60019. ' ng-disabled="disabled()" class="tab-item">' +
  60020. '<span class="badge {{badgeStyle}}" ng-if="badge">{{badge}}</span>' +
  60021. '<i class="icon {{getIcon()}}" ng-if="getIcon()"></i>' +
  60022. '<span class="tab-title" ng-bind-html="title"></span>' +
  60023. '</a>',
  60024. scope: {
  60025. title: '@',
  60026. icon: '@',
  60027. iconOn: '@',
  60028. iconOff: '@',
  60029. badge: '=',
  60030. hidden: '@',
  60031. disabled: '&',
  60032. badgeStyle: '@',
  60033. 'class': '@'
  60034. },
  60035. link: function($scope, $element, $attrs, ctrls) {
  60036. var tabsCtrl = ctrls[0],
  60037. tabCtrl = ctrls[1];
  60038. //Remove title attribute so browser-tooltip does not apear
  60039. $element[0].removeAttribute('title');
  60040. $scope.selectTab = function(e) {
  60041. e.preventDefault();
  60042. tabsCtrl.select(tabCtrl.$scope, true);
  60043. };
  60044. if (!$attrs.ngClick) {
  60045. $element.on('click', function(event) {
  60046. $scope.$apply(function() {
  60047. $scope.selectTab(event);
  60048. });
  60049. });
  60050. }
  60051. $scope.isHidden = function() {
  60052. if ($attrs.hidden === 'true' || $attrs.hidden === true) return true;
  60053. return false;
  60054. };
  60055. $scope.getIconOn = function() {
  60056. return $scope.iconOn || $scope.icon;
  60057. };
  60058. $scope.getIconOff = function() {
  60059. return $scope.iconOff || $scope.icon;
  60060. };
  60061. $scope.isTabActive = function() {
  60062. return tabsCtrl.selectedTab() === tabCtrl.$scope;
  60063. };
  60064. $scope.getIcon = function() {
  60065. if ( tabsCtrl.selectedTab() === tabCtrl.$scope ) {
  60066. // active
  60067. return $scope.iconOn || $scope.icon;
  60068. }
  60069. else {
  60070. // inactive
  60071. return $scope.iconOff || $scope.icon;
  60072. }
  60073. };
  60074. }
  60075. };
  60076. }]);
  60077. /**
  60078. * @ngdoc directive
  60079. * @name ionTabs
  60080. * @module ionic
  60081. * @delegate ionic.service:$ionicTabsDelegate
  60082. * @restrict E
  60083. * @codepen odqCz
  60084. *
  60085. * @description
  60086. * Powers a multi-tabbed interface with a Tab Bar and a set of "pages" that can be tabbed
  60087. * through.
  60088. *
  60089. * Assign any [tabs class](/docs/components#tabs) to the element to define
  60090. * its look and feel.
  60091. *
  60092. * For iOS, tabs will appear at the bottom of the screen. For Android, tabs will be at the top
  60093. * of the screen, below the nav-bar. This follows each OS's design specification, but can be
  60094. * configured with the {@link ionic.provider:$ionicConfigProvider}.
  60095. *
  60096. * See the {@link ionic.directive:ionTab} directive's documentation for more details on
  60097. * individual tabs.
  60098. *
  60099. * Note: do not place ion-tabs inside of an ion-content element; it has been known to cause a
  60100. * certain CSS bug.
  60101. *
  60102. * @usage
  60103. * ```html
  60104. * <ion-tabs class="tabs-positive tabs-icon-top">
  60105. *
  60106. * <ion-tab title="Home" icon-on="ion-ios-filing" icon-off="ion-ios-filing-outline">
  60107. * <!-- Tab 1 content -->
  60108. * </ion-tab>
  60109. *
  60110. * <ion-tab title="About" icon-on="ion-ios-clock" icon-off="ion-ios-clock-outline">
  60111. * <!-- Tab 2 content -->
  60112. * </ion-tab>
  60113. *
  60114. * <ion-tab title="Settings" icon-on="ion-ios-gear" icon-off="ion-ios-gear-outline">
  60115. * <!-- Tab 3 content -->
  60116. * </ion-tab>
  60117. *
  60118. * </ion-tabs>
  60119. * ```
  60120. *
  60121. * @param {string=} delegate-handle The handle used to identify these tabs
  60122. * with {@link ionic.service:$ionicTabsDelegate}.
  60123. */
  60124. IonicModule
  60125. .directive('ionTabs', [
  60126. '$ionicTabsDelegate',
  60127. '$ionicConfig',
  60128. function($ionicTabsDelegate, $ionicConfig) {
  60129. return {
  60130. restrict: 'E',
  60131. scope: true,
  60132. controller: '$ionicTabs',
  60133. compile: function(tElement) {
  60134. //We cannot use regular transclude here because it breaks element.data()
  60135. //inheritance on compile
  60136. var innerElement = jqLite('<div class="tab-nav tabs">');
  60137. innerElement.append(tElement.contents());
  60138. tElement.append(innerElement)
  60139. .addClass('tabs-' + $ionicConfig.tabs.position() + ' tabs-' + $ionicConfig.tabs.style());
  60140. return { pre: prelink, post: postLink };
  60141. function prelink($scope, $element, $attr, tabsCtrl) {
  60142. var deregisterInstance = $ionicTabsDelegate._registerInstance(
  60143. tabsCtrl, $attr.delegateHandle, tabsCtrl.hasActiveScope
  60144. );
  60145. tabsCtrl.$scope = $scope;
  60146. tabsCtrl.$element = $element;
  60147. tabsCtrl.$tabsElement = jqLite($element[0].querySelector('.tabs'));
  60148. $scope.$watch(function() { return $element[0].className; }, function(value) {
  60149. var isTabsTop = value.indexOf('tabs-top') !== -1;
  60150. var isHidden = value.indexOf('tabs-item-hide') !== -1;
  60151. $scope.$hasTabs = !isTabsTop && !isHidden;
  60152. $scope.$hasTabsTop = isTabsTop && !isHidden;
  60153. $scope.$emit('$ionicTabs.top', $scope.$hasTabsTop);
  60154. });
  60155. function emitLifecycleEvent(ev, data) {
  60156. ev.stopPropagation();
  60157. var previousSelectedTab = tabsCtrl.previousSelectedTab();
  60158. if (previousSelectedTab) {
  60159. previousSelectedTab.$broadcast(ev.name.replace('NavView', 'Tabs'), data);
  60160. }
  60161. }
  60162. $scope.$on('$ionicNavView.beforeLeave', emitLifecycleEvent);
  60163. $scope.$on('$ionicNavView.afterLeave', emitLifecycleEvent);
  60164. $scope.$on('$ionicNavView.leave', emitLifecycleEvent);
  60165. $scope.$on('$destroy', function() {
  60166. // variable to inform child tabs that they're all being blown away
  60167. // used so that while destorying an individual tab, each one
  60168. // doesn't select the next tab as the active one, which causes unnecessary
  60169. // loading of tab views when each will eventually all go away anyway
  60170. $scope.$tabsDestroy = true;
  60171. deregisterInstance();
  60172. tabsCtrl.$tabsElement = tabsCtrl.$element = tabsCtrl.$scope = innerElement = null;
  60173. delete $scope.$hasTabs;
  60174. delete $scope.$hasTabsTop;
  60175. });
  60176. }
  60177. function postLink($scope, $element, $attr, tabsCtrl) {
  60178. if (!tabsCtrl.selectedTab()) {
  60179. // all the tabs have been added
  60180. // but one hasn't been selected yet
  60181. tabsCtrl.select(0);
  60182. }
  60183. }
  60184. }
  60185. };
  60186. }]);
  60187. /**
  60188. * @ngdoc directive
  60189. * @name ionTitle
  60190. * @module ionic
  60191. * @restrict E
  60192. *
  60193. * Used for titles in header and nav bars. New in 1.2
  60194. *
  60195. * Identical to <div class="title"> but with future compatibility for Ionic 2
  60196. *
  60197. * @usage
  60198. *
  60199. * ```html
  60200. * <ion-nav-bar>
  60201. * <ion-title>Hello</ion-title>
  60202. * <ion-nav-bar>
  60203. * ```
  60204. */
  60205. IonicModule
  60206. .directive('ionTitle', [function() {
  60207. return {
  60208. restrict: 'E',
  60209. compile: function(element) {
  60210. element.addClass('title');
  60211. }
  60212. };
  60213. }]);
  60214. /**
  60215. * @ngdoc directive
  60216. * @name ionToggle
  60217. * @module ionic
  60218. * @codepen tfAzj
  60219. * @restrict E
  60220. *
  60221. * @description
  60222. * A toggle is an animated switch which binds a given model to a boolean.
  60223. *
  60224. * Allows dragging of the switch's nub.
  60225. *
  60226. * The toggle behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]) otherwise.
  60227. *
  60228. * @param toggle-class {string=} Sets the CSS class on the inner `label.toggle` element created by the directive.
  60229. *
  60230. * @usage
  60231. * Below is an example of a toggle directive which is wired up to the `airplaneMode` model
  60232. * and has the `toggle-calm` CSS class assigned to the inner element.
  60233. *
  60234. * ```html
  60235. * <ion-toggle ng-model="airplaneMode" toggle-class="toggle-calm">Airplane Mode</ion-toggle>
  60236. * ```
  60237. */
  60238. IonicModule
  60239. .directive('ionToggle', [
  60240. '$timeout',
  60241. '$ionicConfig',
  60242. function($timeout, $ionicConfig) {
  60243. return {
  60244. restrict: 'E',
  60245. replace: true,
  60246. require: '?ngModel',
  60247. transclude: true,
  60248. template:
  60249. '<div class="item item-toggle">' +
  60250. '<div ng-transclude></div>' +
  60251. '<label class="toggle">' +
  60252. '<input type="checkbox">' +
  60253. '<div class="track">' +
  60254. '<div class="handle"></div>' +
  60255. '</div>' +
  60256. '</label>' +
  60257. '</div>',
  60258. compile: function(element, attr) {
  60259. var input = element.find('input');
  60260. forEach({
  60261. 'name': attr.name,
  60262. 'ng-value': attr.ngValue,
  60263. 'ng-model': attr.ngModel,
  60264. 'ng-checked': attr.ngChecked,
  60265. 'ng-disabled': attr.ngDisabled,
  60266. 'ng-true-value': attr.ngTrueValue,
  60267. 'ng-false-value': attr.ngFalseValue,
  60268. 'ng-change': attr.ngChange,
  60269. 'ng-required': attr.ngRequired,
  60270. 'required': attr.required
  60271. }, function(value, name) {
  60272. if (isDefined(value)) {
  60273. input.attr(name, value);
  60274. }
  60275. });
  60276. if (attr.toggleClass) {
  60277. element[0].getElementsByTagName('label')[0].classList.add(attr.toggleClass);
  60278. }
  60279. element.addClass('toggle-' + $ionicConfig.form.toggle());
  60280. return function($scope, $element) {
  60281. var el = $element[0].getElementsByTagName('label')[0];
  60282. var checkbox = el.children[0];
  60283. var track = el.children[1];
  60284. var handle = track.children[0];
  60285. var ngModelController = jqLite(checkbox).controller('ngModel');
  60286. $scope.toggle = new ionic.views.Toggle({
  60287. el: el,
  60288. track: track,
  60289. checkbox: checkbox,
  60290. handle: handle,
  60291. onChange: function() {
  60292. if (ngModelController) {
  60293. ngModelController.$setViewValue(checkbox.checked);
  60294. $scope.$apply();
  60295. }
  60296. }
  60297. });
  60298. $scope.$on('$destroy', function() {
  60299. $scope.toggle.destroy();
  60300. });
  60301. };
  60302. }
  60303. };
  60304. }]);
  60305. /**
  60306. * @ngdoc directive
  60307. * @name ionView
  60308. * @module ionic
  60309. * @restrict E
  60310. * @parent ionNavView
  60311. *
  60312. * @description
  60313. * A container for view content and any navigational and header bar information. When a view
  60314. * enters and exits its parent {@link ionic.directive:ionNavView}, the view also emits view
  60315. * information, such as its title, whether the back button should be displayed or not, whether the
  60316. * corresponding {@link ionic.directive:ionNavBar} should be displayed or not, which transition the view
  60317. * should use to animate, and which direction to animate.
  60318. *
  60319. * *Views are cached to improve performance.* When a view is navigated away from, its element is
  60320. * left in the DOM, and its scope is disconnected from the `$watch` cycle. When navigating to a
  60321. * view that is already cached, its scope is reconnected, and the existing element, which was
  60322. * left in the DOM, becomes active again. This can be disabled, or the maximum number of cached
  60323. * views changed in {@link ionic.provider:$ionicConfigProvider}, in the view's `$state` configuration, or
  60324. * as an attribute on the view itself (see below).
  60325. *
  60326. * @usage
  60327. * Below is an example where our page will load with a {@link ionic.directive:ionNavBar} containing
  60328. * "My Page" as the title.
  60329. *
  60330. * ```html
  60331. * <ion-nav-bar></ion-nav-bar>
  60332. * <ion-nav-view>
  60333. * <ion-view view-title="My Page">
  60334. * <ion-content>
  60335. * Hello!
  60336. * </ion-content>
  60337. * </ion-view>
  60338. * </ion-nav-view>
  60339. * ```
  60340. *
  60341. * ## View LifeCycle and Events
  60342. *
  60343. * Views can be cached, which means ***controllers normally only load once***, which may
  60344. * affect your controller logic. To know when a view has entered or left, events
  60345. * have been added that are emitted from the view's scope. These events also
  60346. * contain data about the view, such as the title and whether the back button should
  60347. * show. Also contained is transition data, such as the transition type and
  60348. * direction that will be or was used.
  60349. *
  60350. * Life cycle events are emitted upwards from the transitioning view's scope. In some cases, it is
  60351. * desirable for a child/nested view to be notified of the event.
  60352. * For this use case, `$ionicParentView` life cycle events are broadcast downwards.
  60353. *
  60354. * <table class="table">
  60355. * <tr>
  60356. * <td><code>$ionicView.loaded</code></td>
  60357. * <td>The view has loaded. This event only happens once per
  60358. * view being created and added to the DOM. If a view leaves but is cached,
  60359. * then this event will not fire again on a subsequent viewing. The loaded event
  60360. * is good place to put your setup code for the view; however, it is not the
  60361. * recommended event to listen to when a view becomes active.</td>
  60362. * </tr>
  60363. * <tr>
  60364. * <td><code>$ionicView.enter</code></td>
  60365. * <td>The view has fully entered and is now the active view.
  60366. * This event will fire, whether it was the first load or a cached view.</td>
  60367. * </tr>
  60368. * <tr>
  60369. * <td><code>$ionicView.leave</code></td>
  60370. * <td>The view has finished leaving and is no longer the
  60371. * active view. This event will fire, whether it is cached or destroyed.</td>
  60372. * </tr>
  60373. * <tr>
  60374. * <td><code>$ionicView.beforeEnter</code></td>
  60375. * <td>The view is about to enter and become the active view.</td>
  60376. * </tr>
  60377. * <tr>
  60378. * <td><code>$ionicView.beforeLeave</code></td>
  60379. * <td>The view is about to leave and no longer be the active view.</td>
  60380. * </tr>
  60381. * <tr>
  60382. * <td><code>$ionicView.afterEnter</code></td>
  60383. * <td>The view has fully entered and is now the active view.</td>
  60384. * </tr>
  60385. * <tr>
  60386. * <td><code>$ionicView.afterLeave</code></td>
  60387. * <td>The view has finished leaving and is no longer the active view.</td>
  60388. * </tr>
  60389. * <tr>
  60390. * <td><code>$ionicView.unloaded</code></td>
  60391. * <td>The view's controller has been destroyed and its element has been
  60392. * removed from the DOM.</td>
  60393. * </tr>
  60394. * <tr>
  60395. * <td><code>$ionicParentView.enter</code></td>
  60396. * <td>The parent view has fully entered and is now the active view.
  60397. * This event will fire, whether it was the first load or a cached view.</td>
  60398. * </tr>
  60399. * <tr>
  60400. * <td><code>$ionicParentView.leave</code></td>
  60401. * <td>The parent view has finished leaving and is no longer the
  60402. * active view. This event will fire, whether it is cached or destroyed.</td>
  60403. * </tr>
  60404. * <tr>
  60405. * <td><code>$ionicParentView.beforeEnter</code></td>
  60406. * <td>The parent view is about to enter and become the active view.</td>
  60407. * </tr>
  60408. * <tr>
  60409. * <td><code>$ionicParentView.beforeLeave</code></td>
  60410. * <td>The parent view is about to leave and no longer be the active view.</td>
  60411. * </tr>
  60412. * <tr>
  60413. * <td><code>$ionicParentView.afterEnter</code></td>
  60414. * <td>The parent view has fully entered and is now the active view.</td>
  60415. * </tr>
  60416. * <tr>
  60417. * <td><code>$ionicParentView.afterLeave</code></td>
  60418. * <td>The parent view has finished leaving and is no longer the active view.</td>
  60419. * </tr>
  60420. * </table>
  60421. *
  60422. * ## LifeCycle Event Usage
  60423. *
  60424. * Below is an example of how to listen to life cycle events and
  60425. * access state parameter data
  60426. *
  60427. * ```js
  60428. * $scope.$on("$ionicView.beforeEnter", function(event, data){
  60429. * // handle event
  60430. * console.log("State Params: ", data.stateParams);
  60431. * });
  60432. *
  60433. * $scope.$on("$ionicView.enter", function(event, data){
  60434. * // handle event
  60435. * console.log("State Params: ", data.stateParams);
  60436. * });
  60437. *
  60438. * $scope.$on("$ionicView.afterEnter", function(event, data){
  60439. * // handle event
  60440. * console.log("State Params: ", data.stateParams);
  60441. * });
  60442. * ```
  60443. *
  60444. * ## Caching
  60445. *
  60446. * Caching can be disabled and enabled in multiple ways. By default, Ionic will
  60447. * cache a maximum of 10 views. You can optionally choose to disable caching at
  60448. * either an individual view basis, or by global configuration. Please see the
  60449. * _Caching_ section in {@link ionic.directive:ionNavView} for more info.
  60450. *
  60451. * @param {string=} view-title A text-only title to display on the parent {@link ionic.directive:ionNavBar}.
  60452. * For an HTML title, such as an image, see {@link ionic.directive:ionNavTitle} instead.
  60453. * @param {boolean=} cache-view If this view should be allowed to be cached or not.
  60454. * Please see the _Caching_ section in {@link ionic.directive:ionNavView} for
  60455. * more info. Default `true`
  60456. * @param {boolean=} can-swipe-back If this view should be allowed to use the swipe to go back gesture or not.
  60457. * This does not enable the swipe to go back feature if it is not available for the platform it's running
  60458. * from, or there isn't a previous view. Default `true`
  60459. * @param {boolean=} hide-back-button Whether to hide the back button on the parent
  60460. * {@link ionic.directive:ionNavBar} by default.
  60461. * @param {boolean=} hide-nav-bar Whether to hide the parent
  60462. * {@link ionic.directive:ionNavBar} by default.
  60463. */
  60464. IonicModule
  60465. .directive('ionView', function() {
  60466. return {
  60467. restrict: 'EA',
  60468. priority: 1000,
  60469. controller: '$ionicView',
  60470. compile: function(tElement) {
  60471. tElement.addClass('pane');
  60472. tElement[0].removeAttribute('title');
  60473. return function link($scope, $element, $attrs, viewCtrl) {
  60474. viewCtrl.init();
  60475. };
  60476. }
  60477. };
  60478. });
  60479. })();