angular-ui-router.js 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861
  1. /**
  2. * State-based routing for AngularJS
  3. * @version v0.4.2
  4. * @link http://angular-ui.github.com/
  5. * @license MIT License, http://www.opensource.org/licenses/MIT
  6. */
  7. /* commonjs package manager support (eg componentjs) */
  8. if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports) {
  9. module.exports = 'ui.router';
  10. }
  11. (function (window, angular, undefined) {
  12. /*jshint globalstrict:true*/
  13. /*global angular:false*/
  14. 'use strict';
  15. var isDefined = angular.isDefined,
  16. isFunction = angular.isFunction,
  17. isString = angular.isString,
  18. isObject = angular.isObject,
  19. isArray = angular.isArray,
  20. forEach = angular.forEach,
  21. extend = angular.extend,
  22. copy = angular.copy,
  23. toJson = angular.toJson;
  24. function inherit(parent, extra) {
  25. return extend(new (extend(function () {
  26. }, {prototype: parent}))(), extra);
  27. }
  28. function merge(dst) {
  29. forEach(arguments, function (obj) {
  30. if (obj !== dst) {
  31. forEach(obj, function (value, key) {
  32. if (!dst.hasOwnProperty(key)) dst[key] = value;
  33. });
  34. }
  35. });
  36. return dst;
  37. }
  38. /**
  39. * Finds the common ancestor path between two states.
  40. *
  41. * @param {Object} first The first state.
  42. * @param {Object} second The second state.
  43. * @return {Array} Returns an array of state names in descending order, not including the root.
  44. */
  45. function ancestors(first, second) {
  46. var path = [];
  47. for (var n in first.path) {
  48. if (first.path[n] !== second.path[n]) break;
  49. path.push(first.path[n]);
  50. }
  51. return path;
  52. }
  53. /**
  54. * IE8-safe wrapper for `Object.keys()`.
  55. *
  56. * @param {Object} object A JavaScript object.
  57. * @return {Array} Returns the keys of the object as an array.
  58. */
  59. function objectKeys(object) {
  60. if (Object.keys) {
  61. return Object.keys(object);
  62. }
  63. var result = [];
  64. forEach(object, function (val, key) {
  65. result.push(key);
  66. });
  67. return result;
  68. }
  69. /**
  70. * IE8-safe wrapper for `Array.prototype.indexOf()`.
  71. *
  72. * @param {Array} array A JavaScript array.
  73. * @param {*} value A value to search the array for.
  74. * @return {Number} Returns the array index value of `value`, or `-1` if not present.
  75. */
  76. function indexOf(array, value) {
  77. if (Array.prototype.indexOf) {
  78. return array.indexOf(value, Number(arguments[2]) || 0);
  79. }
  80. var len = array.length >>> 0, from = Number(arguments[2]) || 0;
  81. from = (from < 0) ? Math.ceil(from) : Math.floor(from);
  82. if (from < 0) from += len;
  83. for (; from < len; from++) {
  84. if (from in array && array[from] === value) return from;
  85. }
  86. return -1;
  87. }
  88. /**
  89. * Merges a set of parameters with all parameters inherited between the common parents of the
  90. * current state and a given destination state.
  91. *
  92. * @param {Object} currentParams The value of the current state parameters ($stateParams).
  93. * @param {Object} newParams The set of parameters which will be composited with inherited params.
  94. * @param {Object} $current Internal definition of object representing the current state.
  95. * @param {Object} $to Internal definition of object representing state to transition to.
  96. */
  97. function inheritParams(currentParams, newParams, $current, $to) {
  98. var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];
  99. for (var i in parents) {
  100. if (!parents[i] || !parents[i].params) continue;
  101. parentParams = objectKeys(parents[i].params);
  102. if (!parentParams.length) continue;
  103. for (var j in parentParams) {
  104. if (indexOf(inheritList, parentParams[j]) >= 0) continue;
  105. inheritList.push(parentParams[j]);
  106. inherited[parentParams[j]] = currentParams[parentParams[j]];
  107. }
  108. }
  109. return extend({}, inherited, newParams);
  110. }
  111. /**
  112. * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.
  113. *
  114. * @param {Object} a The first object.
  115. * @param {Object} b The second object.
  116. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,
  117. * it defaults to the list of keys in `a`.
  118. * @return {Boolean} Returns `true` if the keys match, otherwise `false`.
  119. */
  120. function equalForKeys(a, b, keys) {
  121. if (!keys) {
  122. keys = [];
  123. for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility
  124. }
  125. for (var i = 0; i < keys.length; i++) {
  126. var k = keys[i];
  127. if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized
  128. }
  129. return true;
  130. }
  131. /**
  132. * Returns the subset of an object, based on a list of keys.
  133. *
  134. * @param {Array} keys
  135. * @param {Object} values
  136. * @return {Boolean} Returns a subset of `values`.
  137. */
  138. function filterByKeys(keys, values) {
  139. var filtered = {};
  140. forEach(keys, function (name) {
  141. filtered[name] = values[name];
  142. });
  143. return filtered;
  144. }
  145. // like _.indexBy
  146. // when you know that your index values will be unique, or you want last-one-in to win
  147. function indexBy(array, propName) {
  148. var result = {};
  149. forEach(array, function (item) {
  150. result[item[propName]] = item;
  151. });
  152. return result;
  153. }
  154. // extracted from underscore.js
  155. // Return a copy of the object only containing the whitelisted properties.
  156. function pick(obj) {
  157. var copy = {};
  158. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  159. forEach(keys, function (key) {
  160. if (key in obj) copy[key] = obj[key];
  161. });
  162. return copy;
  163. }
  164. // extracted from underscore.js
  165. // Return a copy of the object omitting the blacklisted properties.
  166. function omit(obj) {
  167. var copy = {};
  168. var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));
  169. for (var key in obj) {
  170. if (indexOf(keys, key) == -1) copy[key] = obj[key];
  171. }
  172. return copy;
  173. }
  174. function pluck(collection, key) {
  175. var result = isArray(collection) ? [] : {};
  176. forEach(collection, function (val, i) {
  177. result[i] = isFunction(key) ? key(val) : val[key];
  178. });
  179. return result;
  180. }
  181. function filter(collection, callback) {
  182. var array = isArray(collection);
  183. var result = array ? [] : {};
  184. forEach(collection, function (val, i) {
  185. if (callback(val, i)) {
  186. result[array ? result.length : i] = val;
  187. }
  188. });
  189. return result;
  190. }
  191. function map(collection, callback) {
  192. var result = isArray(collection) ? [] : {};
  193. forEach(collection, function (val, i) {
  194. result[i] = callback(val, i);
  195. });
  196. return result;
  197. }
  198. // issue #2676 #2889
  199. function silenceUncaughtInPromise(promise) {
  200. return promise.then(undefined, function () {
  201. }) && promise;
  202. }
  203. /**
  204. * @ngdoc overview
  205. * @name ui.router.util
  206. *
  207. * @description
  208. * # ui.router.util sub-module
  209. *
  210. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  211. * in your angular app (use {@link ui.router} module instead).
  212. *
  213. */
  214. angular.module('ui.router.util', ['ng']);
  215. /**
  216. * @ngdoc overview
  217. * @name ui.router.router
  218. *
  219. * @requires ui.router.util
  220. *
  221. * @description
  222. * # ui.router.router sub-module
  223. *
  224. * This module is a dependency of other sub-modules. Do not include this module as a dependency
  225. * in your angular app (use {@link ui.router} module instead).
  226. */
  227. angular.module('ui.router.router', ['ui.router.util']);
  228. /**
  229. * @ngdoc overview
  230. * @name ui.router.state
  231. *
  232. * @requires ui.router.router
  233. * @requires ui.router.util
  234. *
  235. * @description
  236. * # ui.router.state sub-module
  237. *
  238. * This module is a dependency of the main ui.router module. Do not include this module as a dependency
  239. * in your angular app (use {@link ui.router} module instead).
  240. *
  241. */
  242. angular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);
  243. /**
  244. * @ngdoc overview
  245. * @name ui.router
  246. *
  247. * @requires ui.router.state
  248. *
  249. * @description
  250. * # ui.router
  251. *
  252. * ## The main module for ui.router
  253. * There are several sub-modules included with the ui.router module, however only this module is needed
  254. * as a dependency within your angular app. The other modules are for organization purposes.
  255. *
  256. * The modules are:
  257. * * ui.router - the main "umbrella" module
  258. * * ui.router.router -
  259. *
  260. * *You'll need to include **only** this module as the dependency within your angular app.*
  261. *
  262. * <pre>
  263. * <!doctype html>
  264. * <html ng-app="myApp">
  265. * <head>
  266. * <script src="js/angular.js"></script>
  267. * <!-- Include the ui-router script -->
  268. * <script src="js/angular-ui-router.min.js"></script>
  269. * <script>
  270. * // ...and add 'ui.router' as a dependency
  271. * var myApp = angular.module('myApp', ['ui.router']);
  272. * </script>
  273. * </head>
  274. * <body>
  275. * </body>
  276. * </html>
  277. * </pre>
  278. */
  279. angular.module('ui.router', ['ui.router.state']);
  280. angular.module('ui.router.compat', ['ui.router']);
  281. /**
  282. * @ngdoc object
  283. * @name ui.router.util.$resolve
  284. *
  285. * @requires $q
  286. * @requires $injector
  287. *
  288. * @description
  289. * Manages resolution of (acyclic) graphs of promises.
  290. */
  291. $Resolve.$inject = ['$q', '$injector'];
  292. function $Resolve($q, $injector) {
  293. var VISIT_IN_PROGRESS = 1,
  294. VISIT_DONE = 2,
  295. NOTHING = {},
  296. NO_DEPENDENCIES = [],
  297. NO_LOCALS = NOTHING,
  298. NO_PARENT = extend($q.when(NOTHING), {$$promises: NOTHING, $$values: NOTHING});
  299. /**
  300. * @ngdoc function
  301. * @name ui.router.util.$resolve#study
  302. * @methodOf ui.router.util.$resolve
  303. *
  304. * @description
  305. * Studies a set of invocables that are likely to be used multiple times.
  306. * <pre>
  307. * $resolve.study(invocables)(locals, parent, self)
  308. * </pre>
  309. * is equivalent to
  310. * <pre>
  311. * $resolve.resolve(invocables, locals, parent, self)
  312. * </pre>
  313. * but the former is more efficient (in fact `resolve` just calls `study`
  314. * internally).
  315. *
  316. * @param {object} invocables Invocable objects
  317. * @return {function} a function to pass in locals, parent and self
  318. */
  319. this.study = function (invocables) {
  320. if (!isObject(invocables)) throw new Error("'invocables' must be an object");
  321. var invocableKeys = objectKeys(invocables || {});
  322. // Perform a topological sort of invocables to build an ordered plan
  323. var plan = [], cycle = [], visited = {};
  324. function visit(value, key) {
  325. if (visited[key] === VISIT_DONE) return;
  326. cycle.push(key);
  327. if (visited[key] === VISIT_IN_PROGRESS) {
  328. cycle.splice(0, indexOf(cycle, key));
  329. throw new Error("Cyclic dependency: " + cycle.join(" -> "));
  330. }
  331. visited[key] = VISIT_IN_PROGRESS;
  332. if (isString(value)) {
  333. plan.push(key, [function () {
  334. return $injector.get(value);
  335. }], NO_DEPENDENCIES);
  336. } else {
  337. var params = $injector.annotate(value);
  338. forEach(params, function (param) {
  339. if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);
  340. });
  341. plan.push(key, value, params);
  342. }
  343. cycle.pop();
  344. visited[key] = VISIT_DONE;
  345. }
  346. forEach(invocables, visit);
  347. invocables = cycle = visited = null; // plan is all that's required
  348. function isResolve(value) {
  349. return isObject(value) && value.then && value.$$promises;
  350. }
  351. return function (locals, parent, self) {
  352. if (isResolve(locals) && self === undefined) {
  353. self = parent;
  354. parent = locals;
  355. locals = null;
  356. }
  357. if (!locals) locals = NO_LOCALS;
  358. else if (!isObject(locals)) {
  359. throw new Error("'locals' must be an object");
  360. }
  361. if (!parent) parent = NO_PARENT;
  362. else if (!isResolve(parent)) {
  363. throw new Error("'parent' must be a promise returned by $resolve.resolve()");
  364. }
  365. // To complete the overall resolution, we have to wait for the parent
  366. // promise and for the promise for each invokable in our plan.
  367. var resolution = $q.defer(),
  368. result = silenceUncaughtInPromise(resolution.promise),
  369. promises = result.$$promises = {},
  370. values = extend({}, locals),
  371. wait = 1 + plan.length / 3,
  372. merged = false;
  373. silenceUncaughtInPromise(result);
  374. function done() {
  375. // Merge parent values we haven't got yet and publish our own $$values
  376. if (!--wait) {
  377. if (!merged) merge(values, parent.$$values);
  378. result.$$values = values;
  379. result.$$promises = result.$$promises || true; // keep for isResolve()
  380. delete result.$$inheritedValues;
  381. resolution.resolve(values);
  382. }
  383. }
  384. function fail(reason) {
  385. result.$$failure = reason;
  386. resolution.reject(reason);
  387. }
  388. // Short-circuit if parent has already failed
  389. if (isDefined(parent.$$failure)) {
  390. fail(parent.$$failure);
  391. return result;
  392. }
  393. if (parent.$$inheritedValues) {
  394. merge(values, omit(parent.$$inheritedValues, invocableKeys));
  395. }
  396. // Merge parent values if the parent has already resolved, or merge
  397. // parent promises and wait if the parent resolve is still in progress.
  398. extend(promises, parent.$$promises);
  399. if (parent.$$values) {
  400. merged = merge(values, omit(parent.$$values, invocableKeys));
  401. result.$$inheritedValues = omit(parent.$$values, invocableKeys);
  402. done();
  403. } else {
  404. if (parent.$$inheritedValues) {
  405. result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);
  406. }
  407. parent.then(done, fail);
  408. }
  409. // Process each invocable in the plan, but ignore any where a local of the same name exists.
  410. for (var i = 0, ii = plan.length; i < ii; i += 3) {
  411. if (locals.hasOwnProperty(plan[i])) done();
  412. else invoke(plan[i], plan[i + 1], plan[i + 2]);
  413. }
  414. function invoke(key, invocable, params) {
  415. // Create a deferred for this invocation. Failures will propagate to the resolution as well.
  416. var invocation = $q.defer(), waitParams = 0;
  417. function onfailure(reason) {
  418. invocation.reject(reason);
  419. fail(reason);
  420. }
  421. // Wait for any parameter that we have a promise for (either from parent or from this
  422. // resolve; in that case study() will have made sure it's ordered before us in the plan).
  423. forEach(params, function (dep) {
  424. if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {
  425. waitParams++;
  426. promises[dep].then(function (result) {
  427. values[dep] = result;
  428. if (!(--waitParams)) proceed();
  429. }, onfailure);
  430. }
  431. });
  432. if (!waitParams) proceed();
  433. function proceed() {
  434. if (isDefined(result.$$failure)) return;
  435. try {
  436. invocation.resolve($injector.invoke(invocable, self, values));
  437. invocation.promise.then(function (result) {
  438. values[key] = result;
  439. done();
  440. }, onfailure);
  441. } catch (e) {
  442. onfailure(e);
  443. }
  444. }
  445. // Publish promise synchronously; invocations further down in the plan may depend on it.
  446. promises[key] = silenceUncaughtInPromise(invocation.promise);
  447. }
  448. return result;
  449. };
  450. };
  451. /**
  452. * @ngdoc function
  453. * @name ui.router.util.$resolve#resolve
  454. * @methodOf ui.router.util.$resolve
  455. *
  456. * @description
  457. * Resolves a set of invocables. An invocable is a function to be invoked via
  458. * `$injector.invoke()`, and can have an arbitrary number of dependencies.
  459. * An invocable can either return a value directly,
  460. * or a `$q` promise. If a promise is returned it will be resolved and the
  461. * resulting value will be used instead. Dependencies of invocables are resolved
  462. * (in this order of precedence)
  463. *
  464. * - from the specified `locals`
  465. * - from another invocable that is part of this `$resolve` call
  466. * - from an invocable that is inherited from a `parent` call to `$resolve`
  467. * (or recursively
  468. * - from any ancestor `$resolve` of that parent).
  469. *
  470. * The return value of `$resolve` is a promise for an object that contains
  471. * (in this order of precedence)
  472. *
  473. * - any `locals` (if specified)
  474. * - the resolved return values of all injectables
  475. * - any values inherited from a `parent` call to `$resolve` (if specified)
  476. *
  477. * The promise will resolve after the `parent` promise (if any) and all promises
  478. * returned by injectables have been resolved. If any invocable
  479. * (or `$injector.invoke`) throws an exception, or if a promise returned by an
  480. * invocable is rejected, the `$resolve` promise is immediately rejected with the
  481. * same error. A rejection of a `parent` promise (if specified) will likewise be
  482. * propagated immediately. Once the `$resolve` promise has been rejected, no
  483. * further invocables will be called.
  484. *
  485. * Cyclic dependencies between invocables are not permitted and will cause `$resolve`
  486. * to throw an error. As a special case, an injectable can depend on a parameter
  487. * with the same name as the injectable, which will be fulfilled from the `parent`
  488. * injectable of the same name. This allows inherited values to be decorated.
  489. * Note that in this case any other injectable in the same `$resolve` with the same
  490. * dependency would see the decorated value, not the inherited value.
  491. *
  492. * Note that missing dependencies -- unlike cyclic dependencies -- will cause an
  493. * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous)
  494. * exception.
  495. *
  496. * Invocables are invoked eagerly as soon as all dependencies are available.
  497. * This is true even for dependencies inherited from a `parent` call to `$resolve`.
  498. *
  499. * As a special case, an invocable can be a string, in which case it is taken to
  500. * be a service name to be passed to `$injector.get()`. This is supported primarily
  501. * for backwards-compatibility with the `resolve` property of `$routeProvider`
  502. * routes.
  503. *
  504. * @param {object} invocables functions to invoke or
  505. * `$injector` services to fetch.
  506. * @param {object} locals values to make available to the injectables
  507. * @param {object} parent a promise returned by another call to `$resolve`.
  508. * @param {object} self the `this` for the invoked methods
  509. * @return {object} Promise for an object that contains the resolved return value
  510. * of all invocables, as well as any inherited and local values.
  511. */
  512. this.resolve = function (invocables, locals, parent, self) {
  513. return this.study(invocables)(locals, parent, self);
  514. };
  515. }
  516. angular.module('ui.router.util').service('$resolve', $Resolve);
  517. /**
  518. * @ngdoc object
  519. * @name ui.router.util.$templateFactoryProvider
  520. *
  521. * @description
  522. * Provider for $templateFactory. Manages which template-loading mechanism to
  523. * use, and will default to the most recent one ($templateRequest on Angular
  524. * versions starting from 1.3, $http otherwise).
  525. */
  526. function TemplateFactoryProvider() {
  527. var shouldUnsafelyUseHttp = angular.version.minor < 3;
  528. /**
  529. * @ngdoc function
  530. * @name ui.router.util.$templateFactoryProvider#shouldUnsafelyUseHttp
  531. * @methodOf ui.router.util.$templateFactoryProvider
  532. *
  533. * @description
  534. * Forces $templateFactory to use $http instead of $templateRequest. This
  535. * might cause XSS, as $http doesn't enforce the regular security checks for
  536. * templates that have been introduced in Angular 1.3. Note that setting this
  537. * to false on Angular older than 1.3.x will crash, as the $templateRequest
  538. * service (and the security checks) are not implemented on these versions.
  539. *
  540. * See the $sce documentation, section
  541. * <a href="https://docs.angularjs.org/api/ng/service/$sce#impact-on-loading-templates">
  542. * Impact on loading templates</a> for more details about this mechanism.
  543. *
  544. * @param {boolean} value
  545. */
  546. this.shouldUnsafelyUseHttp = function (value) {
  547. shouldUnsafelyUseHttp = !!value;
  548. };
  549. /**
  550. * @ngdoc object
  551. * @name ui.router.util.$templateFactory
  552. *
  553. * @requires $http
  554. * @requires $templateCache
  555. * @requires $injector
  556. *
  557. * @description
  558. * Service. Manages loading of templates.
  559. */
  560. this.$get = ['$http', '$templateCache', '$injector', function ($http, $templateCache, $injector) {
  561. return new TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp);
  562. }];
  563. }
  564. /**
  565. * @ngdoc object
  566. * @name ui.router.util.$templateFactory
  567. *
  568. * @requires $http
  569. * @requires $templateCache
  570. * @requires $injector
  571. *
  572. * @description
  573. * Service. Manages loading of templates.
  574. */
  575. function TemplateFactory($http, $templateCache, $injector, shouldUnsafelyUseHttp) {
  576. /**
  577. * @ngdoc function
  578. * @name ui.router.util.$templateFactory#fromConfig
  579. * @methodOf ui.router.util.$templateFactory
  580. *
  581. * @description
  582. * Creates a template from a configuration object.
  583. *
  584. * @param {object} config Configuration object for which to load a template.
  585. * The following properties are search in the specified order, and the first one
  586. * that is defined is used to create the template:
  587. *
  588. * @param {string|object} config.template html string template or function to
  589. * load via {@link ui.router.util.$templateFactory#fromString fromString}.
  590. * @param {string|object} config.templateUrl url to load or a function returning
  591. * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.
  592. * @param {Function} config.templateProvider function to invoke via
  593. * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.
  594. * @param {object} params Parameters to pass to the template function.
  595. * @param {object} locals Locals to pass to `invoke` if the template is loaded
  596. * via a `templateProvider`. Defaults to `{ params: params }`.
  597. *
  598. * @return {string|object} The template html as a string, or a promise for
  599. * that string,or `null` if no template is configured.
  600. */
  601. this.fromConfig = function (config, params, locals) {
  602. return (
  603. isDefined(config.template) ? this.fromString(config.template, params) :
  604. isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :
  605. isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :
  606. null
  607. );
  608. };
  609. /**
  610. * @ngdoc function
  611. * @name ui.router.util.$templateFactory#fromString
  612. * @methodOf ui.router.util.$templateFactory
  613. *
  614. * @description
  615. * Creates a template from a string or a function returning a string.
  616. *
  617. * @param {string|object} template html template as a string or function that
  618. * returns an html template as a string.
  619. * @param {object} params Parameters to pass to the template function.
  620. *
  621. * @return {string|object} The template html as a string, or a promise for that
  622. * string.
  623. */
  624. this.fromString = function (template, params) {
  625. return isFunction(template) ? template(params) : template;
  626. };
  627. /**
  628. * @ngdoc function
  629. * @name ui.router.util.$templateFactory#fromUrl
  630. * @methodOf ui.router.util.$templateFactory
  631. *
  632. * @description
  633. * Loads a template from the a URL via `$http` and `$templateCache`.
  634. *
  635. * @param {string|Function} url url of the template to load, or a function
  636. * that returns a url.
  637. * @param {Object} params Parameters to pass to the url function.
  638. * @return {string|Promise.<string>} The template html as a string, or a promise
  639. * for that string.
  640. */
  641. this.fromUrl = function (url, params) {
  642. if (isFunction(url)) url = url(params);
  643. if (url == null) return null;
  644. else {
  645. if (!shouldUnsafelyUseHttp) {
  646. return $injector.get('$templateRequest')(url);
  647. } else {
  648. return $http
  649. .get(url, {cache: $templateCache, headers: {Accept: 'text/html'}})
  650. .then(function (response) {
  651. return response.data;
  652. });
  653. }
  654. }
  655. };
  656. /**
  657. * @ngdoc function
  658. * @name ui.router.util.$templateFactory#fromProvider
  659. * @methodOf ui.router.util.$templateFactory
  660. *
  661. * @description
  662. * Creates a template by invoking an injectable provider function.
  663. *
  664. * @param {Function} provider Function to invoke via `$injector.invoke`
  665. * @param {Object} params Parameters for the template.
  666. * @param {Object} locals Locals to pass to `invoke`. Defaults to
  667. * `{ params: params }`.
  668. * @return {string|Promise.<string>} The template html as a string, or a promise
  669. * for that string.
  670. */
  671. this.fromProvider = function (provider, params, locals) {
  672. return $injector.invoke(provider, null, locals || {params: params});
  673. };
  674. }
  675. angular.module('ui.router.util').provider('$templateFactory', TemplateFactoryProvider);
  676. var $$UMFP; // reference to $UrlMatcherFactoryProvider
  677. /**
  678. * @ngdoc object
  679. * @name ui.router.util.type:UrlMatcher
  680. *
  681. * @description
  682. * Matches URLs against patterns and extracts named parameters from the path or the search
  683. * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list
  684. * of search parameters. Multiple search parameter names are separated by '&'. Search parameters
  685. * do not influence whether or not a URL is matched, but their values are passed through into
  686. * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.
  687. *
  688. * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace
  689. * syntax, which optionally allows a regular expression for the parameter to be specified:
  690. *
  691. * * `':'` name - colon placeholder
  692. * * `'*'` name - catch-all placeholder
  693. * * `'{' name '}'` - curly placeholder
  694. * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the
  695. * regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
  696. *
  697. * Parameter names may contain only word characters (latin letters, digits, and underscore) and
  698. * must be unique within the pattern (across both path and search parameters). For colon
  699. * placeholders or curly placeholders without an explicit regexp, a path parameter matches any
  700. * number of characters other than '/'. For catch-all placeholders the path parameter matches
  701. * any number of characters.
  702. *
  703. * Examples:
  704. *
  705. * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for
  706. * trailing slashes, and patterns have to match the entire path, not just a prefix.
  707. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or
  708. * '/user/bob/details'. The second path segment will be captured as the parameter 'id'.
  709. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.
  710. * * `'/user/{id:[^/]*}'` - Same as the previous example.
  711. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id
  712. * parameter consists of 1 to 8 hex digits.
  713. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the
  714. * path into the parameter 'path'.
  715. * * `'/files/*path'` - ditto.
  716. * * `'/calendar/{start:date}'` - Matches "/calendar/2014-11-12" (because the pattern defined
  717. * in the built-in `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start
  718. *
  719. * @param {string} pattern The pattern to compile into a matcher.
  720. * @param {Object} config A configuration object hash:
  721. * @param {Object=} parentMatcher Used to concatenate the pattern/config onto
  722. * an existing UrlMatcher
  723. *
  724. * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.
  725. * * `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`.
  726. *
  727. * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any
  728. * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns
  729. * non-null) will start with this prefix.
  730. *
  731. * @property {string} source The pattern that was passed into the constructor
  732. *
  733. * @property {string} sourcePath The path portion of the source property
  734. *
  735. * @property {string} sourceSearch The search portion of the source property
  736. *
  737. * @property {string} regex The constructed regex that will be used to match against the url when
  738. * it is time to determine which url will match.
  739. *
  740. * @returns {Object} New `UrlMatcher` object
  741. */
  742. function UrlMatcher(pattern, config, parentMatcher) {
  743. config = extend({params: {}}, isObject(config) ? config : {});
  744. // Find all placeholders and create a compiled pattern, using either classic or curly syntax:
  745. // '*' name
  746. // ':' name
  747. // '{' name '}'
  748. // '{' name ':' regexp '}'
  749. // The regular expression is somewhat complicated due to the need to allow curly braces
  750. // inside the regular expression. The placeholder regexp breaks down as follows:
  751. // ([:*])([\w\[\]]+) - classic placeholder ($1 / $2) (search version has - for snake-case)
  752. // \{([\w\[\]]+)(?:\:\s*( ... ))?\} - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case
  753. // (?: ... | ... | ... )+ - the regexp consists of any number of atoms, an atom being either
  754. // [^{}\\]+ - anything other than curly braces or backslash
  755. // \\. - a backslash escape
  756. // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms
  757. var placeholder = /([:*])([\w\[\]]+)|\{([\w\[\]]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  758. searchPlaceholder = /([:]?)([\w\[\].-]+)|\{([\w\[\].-]+)(?:\:\s*((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g,
  759. compiled = '^', last = 0, m,
  760. segments = this.segments = [],
  761. parentParams = parentMatcher ? parentMatcher.params : {},
  762. params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),
  763. paramNames = [];
  764. function addParameter(id, type, config, location) {
  765. paramNames.push(id);
  766. if (parentParams[id]) return parentParams[id];
  767. if (!/^\w+([-.]+\w+)*(?:\[\])?$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'");
  768. if (params[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'");
  769. params[id] = new $$UMFP.Param(id, type, config, location);
  770. return params[id];
  771. }
  772. function quoteRegExp(string, pattern, squash, optional) {
  773. var surroundPattern = ['', ''], result = string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&");
  774. if (!pattern) return result;
  775. switch (squash) {
  776. case false:
  777. surroundPattern = ['(', ')' + (optional ? "?" : "")];
  778. break;
  779. case true:
  780. result = result.replace(/\/$/, '');
  781. surroundPattern = ['(?:\/(', ')|\/)?'];
  782. break;
  783. default:
  784. surroundPattern = ['(' + squash + "|", ')?'];
  785. break;
  786. }
  787. return result + surroundPattern[0] + pattern + surroundPattern[1];
  788. }
  789. this.source = pattern;
  790. // Split into static segments separated by path parameter placeholders.
  791. // The number of segments is always 1 more than the number of parameters.
  792. function matchDetails(m, isSearch) {
  793. var id, regexp, segment, type, cfg, arrayMode;
  794. id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null
  795. cfg = config.params[id];
  796. segment = pattern.substring(last, m.index);
  797. regexp = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);
  798. if (regexp) {
  799. type = $$UMFP.type(regexp) || inherit($$UMFP.type("string"), {pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined)});
  800. }
  801. return {
  802. id: id, regexp: regexp, segment: segment, type: type, cfg: cfg
  803. };
  804. }
  805. var p, param, segment;
  806. while ((m = placeholder.exec(pattern))) {
  807. p = matchDetails(m, false);
  808. if (p.segment.indexOf('?') >= 0) break; // we're into the search part
  809. param = addParameter(p.id, p.type, p.cfg, "path");
  810. compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);
  811. segments.push(p.segment);
  812. last = placeholder.lastIndex;
  813. }
  814. segment = pattern.substring(last);
  815. // Find any search parameter names and remove them from the last segment
  816. var i = segment.indexOf('?');
  817. if (i >= 0) {
  818. var search = this.sourceSearch = segment.substring(i);
  819. segment = segment.substring(0, i);
  820. this.sourcePath = pattern.substring(0, last + i);
  821. if (search.length > 0) {
  822. last = 0;
  823. while ((m = searchPlaceholder.exec(search))) {
  824. p = matchDetails(m, true);
  825. param = addParameter(p.id, p.type, p.cfg, "search");
  826. last = placeholder.lastIndex;
  827. // check if ?&
  828. }
  829. }
  830. } else {
  831. this.sourcePath = pattern;
  832. this.sourceSearch = '';
  833. }
  834. compiled += quoteRegExp(segment) + (config.strict === false ? '\/?' : '') + '$';
  835. segments.push(segment);
  836. this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);
  837. this.prefix = segments[0];
  838. this.$$paramNames = paramNames;
  839. }
  840. /**
  841. * @ngdoc function
  842. * @name ui.router.util.type:UrlMatcher#concat
  843. * @methodOf ui.router.util.type:UrlMatcher
  844. *
  845. * @description
  846. * Returns a new matcher for a pattern constructed by appending the path part and adding the
  847. * search parameters of the specified pattern to this pattern. The current pattern is not
  848. * modified. This can be understood as creating a pattern for URLs that are relative to (or
  849. * suffixes of) the current pattern.
  850. *
  851. * @example
  852. * The following two matchers are equivalent:
  853. * <pre>
  854. * new UrlMatcher('/user/{id}?q').concat('/details?date');
  855. * new UrlMatcher('/user/{id}/details?q&date');
  856. * </pre>
  857. *
  858. * @param {string} pattern The pattern to append.
  859. * @param {Object} config An object hash of the configuration for the matcher.
  860. * @returns {UrlMatcher} A matcher for the concatenated pattern.
  861. */
  862. UrlMatcher.prototype.concat = function (pattern, config) {
  863. // Because order of search parameters is irrelevant, we can add our own search
  864. // parameters to the end of the new pattern. Parse the new pattern by itself
  865. // and then join the bits together, but it's much easier to do this on a string level.
  866. var defaultConfig = {
  867. caseInsensitive: $$UMFP.caseInsensitive(),
  868. strict: $$UMFP.strictMode(),
  869. squash: $$UMFP.defaultSquashPolicy()
  870. };
  871. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);
  872. };
  873. UrlMatcher.prototype.toString = function () {
  874. return this.source;
  875. };
  876. /**
  877. * @ngdoc function
  878. * @name ui.router.util.type:UrlMatcher#exec
  879. * @methodOf ui.router.util.type:UrlMatcher
  880. *
  881. * @description
  882. * Tests the specified path against this matcher, and returns an object containing the captured
  883. * parameter values, or null if the path does not match. The returned object contains the values
  884. * of any search parameters that are mentioned in the pattern, but their value may be null if
  885. * they are not present in `searchParams`. This means that search parameters are always treated
  886. * as optional.
  887. *
  888. * @example
  889. * <pre>
  890. * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {
  891. * x: '1', q: 'hello'
  892. * });
  893. * // returns { id: 'bob', q: 'hello', r: null }
  894. * </pre>
  895. *
  896. * @param {string} path The URL path to match, e.g. `$location.path()`.
  897. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`.
  898. * @returns {Object} The captured parameter values.
  899. */
  900. UrlMatcher.prototype.exec = function (path, searchParams) {
  901. var m = this.regexp.exec(path);
  902. if (!m) return null;
  903. searchParams = searchParams || {};
  904. var paramNames = this.parameters(), nTotal = paramNames.length,
  905. nPath = this.segments.length - 1,
  906. values = {}, i, j, cfg, paramName;
  907. if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'");
  908. function decodePathArray(string) {
  909. function reverseString(str) {
  910. return str.split("").reverse().join("");
  911. }
  912. function unquoteDashes(str) {
  913. return str.replace(/\\-/g, "-");
  914. }
  915. var split = reverseString(string).split(/-(?!\\)/);
  916. var allReversed = map(split, reverseString);
  917. return map(allReversed, unquoteDashes).reverse();
  918. }
  919. var param, paramVal;
  920. for (i = 0; i < nPath; i++) {
  921. paramName = paramNames[i];
  922. param = this.params[paramName];
  923. paramVal = m[i + 1];
  924. // if the param value matches a pre-replace pair, replace the value before decoding.
  925. for (j = 0; j < param.replace.length; j++) {
  926. if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
  927. }
  928. if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);
  929. if (isDefined(paramVal)) paramVal = param.type.decode(paramVal);
  930. values[paramName] = param.value(paramVal);
  931. }
  932. for (/**/; i < nTotal; i++) {
  933. paramName = paramNames[i];
  934. values[paramName] = this.params[paramName].value(searchParams[paramName]);
  935. param = this.params[paramName];
  936. paramVal = searchParams[paramName];
  937. for (j = 0; j < param.replace.length; j++) {
  938. if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;
  939. }
  940. if (isDefined(paramVal)) paramVal = param.type.decode(paramVal);
  941. values[paramName] = param.value(paramVal);
  942. }
  943. return values;
  944. };
  945. /**
  946. * @ngdoc function
  947. * @name ui.router.util.type:UrlMatcher#parameters
  948. * @methodOf ui.router.util.type:UrlMatcher
  949. *
  950. * @description
  951. * Returns the names of all path and search parameters of this pattern in an unspecified order.
  952. *
  953. * @returns {Array.<string>} An array of parameter names. Must be treated as read-only. If the
  954. * pattern has no parameters, an empty array is returned.
  955. */
  956. UrlMatcher.prototype.parameters = function (param) {
  957. if (!isDefined(param)) return this.$$paramNames;
  958. return this.params[param] || null;
  959. };
  960. /**
  961. * @ngdoc function
  962. * @name ui.router.util.type:UrlMatcher#validates
  963. * @methodOf ui.router.util.type:UrlMatcher
  964. *
  965. * @description
  966. * Checks an object hash of parameters to validate their correctness according to the parameter
  967. * types of this `UrlMatcher`.
  968. *
  969. * @param {Object} params The object hash of parameters to validate.
  970. * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.
  971. */
  972. UrlMatcher.prototype.validates = function (params) {
  973. return this.params.$$validates(params);
  974. };
  975. /**
  976. * @ngdoc function
  977. * @name ui.router.util.type:UrlMatcher#format
  978. * @methodOf ui.router.util.type:UrlMatcher
  979. *
  980. * @description
  981. * Creates a URL that matches this pattern by substituting the specified values
  982. * for the path and search parameters. Null values for path parameters are
  983. * treated as empty strings.
  984. *
  985. * @example
  986. * <pre>
  987. * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });
  988. * // returns '/user/bob?q=yes'
  989. * </pre>
  990. *
  991. * @param {Object} values the values to substitute for the parameters in this pattern.
  992. * @returns {string} the formatted URL (path and optionally search part).
  993. */
  994. UrlMatcher.prototype.format = function (values) {
  995. values = values || {};
  996. var segments = this.segments, params = this.parameters(), paramset = this.params;
  997. if (!this.validates(values)) return null;
  998. var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];
  999. function encodeDashes(str) { // Replace dashes with encoded "\-"
  1000. return encodeURIComponent(str).replace(/-/g, function (c) {
  1001. return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase();
  1002. });
  1003. }
  1004. for (i = 0; i < nTotal; i++) {
  1005. var isPathParam = i < nPath;
  1006. var name = params[i], param = paramset[name], value = param.value(values[name]);
  1007. var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);
  1008. var squash = isDefaultValue ? param.squash : false;
  1009. var encoded = param.type.encode(value);
  1010. if (isPathParam) {
  1011. var nextSegment = segments[i + 1];
  1012. var isFinalPathParam = i + 1 === nPath;
  1013. if (squash === false) {
  1014. if (encoded != null) {
  1015. if (isArray(encoded)) {
  1016. result += map(encoded, encodeDashes).join("-");
  1017. } else {
  1018. result += encodeURIComponent(encoded);
  1019. }
  1020. }
  1021. result += nextSegment;
  1022. } else if (squash === true) {
  1023. var capture = result.match(/\/$/) ? /\/?(.*)/ : /(.*)/;
  1024. result += nextSegment.match(capture)[1];
  1025. } else if (isString(squash)) {
  1026. result += squash + nextSegment;
  1027. }
  1028. if (isFinalPathParam && param.squash === true && result.slice(-1) === '/') result = result.slice(0, -1);
  1029. } else {
  1030. if (encoded == null || (isDefaultValue && squash !== false)) continue;
  1031. if (!isArray(encoded)) encoded = [encoded];
  1032. if (encoded.length === 0) continue;
  1033. encoded = map(encoded, encodeURIComponent).join('&' + name + '=');
  1034. result += (search ? '&' : '?') + (name + '=' + encoded);
  1035. search = true;
  1036. }
  1037. }
  1038. return result;
  1039. };
  1040. /**
  1041. * @ngdoc object
  1042. * @name ui.router.util.type:Type
  1043. *
  1044. * @description
  1045. * Implements an interface to define custom parameter types that can be decoded from and encoded to
  1046. * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}
  1047. * objects when matching or formatting URLs, or comparing or validating parameter values.
  1048. *
  1049. * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more
  1050. * information on registering custom types.
  1051. *
  1052. * @param {Object} config A configuration object which contains the custom type definition. The object's
  1053. * properties will override the default methods and/or pattern in `Type`'s public interface.
  1054. * @example
  1055. * <pre>
  1056. * {
  1057. * decode: function(val) { return parseInt(val, 10); },
  1058. * encode: function(val) { return val && val.toString(); },
  1059. * equals: function(a, b) { return this.is(a) && a === b; },
  1060. * is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },
  1061. * pattern: /\d+/
  1062. * }
  1063. * </pre>
  1064. *
  1065. * @property {RegExp} pattern The regular expression pattern used to match values of this type when
  1066. * coming from a substring of a URL.
  1067. *
  1068. * @returns {Object} Returns a new `Type` object.
  1069. */
  1070. function Type(config) {
  1071. extend(this, config);
  1072. }
  1073. /**
  1074. * @ngdoc function
  1075. * @name ui.router.util.type:Type#is
  1076. * @methodOf ui.router.util.type:Type
  1077. *
  1078. * @description
  1079. * Detects whether a value is of a particular type. Accepts a native (decoded) value
  1080. * and determines whether it matches the current `Type` object.
  1081. *
  1082. * @param {*} val The value to check.
  1083. * @param {string} key Optional. If the type check is happening in the context of a specific
  1084. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the
  1085. * parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.
  1086. * @returns {Boolean} Returns `true` if the value matches the type, otherwise `false`.
  1087. */
  1088. Type.prototype.is = function (val, key) {
  1089. return true;
  1090. };
  1091. /**
  1092. * @ngdoc function
  1093. * @name ui.router.util.type:Type#encode
  1094. * @methodOf ui.router.util.type:Type
  1095. *
  1096. * @description
  1097. * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the
  1098. * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it
  1099. * only needs to be a representation of `val` that has been coerced to a string.
  1100. *
  1101. * @param {*} val The value to encode.
  1102. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  1103. * meta-programming of `Type` objects.
  1104. * @returns {string} Returns a string representation of `val` that can be encoded in a URL.
  1105. */
  1106. Type.prototype.encode = function (val, key) {
  1107. return val;
  1108. };
  1109. /**
  1110. * @ngdoc function
  1111. * @name ui.router.util.type:Type#decode
  1112. * @methodOf ui.router.util.type:Type
  1113. *
  1114. * @description
  1115. * Converts a parameter value (from URL string or transition param) to a custom/native value.
  1116. *
  1117. * @param {string} val The URL parameter value to decode.
  1118. * @param {string} key The name of the parameter in which `val` is stored. Can be used for
  1119. * meta-programming of `Type` objects.
  1120. * @returns {*} Returns a custom representation of the URL parameter value.
  1121. */
  1122. Type.prototype.decode = function (val, key) {
  1123. return val;
  1124. };
  1125. /**
  1126. * @ngdoc function
  1127. * @name ui.router.util.type:Type#equals
  1128. * @methodOf ui.router.util.type:Type
  1129. *
  1130. * @description
  1131. * Determines whether two decoded values are equivalent.
  1132. *
  1133. * @param {*} a A value to compare against.
  1134. * @param {*} b A value to compare against.
  1135. * @returns {Boolean} Returns `true` if the values are equivalent/equal, otherwise `false`.
  1136. */
  1137. Type.prototype.equals = function (a, b) {
  1138. return a == b;
  1139. };
  1140. Type.prototype.$subPattern = function () {
  1141. var sub = this.pattern.toString();
  1142. return sub.substr(1, sub.length - 2);
  1143. };
  1144. Type.prototype.pattern = /.*/;
  1145. Type.prototype.toString = function () {
  1146. return "{Type:" + this.name + "}";
  1147. };
  1148. /** Given an encoded string, or a decoded object, returns a decoded object */
  1149. Type.prototype.$normalize = function (val) {
  1150. return this.is(val) ? val : this.decode(val);
  1151. };
  1152. /*
  1153. * Wraps an existing custom Type as an array of Type, depending on 'mode'.
  1154. * e.g.:
  1155. * - urlmatcher pattern "/path?{queryParam[]:int}"
  1156. * - url: "/path?queryParam=1&queryParam=2
  1157. * - $stateParams.queryParam will be [1, 2]
  1158. * if `mode` is "auto", then
  1159. * - url: "/path?queryParam=1 will create $stateParams.queryParam: 1
  1160. * - url: "/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]
  1161. */
  1162. Type.prototype.$asArray = function (mode, isSearch) {
  1163. if (!mode) return this;
  1164. if (mode === "auto" && !isSearch) throw new Error("'auto' array mode is for query parameters only");
  1165. function ArrayType(type, mode) {
  1166. function bindTo(type, callbackName) {
  1167. return function () {
  1168. return type[callbackName].apply(type, arguments);
  1169. };
  1170. }
  1171. // Wrap non-array value as array
  1172. function arrayWrap(val) {
  1173. return isArray(val) ? val : (isDefined(val) ? [val] : []);
  1174. }
  1175. // Unwrap array value for "auto" mode. Return undefined for empty array.
  1176. function arrayUnwrap(val) {
  1177. switch (val.length) {
  1178. case 0:
  1179. return undefined;
  1180. case 1:
  1181. return mode === "auto" ? val[0] : val;
  1182. default:
  1183. return val;
  1184. }
  1185. }
  1186. function falsey(val) {
  1187. return !val;
  1188. }
  1189. // Wraps type (.is/.encode/.decode) functions to operate on each value of an array
  1190. function arrayHandler(callback, allTruthyMode) {
  1191. return function handleArray(val) {
  1192. if (isArray(val) && val.length === 0) return val;
  1193. val = arrayWrap(val);
  1194. var result = map(val, callback);
  1195. if (allTruthyMode === true)
  1196. return filter(result, falsey).length === 0;
  1197. return arrayUnwrap(result);
  1198. };
  1199. }
  1200. // Wraps type (.equals) functions to operate on each value of an array
  1201. function arrayEqualsHandler(callback) {
  1202. return function handleArray(val1, val2) {
  1203. var left = arrayWrap(val1), right = arrayWrap(val2);
  1204. if (left.length !== right.length) return false;
  1205. for (var i = 0; i < left.length; i++) {
  1206. if (!callback(left[i], right[i])) return false;
  1207. }
  1208. return true;
  1209. };
  1210. }
  1211. this.encode = arrayHandler(bindTo(type, 'encode'));
  1212. this.decode = arrayHandler(bindTo(type, 'decode'));
  1213. this.is = arrayHandler(bindTo(type, 'is'), true);
  1214. this.equals = arrayEqualsHandler(bindTo(type, 'equals'));
  1215. this.pattern = type.pattern;
  1216. this.$normalize = arrayHandler(bindTo(type, '$normalize'));
  1217. this.name = type.name;
  1218. this.$arrayMode = mode;
  1219. }
  1220. return new ArrayType(this, mode);
  1221. };
  1222. /**
  1223. * @ngdoc object
  1224. * @name ui.router.util.$urlMatcherFactory
  1225. *
  1226. * @description
  1227. * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory
  1228. * is also available to providers under the name `$urlMatcherFactoryProvider`.
  1229. */
  1230. function $UrlMatcherFactory() {
  1231. $$UMFP = this;
  1232. var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;
  1233. // Use tildes to pre-encode slashes.
  1234. // If the slashes are simply URLEncoded, the browser can choose to pre-decode them,
  1235. // and bidirectional encoding/decoding fails.
  1236. // Tilde was chosen because it's not a RFC 3986 section 2.2 Reserved Character
  1237. function valToString(val) {
  1238. return val != null ? val.toString().replace(/(~|\/)/g, function (m) {
  1239. return {'~': '~~', '/': '~2F'}[m];
  1240. }) : val;
  1241. }
  1242. function valFromString(val) {
  1243. return val != null ? val.toString().replace(/(~~|~2F)/g, function (m) {
  1244. return {'~~': '~', '~2F': '/'}[m];
  1245. }) : val;
  1246. }
  1247. var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {
  1248. "string": {
  1249. encode: valToString,
  1250. decode: valFromString,
  1251. // TODO: in 1.0, make string .is() return false if value is undefined/null by default.
  1252. // In 0.2.x, string params are optional by default for backwards compat
  1253. is: function (val) {
  1254. return val == null || !isDefined(val) || typeof val === "string";
  1255. },
  1256. pattern: /[^/]*/
  1257. },
  1258. "int": {
  1259. encode: valToString,
  1260. decode: function (val) {
  1261. return parseInt(val, 10);
  1262. },
  1263. is: function (val) {
  1264. return val !== undefined && val !== null && this.decode(val.toString()) === val;
  1265. },
  1266. pattern: /\d+/
  1267. },
  1268. "bool": {
  1269. encode: function (val) {
  1270. return val ? 1 : 0;
  1271. },
  1272. decode: function (val) {
  1273. return parseInt(val, 10) !== 0;
  1274. },
  1275. is: function (val) {
  1276. return val === true || val === false;
  1277. },
  1278. pattern: /0|1/
  1279. },
  1280. "date": {
  1281. encode: function (val) {
  1282. if (!this.is(val))
  1283. return undefined;
  1284. return [val.getFullYear(),
  1285. ('0' + (val.getMonth() + 1)).slice(-2),
  1286. ('0' + val.getDate()).slice(-2)
  1287. ].join("-");
  1288. },
  1289. decode: function (val) {
  1290. if (this.is(val)) return val;
  1291. var match = this.capture.exec(val);
  1292. return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;
  1293. },
  1294. is: function (val) {
  1295. return val instanceof Date && !isNaN(val.valueOf());
  1296. },
  1297. equals: function (a, b) {
  1298. return this.is(a) && this.is(b) && a.toISOString() === b.toISOString();
  1299. },
  1300. pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,
  1301. capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/
  1302. },
  1303. "json": {
  1304. encode: angular.toJson,
  1305. decode: angular.fromJson,
  1306. is: angular.isObject,
  1307. equals: angular.equals,
  1308. pattern: /[^/]*/
  1309. },
  1310. "any": { // does not encode/decode
  1311. encode: angular.identity,
  1312. decode: angular.identity,
  1313. equals: angular.equals,
  1314. pattern: /.*/
  1315. }
  1316. };
  1317. function getDefaultConfig() {
  1318. return {
  1319. strict: isStrictMode,
  1320. caseInsensitive: isCaseInsensitive
  1321. };
  1322. }
  1323. function isInjectable(value) {
  1324. return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));
  1325. }
  1326. /**
  1327. * [Internal] Get the default value of a parameter, which may be an injectable function.
  1328. */
  1329. $UrlMatcherFactory.$$getDefaultValue = function (config) {
  1330. if (!isInjectable(config.value)) return config.value;
  1331. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  1332. return injector.invoke(config.value);
  1333. };
  1334. /**
  1335. * @ngdoc function
  1336. * @name ui.router.util.$urlMatcherFactory#caseInsensitive
  1337. * @methodOf ui.router.util.$urlMatcherFactory
  1338. *
  1339. * @description
  1340. * Defines whether URL matching should be case sensitive (the default behavior), or not.
  1341. *
  1342. * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;
  1343. * @returns {boolean} the current value of caseInsensitive
  1344. */
  1345. this.caseInsensitive = function (value) {
  1346. if (isDefined(value))
  1347. isCaseInsensitive = value;
  1348. return isCaseInsensitive;
  1349. };
  1350. /**
  1351. * @ngdoc function
  1352. * @name ui.router.util.$urlMatcherFactory#strictMode
  1353. * @methodOf ui.router.util.$urlMatcherFactory
  1354. *
  1355. * @description
  1356. * Defines whether URLs should match trailing slashes, or not (the default behavior).
  1357. *
  1358. * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.
  1359. * @returns {boolean} the current value of strictMode
  1360. */
  1361. this.strictMode = function (value) {
  1362. if (isDefined(value))
  1363. isStrictMode = value;
  1364. return isStrictMode;
  1365. };
  1366. /**
  1367. * @ngdoc function
  1368. * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy
  1369. * @methodOf ui.router.util.$urlMatcherFactory
  1370. *
  1371. * @description
  1372. * Sets the default behavior when generating or matching URLs with default parameter values.
  1373. *
  1374. * @param {string} value A string that defines the default parameter URL squashing behavior.
  1375. * `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL
  1376. * `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the
  1377. * parameter is surrounded by slashes, squash (remove) one slash from the URL
  1378. * any other string, e.g. "~": When generating an href with a default parameter value, squash (remove)
  1379. * the parameter value from the URL and replace it with this string.
  1380. */
  1381. this.defaultSquashPolicy = function (value) {
  1382. if (!isDefined(value)) return defaultSquashPolicy;
  1383. if (value !== true && value !== false && !isString(value))
  1384. throw new Error("Invalid squash policy: " + value + ". Valid policies: false, true, arbitrary-string");
  1385. defaultSquashPolicy = value;
  1386. return value;
  1387. };
  1388. /**
  1389. * @ngdoc function
  1390. * @name ui.router.util.$urlMatcherFactory#compile
  1391. * @methodOf ui.router.util.$urlMatcherFactory
  1392. *
  1393. * @description
  1394. * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.
  1395. *
  1396. * @param {string} pattern The URL pattern.
  1397. * @param {Object} config The config object hash.
  1398. * @returns {UrlMatcher} The UrlMatcher.
  1399. */
  1400. this.compile = function (pattern, config) {
  1401. return new UrlMatcher(pattern, extend(getDefaultConfig(), config));
  1402. };
  1403. /**
  1404. * @ngdoc function
  1405. * @name ui.router.util.$urlMatcherFactory#isMatcher
  1406. * @methodOf ui.router.util.$urlMatcherFactory
  1407. *
  1408. * @description
  1409. * Returns true if the specified object is a `UrlMatcher`, or false otherwise.
  1410. *
  1411. * @param {Object} object The object to perform the type check against.
  1412. * @returns {Boolean} Returns `true` if the object matches the `UrlMatcher` interface, by
  1413. * implementing all the same methods.
  1414. */
  1415. this.isMatcher = function (o) {
  1416. if (!isObject(o)) return false;
  1417. var result = true;
  1418. forEach(UrlMatcher.prototype, function (val, name) {
  1419. if (isFunction(val)) {
  1420. result = result && (isDefined(o[name]) && isFunction(o[name]));
  1421. }
  1422. });
  1423. return result;
  1424. };
  1425. /**
  1426. * @ngdoc function
  1427. * @name ui.router.util.$urlMatcherFactory#type
  1428. * @methodOf ui.router.util.$urlMatcherFactory
  1429. *
  1430. * @description
  1431. * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to
  1432. * generate URLs with typed parameters.
  1433. *
  1434. * @param {string} name The type name.
  1435. * @param {Object|Function} definition The type definition. See
  1436. * {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  1437. * @param {Object|Function} definitionFn (optional) A function that is injected before the app
  1438. * runtime starts. The result of this function is merged into the existing `definition`.
  1439. * See {@link ui.router.util.type:Type `Type`} for information on the values accepted.
  1440. *
  1441. * @returns {Object} Returns `$urlMatcherFactoryProvider`.
  1442. *
  1443. * @example
  1444. * This is a simple example of a custom type that encodes and decodes items from an
  1445. * array, using the array index as the URL-encoded value:
  1446. *
  1447. * <pre>
  1448. * var list = ['John', 'Paul', 'George', 'Ringo'];
  1449. *
  1450. * $urlMatcherFactoryProvider.type('listItem', {
  1451. * encode: function(item) {
  1452. * // Represent the list item in the URL using its corresponding index
  1453. * return list.indexOf(item);
  1454. * },
  1455. * decode: function(item) {
  1456. * // Look up the list item by index
  1457. * return list[parseInt(item, 10)];
  1458. * },
  1459. * is: function(item) {
  1460. * // Ensure the item is valid by checking to see that it appears
  1461. * // in the list
  1462. * return list.indexOf(item) > -1;
  1463. * }
  1464. * });
  1465. *
  1466. * $stateProvider.state('list', {
  1467. * url: "/list/{item:listItem}",
  1468. * controller: function($scope, $stateParams) {
  1469. * console.log($stateParams.item);
  1470. * }
  1471. * });
  1472. *
  1473. * // ...
  1474. *
  1475. * // Changes URL to '/list/3', logs "Ringo" to the console
  1476. * $state.go('list', { item: "Ringo" });
  1477. * </pre>
  1478. *
  1479. * This is a more complex example of a type that relies on dependency injection to
  1480. * interact with services, and uses the parameter name from the URL to infer how to
  1481. * handle encoding and decoding parameter values:
  1482. *
  1483. * <pre>
  1484. * // Defines a custom type that gets a value from a service,
  1485. * // where each service gets different types of values from
  1486. * // a backend API:
  1487. * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {
  1488. *
  1489. * // Matches up services to URL parameter names
  1490. * var services = {
  1491. * user: Users,
  1492. * post: Posts
  1493. * };
  1494. *
  1495. * return {
  1496. * encode: function(object) {
  1497. * // Represent the object in the URL using its unique ID
  1498. * return object.id;
  1499. * },
  1500. * decode: function(value, key) {
  1501. * // Look up the object by ID, using the parameter
  1502. * // name (key) to call the correct service
  1503. * return services[key].findById(value);
  1504. * },
  1505. * is: function(object, key) {
  1506. * // Check that object is a valid dbObject
  1507. * return angular.isObject(object) && object.id && services[key];
  1508. * }
  1509. * equals: function(a, b) {
  1510. * // Check the equality of decoded objects by comparing
  1511. * // their unique IDs
  1512. * return a.id === b.id;
  1513. * }
  1514. * };
  1515. * });
  1516. *
  1517. * // In a config() block, you can then attach URLs with
  1518. * // type-annotated parameters:
  1519. * $stateProvider.state('users', {
  1520. * url: "/users",
  1521. * // ...
  1522. * }).state('users.item', {
  1523. * url: "/{user:dbObject}",
  1524. * controller: function($scope, $stateParams) {
  1525. * // $stateParams.user will now be an object returned from
  1526. * // the Users service
  1527. * },
  1528. * // ...
  1529. * });
  1530. * </pre>
  1531. */
  1532. this.type = function (name, definition, definitionFn) {
  1533. if (!isDefined(definition)) return $types[name];
  1534. if ($types.hasOwnProperty(name)) throw new Error("A type named '" + name + "' has already been defined.");
  1535. $types[name] = new Type(extend({name: name}, definition));
  1536. if (definitionFn) {
  1537. typeQueue.push({name: name, def: definitionFn});
  1538. if (!enqueue) flushTypeQueue();
  1539. }
  1540. return this;
  1541. };
  1542. // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s
  1543. function flushTypeQueue() {
  1544. while (typeQueue.length) {
  1545. var type = typeQueue.shift();
  1546. if (type.pattern) throw new Error("You cannot override a type's .pattern at runtime.");
  1547. angular.extend($types[type.name], injector.invoke(type.def));
  1548. }
  1549. }
  1550. // Register default types. Store them in the prototype of $types.
  1551. forEach(defaultTypes, function (type, name) {
  1552. $types[name] = new Type(extend({name: name}, type));
  1553. });
  1554. $types = inherit($types, {});
  1555. /* No need to document $get, since it returns this */
  1556. this.$get = ['$injector', function ($injector) {
  1557. injector = $injector;
  1558. enqueue = false;
  1559. flushTypeQueue();
  1560. forEach(defaultTypes, function (type, name) {
  1561. if (!$types[name]) $types[name] = new Type(type);
  1562. });
  1563. return this;
  1564. }];
  1565. this.Param = function Param(id, type, config, location) {
  1566. var self = this;
  1567. config = unwrapShorthand(config);
  1568. type = getType(config, type, location);
  1569. var arrayMode = getArrayMode();
  1570. type = arrayMode ? type.$asArray(arrayMode, location === "search") : type;
  1571. if (type.name === "string" && !arrayMode && location === "path" && config.value === undefined)
  1572. config.value = ""; // for 0.2.x; in 0.3.0+ do not automatically default to ""
  1573. var isOptional = config.value !== undefined;
  1574. var squash = getSquashPolicy(config, isOptional);
  1575. var replace = getReplace(config, arrayMode, isOptional, squash);
  1576. function unwrapShorthand(config) {
  1577. var keys = isObject(config) ? objectKeys(config) : [];
  1578. var isShorthand = indexOf(keys, "value") === -1 && indexOf(keys, "type") === -1 &&
  1579. indexOf(keys, "squash") === -1 && indexOf(keys, "array") === -1;
  1580. if (isShorthand) config = {value: config};
  1581. config.$$fn = isInjectable(config.value) ? config.value : function () {
  1582. return config.value;
  1583. };
  1584. return config;
  1585. }
  1586. function getType(config, urlType, location) {
  1587. if (config.type && urlType) throw new Error("Param '" + id + "' has two type configurations.");
  1588. if (urlType) return urlType;
  1589. if (!config.type) return (location === "config" ? $types.any : $types.string);
  1590. if (angular.isString(config.type))
  1591. return $types[config.type];
  1592. if (config.type instanceof Type)
  1593. return config.type;
  1594. return new Type(config.type);
  1595. }
  1596. // array config: param name (param[]) overrides default settings. explicit config overrides param name.
  1597. function getArrayMode() {
  1598. var arrayDefaults = {array: (location === "search" ? "auto" : false)};
  1599. var arrayParamNomenclature = id.match(/\[\]$/) ? {array: true} : {};
  1600. return extend(arrayDefaults, arrayParamNomenclature, config).array;
  1601. }
  1602. /**
  1603. * returns false, true, or the squash value to indicate the "default parameter url squash policy".
  1604. */
  1605. function getSquashPolicy(config, isOptional) {
  1606. var squash = config.squash;
  1607. if (!isOptional || squash === false) return false;
  1608. if (!isDefined(squash) || squash == null) return defaultSquashPolicy;
  1609. if (squash === true || isString(squash)) return squash;
  1610. throw new Error("Invalid squash policy: '" + squash + "'. Valid policies: false, true, or arbitrary string");
  1611. }
  1612. function getReplace(config, arrayMode, isOptional, squash) {
  1613. var replace, configuredKeys, defaultPolicy = [
  1614. {from: "", to: (isOptional || arrayMode ? undefined : "")},
  1615. {from: null, to: (isOptional || arrayMode ? undefined : "")}
  1616. ];
  1617. replace = isArray(config.replace) ? config.replace : [];
  1618. if (isString(squash))
  1619. replace.push({from: squash, to: undefined});
  1620. configuredKeys = map(replace, function (item) {
  1621. return item.from;
  1622. });
  1623. return filter(defaultPolicy, function (item) {
  1624. return indexOf(configuredKeys, item.from) === -1;
  1625. }).concat(replace);
  1626. }
  1627. /**
  1628. * [Internal] Get the default value of a parameter, which may be an injectable function.
  1629. */
  1630. function $$getDefaultValue() {
  1631. if (!injector) throw new Error("Injectable functions cannot be called at configuration time");
  1632. var defaultValue = injector.invoke(config.$$fn);
  1633. if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))
  1634. throw new Error("Default value (" + defaultValue + ") for parameter '" + self.id + "' is not an instance of Type (" + self.type.name + ")");
  1635. return defaultValue;
  1636. }
  1637. /**
  1638. * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the
  1639. * default value, which may be the result of an injectable function.
  1640. */
  1641. function $value(value) {
  1642. function hasReplaceVal(val) {
  1643. return function (obj) {
  1644. return obj.from === val;
  1645. };
  1646. }
  1647. function $replace(value) {
  1648. var replacement = map(filter(self.replace, hasReplaceVal(value)), function (obj) {
  1649. return obj.to;
  1650. });
  1651. return replacement.length ? replacement[0] : value;
  1652. }
  1653. value = $replace(value);
  1654. return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);
  1655. }
  1656. function toString() {
  1657. return "{Param:" + id + " " + type + " squash: '" + squash + "' optional: " + isOptional + "}";
  1658. }
  1659. extend(this, {
  1660. id: id,
  1661. type: type,
  1662. location: location,
  1663. array: arrayMode,
  1664. squash: squash,
  1665. replace: replace,
  1666. isOptional: isOptional,
  1667. value: $value,
  1668. dynamic: undefined,
  1669. config: config,
  1670. toString: toString
  1671. });
  1672. };
  1673. function ParamSet(params) {
  1674. extend(this, params || {});
  1675. }
  1676. ParamSet.prototype = {
  1677. $$new: function () {
  1678. return inherit(this, extend(new ParamSet(), {$$parent: this}));
  1679. },
  1680. $$keys: function () {
  1681. var keys = [], chain = [], parent = this,
  1682. ignore = objectKeys(ParamSet.prototype);
  1683. while (parent) {
  1684. chain.push(parent);
  1685. parent = parent.$$parent;
  1686. }
  1687. chain.reverse();
  1688. forEach(chain, function (paramset) {
  1689. forEach(objectKeys(paramset), function (key) {
  1690. if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);
  1691. });
  1692. });
  1693. return keys;
  1694. },
  1695. $$values: function (paramValues) {
  1696. var values = {}, self = this;
  1697. forEach(self.$$keys(), function (key) {
  1698. values[key] = self[key].value(paramValues && paramValues[key]);
  1699. });
  1700. return values;
  1701. },
  1702. $$equals: function (paramValues1, paramValues2) {
  1703. var equal = true, self = this;
  1704. forEach(self.$$keys(), function (key) {
  1705. var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];
  1706. if (!self[key].type.equals(left, right)) equal = false;
  1707. });
  1708. return equal;
  1709. },
  1710. $$validates: function $$validate(paramValues) {
  1711. var keys = this.$$keys(), i, param, rawVal, normalized, encoded;
  1712. for (i = 0; i < keys.length; i++) {
  1713. param = this[keys[i]];
  1714. rawVal = paramValues[keys[i]];
  1715. if ((rawVal === undefined || rawVal === null) && param.isOptional)
  1716. break; // There was no parameter value, but the param is optional
  1717. normalized = param.type.$normalize(rawVal);
  1718. if (!param.type.is(normalized))
  1719. return false; // The value was not of the correct Type, and could not be decoded to the correct Type
  1720. encoded = param.type.encode(normalized);
  1721. if (angular.isString(encoded) && !param.type.pattern.exec(encoded))
  1722. return false; // The value was of the correct type, but when encoded, did not match the Type's regexp
  1723. }
  1724. return true;
  1725. },
  1726. $$parent: undefined
  1727. };
  1728. this.ParamSet = ParamSet;
  1729. }
  1730. // Register as a provider so it's available to other providers
  1731. angular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);
  1732. angular.module('ui.router.util').run(['$urlMatcherFactory', function ($urlMatcherFactory) {
  1733. }]);
  1734. /**
  1735. * @ngdoc object
  1736. * @name ui.router.router.$urlRouterProvider
  1737. *
  1738. * @requires ui.router.util.$urlMatcherFactoryProvider
  1739. * @requires $locationProvider
  1740. *
  1741. * @description
  1742. * `$urlRouterProvider` has the responsibility of watching `$location`.
  1743. * When `$location` changes it runs through a list of rules one by one until a
  1744. * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
  1745. * a url in a state configuration. All urls are compiled into a UrlMatcher object.
  1746. *
  1747. * There are several methods on `$urlRouterProvider` that make it useful to use directly
  1748. * in your module config.
  1749. */
  1750. $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
  1751. function $UrlRouterProvider($locationProvider, $urlMatcherFactory) {
  1752. var rules = [], otherwise = null, interceptDeferred = false, listener;
  1753. // Returns a string that is a prefix of all strings matching the RegExp
  1754. function regExpPrefix(re) {
  1755. var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
  1756. return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
  1757. }
  1758. // Interpolates matched values into a String.replace()-style pattern
  1759. function interpolate(pattern, match) {
  1760. return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
  1761. return match[what === '$' ? 0 : Number(what)];
  1762. });
  1763. }
  1764. /**
  1765. * @ngdoc function
  1766. * @name ui.router.router.$urlRouterProvider#rule
  1767. * @methodOf ui.router.router.$urlRouterProvider
  1768. *
  1769. * @description
  1770. * Defines rules that are used by `$urlRouterProvider` to find matches for
  1771. * specific URLs.
  1772. *
  1773. * @example
  1774. * <pre>
  1775. * var app = angular.module('app', ['ui.router.router']);
  1776. *
  1777. * app.config(function ($urlRouterProvider) {
  1778. * // Here's an example of how you might allow case insensitive urls
  1779. * $urlRouterProvider.rule(function ($injector, $location) {
  1780. * var path = $location.path(),
  1781. * normalized = path.toLowerCase();
  1782. *
  1783. * if (path !== normalized) {
  1784. * return normalized;
  1785. * }
  1786. * });
  1787. * });
  1788. * </pre>
  1789. *
  1790. * @param {function} rule Handler function that takes `$injector` and `$location`
  1791. * services as arguments. You can use them to return a valid path as a string.
  1792. *
  1793. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  1794. */
  1795. this.rule = function (rule) {
  1796. if (!isFunction(rule)) throw new Error("'rule' must be a function");
  1797. rules.push(rule);
  1798. return this;
  1799. };
  1800. /**
  1801. * @ngdoc object
  1802. * @name ui.router.router.$urlRouterProvider#otherwise
  1803. * @methodOf ui.router.router.$urlRouterProvider
  1804. *
  1805. * @description
  1806. * Defines a path that is used when an invalid route is requested.
  1807. *
  1808. * @example
  1809. * <pre>
  1810. * var app = angular.module('app', ['ui.router.router']);
  1811. *
  1812. * app.config(function ($urlRouterProvider) {
  1813. * // if the path doesn't match any of the urls you configured
  1814. * // otherwise will take care of routing the user to the
  1815. * // specified url
  1816. * $urlRouterProvider.otherwise('/index');
  1817. *
  1818. * // Example of using function rule as param
  1819. * $urlRouterProvider.otherwise(function ($injector, $location) {
  1820. * return '/a/valid/url';
  1821. * });
  1822. * });
  1823. * </pre>
  1824. *
  1825. * @param {string|function} rule The url path you want to redirect to or a function
  1826. * rule that returns the url path. The function version is passed two params:
  1827. * `$injector` and `$location` services, and must return a url string.
  1828. *
  1829. * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
  1830. */
  1831. this.otherwise = function (rule) {
  1832. if (isString(rule)) {
  1833. var redirect = rule;
  1834. rule = function () {
  1835. return redirect;
  1836. };
  1837. } else if (!isFunction(rule)) throw new Error("'rule' must be a function");
  1838. otherwise = rule;
  1839. return this;
  1840. };
  1841. function handleIfMatch($injector, handler, match) {
  1842. if (!match) return false;
  1843. var result = $injector.invoke(handler, handler, {$match: match});
  1844. return isDefined(result) ? result : true;
  1845. }
  1846. /**
  1847. * @ngdoc function
  1848. * @name ui.router.router.$urlRouterProvider#when
  1849. * @methodOf ui.router.router.$urlRouterProvider
  1850. *
  1851. * @description
  1852. * Registers a handler for a given url matching.
  1853. *
  1854. * If the handler is a string, it is
  1855. * treated as a redirect, and is interpolated according to the syntax of match
  1856. * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
  1857. *
  1858. * If the handler is a function, it is injectable. It gets invoked if `$location`
  1859. * matches. You have the option of inject the match object as `$match`.
  1860. *
  1861. * The handler can return
  1862. *
  1863. * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
  1864. * will continue trying to find another one that matches.
  1865. * - **string** which is treated as a redirect and passed to `$location.url()`
  1866. * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
  1867. *
  1868. * @example
  1869. * <pre>
  1870. * var app = angular.module('app', ['ui.router.router']);
  1871. *
  1872. * app.config(function ($urlRouterProvider) {
  1873. * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
  1874. * if ($state.$current.navigable !== state ||
  1875. * !equalForKeys($match, $stateParams) {
  1876. * $state.transitionTo(state, $match, false);
  1877. * }
  1878. * });
  1879. * });
  1880. * </pre>
  1881. *
  1882. * @param {string|object} what The incoming path that you want to redirect.
  1883. * @param {string|function} handler The path you want to redirect your user to.
  1884. */
  1885. this.when = function (what, handler) {
  1886. var redirect, handlerIsString = isString(handler);
  1887. if (isString(what)) what = $urlMatcherFactory.compile(what);
  1888. if (!handlerIsString && !isFunction(handler) && !isArray(handler))
  1889. throw new Error("invalid 'handler' in when()");
  1890. var strategies = {
  1891. matcher: function (what, handler) {
  1892. if (handlerIsString) {
  1893. redirect = $urlMatcherFactory.compile(handler);
  1894. handler = ['$match', function ($match) {
  1895. return redirect.format($match);
  1896. }];
  1897. }
  1898. return extend(function ($injector, $location) {
  1899. return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
  1900. }, {
  1901. prefix: isString(what.prefix) ? what.prefix : ''
  1902. });
  1903. },
  1904. regex: function (what, handler) {
  1905. if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
  1906. if (handlerIsString) {
  1907. redirect = handler;
  1908. handler = ['$match', function ($match) {
  1909. return interpolate(redirect, $match);
  1910. }];
  1911. }
  1912. return extend(function ($injector, $location) {
  1913. return handleIfMatch($injector, handler, what.exec($location.path()));
  1914. }, {
  1915. prefix: regExpPrefix(what)
  1916. });
  1917. }
  1918. };
  1919. var check = {matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp};
  1920. for (var n in check) {
  1921. if (check[n]) return this.rule(strategies[n](what, handler));
  1922. }
  1923. throw new Error("invalid 'what' in when()");
  1924. };
  1925. /**
  1926. * @ngdoc function
  1927. * @name ui.router.router.$urlRouterProvider#deferIntercept
  1928. * @methodOf ui.router.router.$urlRouterProvider
  1929. *
  1930. * @description
  1931. * Disables (or enables) deferring location change interception.
  1932. *
  1933. * If you wish to customize the behavior of syncing the URL (for example, if you wish to
  1934. * defer a transition but maintain the current URL), call this method at configuration time.
  1935. * Then, at run time, call `$urlRouter.listen()` after you have configured your own
  1936. * `$locationChangeSuccess` event handler.
  1937. *
  1938. * @example
  1939. * <pre>
  1940. * var app = angular.module('app', ['ui.router.router']);
  1941. *
  1942. * app.config(function ($urlRouterProvider) {
  1943. *
  1944. * // Prevent $urlRouter from automatically intercepting URL changes;
  1945. * // this allows you to configure custom behavior in between
  1946. * // location changes and route synchronization:
  1947. * $urlRouterProvider.deferIntercept();
  1948. *
  1949. * }).run(function ($rootScope, $urlRouter, UserService) {
  1950. *
  1951. * $rootScope.$on('$locationChangeSuccess', function(e) {
  1952. * // UserService is an example service for managing user state
  1953. * if (UserService.isLoggedIn()) return;
  1954. *
  1955. * // Prevent $urlRouter's default handler from firing
  1956. * e.preventDefault();
  1957. *
  1958. * UserService.handleLogin().then(function() {
  1959. * // Once the user has logged in, sync the current URL
  1960. * // to the router:
  1961. * $urlRouter.sync();
  1962. * });
  1963. * });
  1964. *
  1965. * // Configures $urlRouter's listener *after* your custom listener
  1966. * $urlRouter.listen();
  1967. * });
  1968. * </pre>
  1969. *
  1970. * @param {boolean} defer Indicates whether to defer location change interception. Passing
  1971. no parameter is equivalent to `true`.
  1972. */
  1973. this.deferIntercept = function (defer) {
  1974. if (defer === undefined) defer = true;
  1975. interceptDeferred = defer;
  1976. };
  1977. /**
  1978. * @ngdoc object
  1979. * @name ui.router.router.$urlRouter
  1980. *
  1981. * @requires $location
  1982. * @requires $rootScope
  1983. * @requires $injector
  1984. * @requires $browser
  1985. *
  1986. * @description
  1987. *
  1988. */
  1989. this.$get = $get;
  1990. $get.$inject = ['$location', '$rootScope', '$injector', '$browser', '$sniffer'];
  1991. function $get($location, $rootScope, $injector, $browser, $sniffer) {
  1992. var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
  1993. function appendBasePath(url, isHtml5, absolute) {
  1994. if (baseHref === '/') return url;
  1995. if (isHtml5) return baseHref.slice(0, -1) + url;
  1996. if (absolute) return baseHref.slice(1) + url;
  1997. return url;
  1998. }
  1999. // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
  2000. function update(evt) {
  2001. if (evt && evt.defaultPrevented) return;
  2002. var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
  2003. lastPushedUrl = undefined;
  2004. // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573
  2005. //if (ignoreUpdate) return true;
  2006. function check(rule) {
  2007. var handled = rule($injector, $location);
  2008. if (!handled) return false;
  2009. if (isString(handled)) $location.replace().url(handled);
  2010. return true;
  2011. }
  2012. var n = rules.length, i;
  2013. for (i = 0; i < n; i++) {
  2014. if (check(rules[i])) return;
  2015. }
  2016. // always check otherwise last to allow dynamic updates to the set of rules
  2017. if (otherwise) check(otherwise);
  2018. }
  2019. function listen() {
  2020. listener = listener || $rootScope.$on('$locationChangeSuccess', update);
  2021. return listener;
  2022. }
  2023. if (!interceptDeferred) listen();
  2024. return {
  2025. /**
  2026. * @ngdoc function
  2027. * @name ui.router.router.$urlRouter#sync
  2028. * @methodOf ui.router.router.$urlRouter
  2029. *
  2030. * @description
  2031. * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
  2032. * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
  2033. * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
  2034. * with the transition by calling `$urlRouter.sync()`.
  2035. *
  2036. * @example
  2037. * <pre>
  2038. * angular.module('app', ['ui.router'])
  2039. * .run(function($rootScope, $urlRouter) {
  2040. * $rootScope.$on('$locationChangeSuccess', function(evt) {
  2041. * // Halt state change from even starting
  2042. * evt.preventDefault();
  2043. * // Perform custom logic
  2044. * var meetsRequirement = ...
  2045. * // Continue with the update and state transition if logic allows
  2046. * if (meetsRequirement) $urlRouter.sync();
  2047. * });
  2048. * });
  2049. * </pre>
  2050. */
  2051. sync: function () {
  2052. update();
  2053. },
  2054. listen: function () {
  2055. return listen();
  2056. },
  2057. update: function (read) {
  2058. if (read) {
  2059. location = $location.url();
  2060. return;
  2061. }
  2062. if ($location.url() === location) return;
  2063. $location.url(location);
  2064. $location.replace();
  2065. },
  2066. push: function (urlMatcher, params, options) {
  2067. var url = urlMatcher.format(params || {});
  2068. // Handle the special hash param, if needed
  2069. if (url !== null && params && params['#']) {
  2070. url += '#' + params['#'];
  2071. }
  2072. $location.url(url);
  2073. lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
  2074. if (options && options.replace) $location.replace();
  2075. },
  2076. /**
  2077. * @ngdoc function
  2078. * @name ui.router.router.$urlRouter#href
  2079. * @methodOf ui.router.router.$urlRouter
  2080. *
  2081. * @description
  2082. * A URL generation method that returns the compiled URL for a given
  2083. * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
  2084. *
  2085. * @example
  2086. * <pre>
  2087. * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
  2088. * person: "bob"
  2089. * });
  2090. * // $bob == "/about/bob";
  2091. * </pre>
  2092. *
  2093. * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
  2094. * @param {object=} params An object of parameter values to fill the matcher's required parameters.
  2095. * @param {object=} options Options object. The options are:
  2096. *
  2097. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  2098. *
  2099. * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
  2100. */
  2101. href: function (urlMatcher, params, options) {
  2102. if (!urlMatcher.validates(params)) return null;
  2103. var isHtml5 = $locationProvider.html5Mode();
  2104. if (angular.isObject(isHtml5)) {
  2105. isHtml5 = isHtml5.enabled;
  2106. }
  2107. isHtml5 = isHtml5 && $sniffer.history;
  2108. var url = urlMatcher.format(params);
  2109. options = options || {};
  2110. if (!isHtml5 && url !== null) {
  2111. url = "#" + $locationProvider.hashPrefix() + url;
  2112. }
  2113. // Handle special hash param, if needed
  2114. if (url !== null && params && params['#']) {
  2115. url += '#' + params['#'];
  2116. }
  2117. url = appendBasePath(url, isHtml5, options.absolute);
  2118. if (!options.absolute || !url) {
  2119. return url;
  2120. }
  2121. var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
  2122. port = (port === 80 || port === 443 ? '' : ':' + port);
  2123. return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
  2124. }
  2125. };
  2126. }
  2127. }
  2128. angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
  2129. /**
  2130. * @ngdoc object
  2131. * @name ui.router.state.$stateProvider
  2132. *
  2133. * @requires ui.router.router.$urlRouterProvider
  2134. * @requires ui.router.util.$urlMatcherFactoryProvider
  2135. *
  2136. * @description
  2137. * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
  2138. * on state.
  2139. *
  2140. * A state corresponds to a "place" in the application in terms of the overall UI and
  2141. * navigation. A state describes (via the controller / template / view properties) what
  2142. * the UI looks like and does at that place.
  2143. *
  2144. * States often have things in common, and the primary way of factoring out these
  2145. * commonalities in this model is via the state hierarchy, i.e. parent/child states aka
  2146. * nested states.
  2147. *
  2148. * The `$stateProvider` provides interfaces to declare these states for your app.
  2149. */
  2150. $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];
  2151. function $StateProvider($urlRouterProvider, $urlMatcherFactory) {
  2152. var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
  2153. // Builds state properties from definition passed to registerState()
  2154. var stateBuilder = {
  2155. // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
  2156. // state.children = [];
  2157. // if (parent) parent.children.push(state);
  2158. parent: function (state) {
  2159. if (isDefined(state.parent) && state.parent) return findState(state.parent);
  2160. // regex matches any valid composite state name
  2161. // would match "contact.list" but not "contacts"
  2162. var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
  2163. return compositeName ? findState(compositeName[1]) : root;
  2164. },
  2165. // inherit 'data' from parent and override by own values (if any)
  2166. data: function (state) {
  2167. if (state.parent && state.parent.data) {
  2168. state.data = state.self.data = inherit(state.parent.data, state.data);
  2169. }
  2170. return state.data;
  2171. },
  2172. // Build a URLMatcher if necessary, either via a relative or absolute URL
  2173. url: function (state) {
  2174. var url = state.url, config = {params: state.params || {}};
  2175. if (isString(url)) {
  2176. if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
  2177. return (state.parent.navigable || root).url.concat(url, config);
  2178. }
  2179. if (!url || $urlMatcherFactory.isMatcher(url)) return url;
  2180. throw new Error("Invalid url '" + url + "' in state '" + state + "'");
  2181. },
  2182. // Keep track of the closest ancestor state that has a URL (i.e. is navigable)
  2183. navigable: function (state) {
  2184. return state.url ? state : (state.parent ? state.parent.navigable : null);
  2185. },
  2186. // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params
  2187. ownParams: function (state) {
  2188. var params = state.url && state.url.params || new $$UMFP.ParamSet();
  2189. forEach(state.params || {}, function (config, id) {
  2190. if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, "config");
  2191. });
  2192. return params;
  2193. },
  2194. // Derive parameters for this state and ensure they're a super-set of parent's parameters
  2195. params: function (state) {
  2196. var ownParams = pick(state.ownParams, state.ownParams.$$keys());
  2197. return state.parent && state.parent.params ? extend(state.parent.params.$$new(), ownParams) : new $$UMFP.ParamSet();
  2198. },
  2199. // If there is no explicit multi-view configuration, make one up so we don't have
  2200. // to handle both cases in the view directive later. Note that having an explicit
  2201. // 'views' property will mean the default unnamed view properties are ignored. This
  2202. // is also a good time to resolve view names to absolute names, so everything is a
  2203. // straight lookup at link time.
  2204. views: function (state) {
  2205. var views = {};
  2206. forEach(isDefined(state.views) ? state.views : {'': state}, function (view, name) {
  2207. if (name.indexOf('@') < 0) name += '@' + state.parent.name;
  2208. view.resolveAs = view.resolveAs || state.resolveAs || '$resolve';
  2209. views[name] = view;
  2210. });
  2211. return views;
  2212. },
  2213. // Keep a full path from the root down to this state as this is needed for state activation.
  2214. path: function (state) {
  2215. return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
  2216. },
  2217. // Speed up $state.contains() as it's used a lot
  2218. includes: function (state) {
  2219. var includes = state.parent ? extend({}, state.parent.includes) : {};
  2220. includes[state.name] = true;
  2221. return includes;
  2222. },
  2223. $delegates: {}
  2224. };
  2225. function isRelative(stateName) {
  2226. return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
  2227. }
  2228. function findState(stateOrName, base) {
  2229. if (!stateOrName) return undefined;
  2230. var isStr = isString(stateOrName),
  2231. name = isStr ? stateOrName : stateOrName.name,
  2232. path = isRelative(name);
  2233. if (path) {
  2234. if (!base) throw new Error("No reference point given for path '" + name + "'");
  2235. base = findState(base);
  2236. var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
  2237. for (; i < pathLength; i++) {
  2238. if (rel[i] === "" && i === 0) {
  2239. current = base;
  2240. continue;
  2241. }
  2242. if (rel[i] === "^") {
  2243. if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
  2244. current = current.parent;
  2245. continue;
  2246. }
  2247. break;
  2248. }
  2249. rel = rel.slice(i).join(".");
  2250. name = current.name + (current.name && rel ? "." : "") + rel;
  2251. }
  2252. var state = states[name];
  2253. if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
  2254. return state;
  2255. }
  2256. return undefined;
  2257. }
  2258. function queueState(parentName, state) {
  2259. if (!queue[parentName]) {
  2260. queue[parentName] = [];
  2261. }
  2262. queue[parentName].push(state);
  2263. }
  2264. function flushQueuedChildren(parentName) {
  2265. var queued = queue[parentName] || [];
  2266. while (queued.length) {
  2267. registerState(queued.shift());
  2268. }
  2269. }
  2270. function registerState(state) {
  2271. // Wrap a new object around the state so we can store our private details easily.
  2272. state = inherit(state, {
  2273. self: state,
  2274. resolve: state.resolve || {},
  2275. toString: function () {
  2276. return this.name;
  2277. }
  2278. });
  2279. var name = state.name;
  2280. if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
  2281. if (states.hasOwnProperty(name)) throw new Error("State '" + name + "' is already defined");
  2282. // Get parent name
  2283. var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
  2284. : (isString(state.parent)) ? state.parent
  2285. : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name
  2286. : '';
  2287. // If parent is not registered yet, add state to queue and register later
  2288. if (parentName && !states[parentName]) {
  2289. return queueState(parentName, state.self);
  2290. }
  2291. for (var key in stateBuilder) {
  2292. if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
  2293. }
  2294. states[name] = state;
  2295. // Register the state in the global state list and with $urlRouter if necessary.
  2296. if (!state[abstractKey] && state.url) {
  2297. $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
  2298. if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
  2299. $state.transitionTo(state, $match, {inherit: true, location: false});
  2300. }
  2301. }]);
  2302. }
  2303. // Register any queued children
  2304. flushQueuedChildren(name);
  2305. return state;
  2306. }
  2307. // Checks text to see if it looks like a glob.
  2308. function isGlob(text) {
  2309. return text.indexOf('*') > -1;
  2310. }
  2311. // Returns true if glob matches current $state name.
  2312. function doesStateMatchGlob(glob) {
  2313. var globSegments = glob.split('.'),
  2314. segments = $state.$current.name.split('.');
  2315. //match single stars
  2316. for (var i = 0, l = globSegments.length; i < l; i++) {
  2317. if (globSegments[i] === '*') {
  2318. segments[i] = '*';
  2319. }
  2320. }
  2321. //match greedy starts
  2322. if (globSegments[0] === '**') {
  2323. segments = segments.slice(indexOf(segments, globSegments[1]));
  2324. segments.unshift('**');
  2325. }
  2326. //match greedy ends
  2327. if (globSegments[globSegments.length - 1] === '**') {
  2328. segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
  2329. segments.push('**');
  2330. }
  2331. if (globSegments.length != segments.length) {
  2332. return false;
  2333. }
  2334. return segments.join('') === globSegments.join('');
  2335. }
  2336. // Implicit root state that is always active
  2337. root = registerState({
  2338. name: '',
  2339. url: '^',
  2340. views: null,
  2341. 'abstract': true
  2342. });
  2343. root.navigable = null;
  2344. /**
  2345. * @ngdoc function
  2346. * @name ui.router.state.$stateProvider#decorator
  2347. * @methodOf ui.router.state.$stateProvider
  2348. *
  2349. * @description
  2350. * Allows you to extend (carefully) or override (at your own peril) the
  2351. * `stateBuilder` object used internally by `$stateProvider`. This can be used
  2352. * to add custom functionality to ui-router, for example inferring templateUrl
  2353. * based on the state name.
  2354. *
  2355. * When passing only a name, it returns the current (original or decorated) builder
  2356. * function that matches `name`.
  2357. *
  2358. * The builder functions that can be decorated are listed below. Though not all
  2359. * necessarily have a good use case for decoration, that is up to you to decide.
  2360. *
  2361. * In addition, users can attach custom decorators, which will generate new
  2362. * properties within the state's internal definition. There is currently no clear
  2363. * use-case for this beyond accessing internal states (i.e. $state.$current),
  2364. * however, expect this to become increasingly relevant as we introduce additional
  2365. * meta-programming features.
  2366. *
  2367. * **Warning**: Decorators should not be interdependent because the order of
  2368. * execution of the builder functions in non-deterministic. Builder functions
  2369. * should only be dependent on the state definition object and super function.
  2370. *
  2371. *
  2372. * Existing builder functions and current return values:
  2373. *
  2374. * - **parent** `{object}` - returns the parent state object.
  2375. * - **data** `{object}` - returns state data, including any inherited data that is not
  2376. * overridden by own values (if any).
  2377. * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
  2378. * or `null`.
  2379. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
  2380. * navigable).
  2381. * - **params** `{object}` - returns an array of state params that are ensured to
  2382. * be a super-set of parent's params.
  2383. * - **views** `{object}` - returns a views object where each key is an absolute view
  2384. * name (i.e. "viewName@stateName") and each value is the config object
  2385. * (template, controller) for the view. Even when you don't use the views object
  2386. * explicitly on a state config, one is still created for you internally.
  2387. * So by decorating this builder function you have access to decorating template
  2388. * and controller properties.
  2389. * - **ownParams** `{object}` - returns an array of params that belong to the state,
  2390. * not including any params defined by ancestor states.
  2391. * - **path** `{string}` - returns the full path from the root down to this state.
  2392. * Needed for state activation.
  2393. * - **includes** `{object}` - returns an object that includes every state that
  2394. * would pass a `$state.includes()` test.
  2395. *
  2396. * @example
  2397. * <pre>
  2398. * // Override the internal 'views' builder with a function that takes the state
  2399. * // definition, and a reference to the internal function being overridden:
  2400. * $stateProvider.decorator('views', function (state, parent) {
  2401. * var result = {},
  2402. * views = parent(state);
  2403. *
  2404. * angular.forEach(views, function (config, name) {
  2405. * var autoName = (state.name + '.' + name).replace('.', '/');
  2406. * config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
  2407. * result[name] = config;
  2408. * });
  2409. * return result;
  2410. * });
  2411. *
  2412. * $stateProvider.state('home', {
  2413. * views: {
  2414. * 'contact.list': { controller: 'ListController' },
  2415. * 'contact.item': { controller: 'ItemController' }
  2416. * }
  2417. * });
  2418. *
  2419. * // ...
  2420. *
  2421. * $state.go('home');
  2422. * // Auto-populates list and item views with /partials/home/contact/list.html,
  2423. * // and /partials/home/contact/item.html, respectively.
  2424. * </pre>
  2425. *
  2426. * @param {string} name The name of the builder function to decorate.
  2427. * @param {object} func A function that is responsible for decorating the original
  2428. * builder function. The function receives two parameters:
  2429. *
  2430. * - `{object}` - state - The state config object.
  2431. * - `{object}` - super - The original builder function.
  2432. *
  2433. * @return {object} $stateProvider - $stateProvider instance
  2434. */
  2435. this.decorator = decorator;
  2436. function decorator(name, func) {
  2437. /*jshint validthis: true */
  2438. if (isString(name) && !isDefined(func)) {
  2439. return stateBuilder[name];
  2440. }
  2441. if (!isFunction(func) || !isString(name)) {
  2442. return this;
  2443. }
  2444. if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
  2445. stateBuilder.$delegates[name] = stateBuilder[name];
  2446. }
  2447. stateBuilder[name] = func;
  2448. return this;
  2449. }
  2450. /**
  2451. * @ngdoc function
  2452. * @name ui.router.state.$stateProvider#state
  2453. * @methodOf ui.router.state.$stateProvider
  2454. *
  2455. * @description
  2456. * Registers a state configuration under a given state name. The stateConfig object
  2457. * has the following acceptable properties.
  2458. *
  2459. * @param {string} name A unique state name, e.g. "home", "about", "contacts".
  2460. * To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
  2461. * @param {object} stateConfig State configuration object.
  2462. * @param {string|function=} stateConfig.template
  2463. * <a id='template'></a>
  2464. * html template as a string or a function that returns
  2465. * an html template as a string which should be used by the uiView directives. This property
  2466. * takes precedence over templateUrl.
  2467. *
  2468. * If `template` is a function, it will be called with the following parameters:
  2469. *
  2470. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  2471. * applying the current state
  2472. *
  2473. * <pre>template:
  2474. * "<h1>inline template definition</h1>" +
  2475. * "<div ui-view></div>"</pre>
  2476. * <pre>template: function(params) {
  2477. * return "<h1>generated template</h1>"; }</pre>
  2478. * </div>
  2479. *
  2480. * @param {string|function=} stateConfig.templateUrl
  2481. * <a id='templateUrl'></a>
  2482. *
  2483. * path or function that returns a path to an html
  2484. * template that should be used by uiView.
  2485. *
  2486. * If `templateUrl` is a function, it will be called with the following parameters:
  2487. *
  2488. * - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by
  2489. * applying the current state
  2490. *
  2491. * <pre>templateUrl: "home.html"</pre>
  2492. * <pre>templateUrl: function(params) {
  2493. * return myTemplates[params.pageId]; }</pre>
  2494. *
  2495. * @param {function=} stateConfig.templateProvider
  2496. * <a id='templateProvider'></a>
  2497. * Provider function that returns HTML content string.
  2498. * <pre> templateProvider:
  2499. * function(MyTemplateService, params) {
  2500. * return MyTemplateService.getTemplate(params.pageId);
  2501. * }</pre>
  2502. *
  2503. * @param {string|function=} stateConfig.controller
  2504. * <a id='controller'></a>
  2505. *
  2506. * Controller fn that should be associated with newly
  2507. * related scope or the name of a registered controller if passed as a string.
  2508. * Optionally, the ControllerAs may be declared here.
  2509. * <pre>controller: "MyRegisteredController"</pre>
  2510. * <pre>controller:
  2511. * "MyRegisteredController as fooCtrl"}</pre>
  2512. * <pre>controller: function($scope, MyService) {
  2513. * $scope.data = MyService.getData(); }</pre>
  2514. *
  2515. * @param {function=} stateConfig.controllerProvider
  2516. * <a id='controllerProvider'></a>
  2517. *
  2518. * Injectable provider function that returns the actual controller or string.
  2519. * <pre>controllerProvider:
  2520. * function(MyResolveData) {
  2521. * if (MyResolveData.foo)
  2522. * return "FooCtrl"
  2523. * else if (MyResolveData.bar)
  2524. * return "BarCtrl";
  2525. * else return function($scope) {
  2526. * $scope.baz = "Qux";
  2527. * }
  2528. * }</pre>
  2529. *
  2530. * @param {string=} stateConfig.controllerAs
  2531. * <a id='controllerAs'></a>
  2532. *
  2533. * A controller alias name. If present the controller will be
  2534. * published to scope under the controllerAs name.
  2535. * <pre>controllerAs: "myCtrl"</pre>
  2536. *
  2537. * @param {string|object=} stateConfig.parent
  2538. * <a id='parent'></a>
  2539. * Optionally specifies the parent state of this state.
  2540. *
  2541. * <pre>parent: 'parentState'</pre>
  2542. * <pre>parent: parentState // JS variable</pre>
  2543. *
  2544. * @param {object=} stateConfig.resolve
  2545. * <a id='resolve'></a>
  2546. *
  2547. * An optional map&lt;string, function&gt; of dependencies which
  2548. * should be injected into the controller. If any of these dependencies are promises,
  2549. * the router will wait for them all to be resolved before the controller is instantiated.
  2550. * If all the promises are resolved successfully, the $stateChangeSuccess event is fired
  2551. * and the values of the resolved promises are injected into any controllers that reference them.
  2552. * If any of the promises are rejected the $stateChangeError event is fired.
  2553. *
  2554. * The map object is:
  2555. *
  2556. * - key - {string}: name of dependency to be injected into controller
  2557. * - factory - {string|function}: If string then it is alias for service. Otherwise if function,
  2558. * it is injected and return value it treated as dependency. If result is a promise, it is
  2559. * resolved before its value is injected into controller.
  2560. *
  2561. * <pre>resolve: {
  2562. * myResolve1:
  2563. * function($http, $stateParams) {
  2564. * return $http.get("/api/foos/"+stateParams.fooID);
  2565. * }
  2566. * }</pre>
  2567. *
  2568. * @param {string=} stateConfig.url
  2569. * <a id='url'></a>
  2570. *
  2571. * A url fragment with optional parameters. When a state is navigated or
  2572. * transitioned to, the `$stateParams` service will be populated with any
  2573. * parameters that were passed.
  2574. *
  2575. * (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for
  2576. * more details on acceptable patterns )
  2577. *
  2578. * examples:
  2579. * <pre>url: "/home"
  2580. * url: "/users/:userid"
  2581. * url: "/books/{bookid:[a-zA-Z_-]}"
  2582. * url: "/books/{categoryid:int}"
  2583. * url: "/books/{publishername:string}/{categoryid:int}"
  2584. * url: "/messages?before&after"
  2585. * url: "/messages?{before:date}&{after:date}"
  2586. * url: "/messages/:mailboxid?{before:date}&{after:date}"
  2587. * </pre>
  2588. *
  2589. * @param {object=} stateConfig.views
  2590. * <a id='views'></a>
  2591. * an optional map&lt;string, object&gt; which defined multiple views, or targets views
  2592. * manually/explicitly.
  2593. *
  2594. * Examples:
  2595. *
  2596. * Targets three named `ui-view`s in the parent state's template
  2597. * <pre>views: {
  2598. * header: {
  2599. * controller: "headerCtrl",
  2600. * templateUrl: "header.html"
  2601. * }, body: {
  2602. * controller: "bodyCtrl",
  2603. * templateUrl: "body.html"
  2604. * }, footer: {
  2605. * controller: "footCtrl",
  2606. * templateUrl: "footer.html"
  2607. * }
  2608. * }</pre>
  2609. *
  2610. * Targets named `ui-view="header"` from grandparent state 'top''s template, and named `ui-view="body" from parent state's template.
  2611. * <pre>views: {
  2612. * 'header@top': {
  2613. * controller: "msgHeaderCtrl",
  2614. * templateUrl: "msgHeader.html"
  2615. * }, 'body': {
  2616. * controller: "messagesCtrl",
  2617. * templateUrl: "messages.html"
  2618. * }
  2619. * }</pre>
  2620. *
  2621. * @param {boolean=} [stateConfig.abstract=false]
  2622. * <a id='abstract'></a>
  2623. * An abstract state will never be directly activated,
  2624. * but can provide inherited properties to its common children states.
  2625. * <pre>abstract: true</pre>
  2626. *
  2627. * @param {function=} stateConfig.onEnter
  2628. * <a id='onEnter'></a>
  2629. *
  2630. * Callback function for when a state is entered. Good way
  2631. * to trigger an action or dispatch an event, such as opening a dialog.
  2632. * If minifying your scripts, make sure to explicitly annotate this function,
  2633. * because it won't be automatically annotated by your build tools.
  2634. *
  2635. * <pre>onEnter: function(MyService, $stateParams) {
  2636. * MyService.foo($stateParams.myParam);
  2637. * }</pre>
  2638. *
  2639. * @param {function=} stateConfig.onExit
  2640. * <a id='onExit'></a>
  2641. *
  2642. * Callback function for when a state is exited. Good way to
  2643. * trigger an action or dispatch an event, such as opening a dialog.
  2644. * If minifying your scripts, make sure to explicitly annotate this function,
  2645. * because it won't be automatically annotated by your build tools.
  2646. *
  2647. * <pre>onExit: function(MyService, $stateParams) {
  2648. * MyService.cleanup($stateParams.myParam);
  2649. * }</pre>
  2650. *
  2651. * @param {boolean=} [stateConfig.reloadOnSearch=true]
  2652. * <a id='reloadOnSearch'></a>
  2653. *
  2654. * If `false`, will not retrigger the same state
  2655. * just because a search/query parameter has changed (via $location.search() or $location.hash()).
  2656. * Useful for when you'd like to modify $location.search() without triggering a reload.
  2657. * <pre>reloadOnSearch: false</pre>
  2658. *
  2659. * @param {object=} stateConfig.data
  2660. * <a id='data'></a>
  2661. *
  2662. * Arbitrary data object, useful for custom configuration. The parent state's `data` is
  2663. * prototypally inherited. In other words, adding a data property to a state adds it to
  2664. * the entire subtree via prototypal inheritance.
  2665. *
  2666. * <pre>data: {
  2667. * requiredRole: 'foo'
  2668. * } </pre>
  2669. *
  2670. * @param {object=} stateConfig.params
  2671. * <a id='params'></a>
  2672. *
  2673. * A map which optionally configures parameters declared in the `url`, or
  2674. * defines additional non-url parameters. For each parameter being
  2675. * configured, add a configuration object keyed to the name of the parameter.
  2676. *
  2677. * Each parameter configuration object may contain the following properties:
  2678. *
  2679. * - ** value ** - {object|function=}: specifies the default value for this
  2680. * parameter. This implicitly sets this parameter as optional.
  2681. *
  2682. * When UI-Router routes to a state and no value is
  2683. * specified for this parameter in the URL or transition, the
  2684. * default value will be used instead. If `value` is a function,
  2685. * it will be injected and invoked, and the return value used.
  2686. *
  2687. * *Note*: `undefined` is treated as "no default value" while `null`
  2688. * is treated as "the default value is `null`".
  2689. *
  2690. * *Shorthand*: If you only need to configure the default value of the
  2691. * parameter, you may use a shorthand syntax. In the **`params`**
  2692. * map, instead mapping the param name to a full parameter configuration
  2693. * object, simply set map it to the default parameter value, e.g.:
  2694. *
  2695. * <pre>// define a parameter's default value
  2696. * params: {
  2697. * param1: { value: "defaultValue" }
  2698. * }
  2699. * // shorthand default values
  2700. * params: {
  2701. * param1: "defaultValue",
  2702. * param2: "param2Default"
  2703. * }</pre>
  2704. *
  2705. * - ** array ** - {boolean=}: *(default: false)* If true, the param value will be
  2706. * treated as an array of values. If you specified a Type, the value will be
  2707. * treated as an array of the specified Type. Note: query parameter values
  2708. * default to a special `"auto"` mode.
  2709. *
  2710. * For query parameters in `"auto"` mode, if multiple values for a single parameter
  2711. * are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values
  2712. * are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`). However, if
  2713. * only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single
  2714. * value (e.g.: `{ foo: '1' }`).
  2715. *
  2716. * <pre>params: {
  2717. * param1: { array: true }
  2718. * }</pre>
  2719. *
  2720. * - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when
  2721. * the current parameter value is the same as the default value. If `squash` is not set, it uses the
  2722. * configured default squash policy.
  2723. * (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})
  2724. *
  2725. * There are three squash settings:
  2726. *
  2727. * - false: The parameter's default value is not squashed. It is encoded and included in the URL
  2728. * - true: The parameter's default value is omitted from the URL. If the parameter is preceeded and followed
  2729. * by slashes in the state's `url` declaration, then one of those slashes are omitted.
  2730. * This can allow for cleaner looking URLs.
  2731. * - `"<arbitrary string>"`: The parameter's default value is replaced with an arbitrary placeholder of your choice.
  2732. *
  2733. * <pre>params: {
  2734. * param1: {
  2735. * value: "defaultId",
  2736. * squash: true
  2737. * } }
  2738. * // squash "defaultValue" to "~"
  2739. * params: {
  2740. * param1: {
  2741. * value: "defaultValue",
  2742. * squash: "~"
  2743. * } }
  2744. * </pre>
  2745. *
  2746. *
  2747. * @example
  2748. * <pre>
  2749. * // Some state name examples
  2750. *
  2751. * // stateName can be a single top-level name (must be unique).
  2752. * $stateProvider.state("home", {});
  2753. *
  2754. * // Or it can be a nested state name. This state is a child of the
  2755. * // above "home" state.
  2756. * $stateProvider.state("home.newest", {});
  2757. *
  2758. * // Nest states as deeply as needed.
  2759. * $stateProvider.state("home.newest.abc.xyz.inception", {});
  2760. *
  2761. * // state() returns $stateProvider, so you can chain state declarations.
  2762. * $stateProvider
  2763. * .state("home", {})
  2764. * .state("about", {})
  2765. * .state("contacts", {});
  2766. * </pre>
  2767. *
  2768. */
  2769. this.state = state;
  2770. function state(name, definition) {
  2771. /*jshint validthis: true */
  2772. if (isObject(name)) definition = name;
  2773. else definition.name = name;
  2774. registerState(definition);
  2775. return this;
  2776. }
  2777. /**
  2778. 添加states方法
  2779. */
  2780. this.getStates=function () {
  2781. return states;
  2782. };
  2783. /**
  2784. * @ngdoc object
  2785. * @name ui.router.state.$state
  2786. *
  2787. * @requires $rootScope
  2788. * @requires $q
  2789. * @requires ui.router.state.$view
  2790. * @requires $injector
  2791. * @requires ui.router.util.$resolve
  2792. * @requires ui.router.state.$stateParams
  2793. * @requires ui.router.router.$urlRouter
  2794. *
  2795. * @property {object} params A param object, e.g. {sectionId: section.id)}, that
  2796. * you'd like to test against the current active state.
  2797. * @property {object} current A reference to the state's config object. However
  2798. * you passed it in. Useful for accessing custom data.
  2799. * @property {object} transition Currently pending transition. A promise that'll
  2800. * resolve or reject.
  2801. *
  2802. * @description
  2803. * `$state` service is responsible for representing states as well as transitioning
  2804. * between them. It also provides interfaces to ask for current state or even states
  2805. * you're coming from.
  2806. */
  2807. this.$get = $get;
  2808. $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];
  2809. function $get($rootScope, $q, $view, $injector, $resolve, $stateParams, $urlRouter, $location, $urlMatcherFactory) {
  2810. var TransitionSupersededError = new Error('transition superseded');
  2811. var TransitionSuperseded = silenceUncaughtInPromise($q.reject(TransitionSupersededError));
  2812. var TransitionPrevented = silenceUncaughtInPromise($q.reject(new Error('transition prevented')));
  2813. var TransitionAborted = silenceUncaughtInPromise($q.reject(new Error('transition aborted')));
  2814. var TransitionFailed = silenceUncaughtInPromise($q.reject(new Error('transition failed')));
  2815. // Handles the case where a state which is the target of a transition is not found, and the user
  2816. // can optionally retry or defer the transition
  2817. function handleRedirect(redirect, state, params, options) {
  2818. /**
  2819. * @ngdoc event
  2820. * @name ui.router.state.$state#$stateNotFound
  2821. * @eventOf ui.router.state.$state
  2822. * @eventType broadcast on root scope
  2823. * @description
  2824. * Fired when a requested state **cannot be found** using the provided state name during transition.
  2825. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by
  2826. * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
  2827. * you can see its three properties in the example. You can use `event.preventDefault()` to abort the
  2828. * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
  2829. *
  2830. * @param {Object} event Event object.
  2831. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
  2832. * @param {State} fromState Current state object.
  2833. * @param {Object} fromParams Current state params.
  2834. *
  2835. * @example
  2836. *
  2837. * <pre>
  2838. * // somewhere, assume lazy.state has not been defined
  2839. * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
  2840. *
  2841. * // somewhere else
  2842. * $scope.$on('$stateNotFound',
  2843. * function(event, unfoundState, fromState, fromParams){
  2844. * console.log(unfoundState.to); // "lazy.state"
  2845. * console.log(unfoundState.toParams); // {a:1, b:2}
  2846. * console.log(unfoundState.options); // {inherit:false} + default options
  2847. * })
  2848. * </pre>
  2849. */
  2850. var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
  2851. if (evt.defaultPrevented) {
  2852. $urlRouter.update();
  2853. return TransitionAborted;
  2854. }
  2855. if (!evt.retry) {
  2856. return null;
  2857. }
  2858. // Allow the handler to return a promise to defer state lookup retry
  2859. if (options.$retry) {
  2860. $urlRouter.update();
  2861. return TransitionFailed;
  2862. }
  2863. var retryTransition = $state.transition = $q.when(evt.retry);
  2864. retryTransition.then(function () {
  2865. if (retryTransition !== $state.transition) {
  2866. $rootScope.$broadcast('$stateChangeCancel', redirect.to, redirect.toParams, state, params);
  2867. return TransitionSuperseded;
  2868. }
  2869. redirect.options.$retry = true;
  2870. return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
  2871. }, function () {
  2872. return TransitionAborted;
  2873. });
  2874. $urlRouter.update();
  2875. return retryTransition;
  2876. }
  2877. root.locals = {resolve: null, globals: {$stateParams: {}}};
  2878. $state = {
  2879. params: {},
  2880. current: root.self,
  2881. $current: root,
  2882. transition: null
  2883. };
  2884. /**
  2885. * @ngdoc function
  2886. * @name ui.router.state.$state#reload
  2887. * @methodOf ui.router.state.$state
  2888. *
  2889. * @description
  2890. * A method that force reloads the current state. All resolves are re-resolved,
  2891. * controllers reinstantiated, and events re-fired.
  2892. *
  2893. * @example
  2894. * <pre>
  2895. * var app angular.module('app', ['ui.router']);
  2896. *
  2897. * app.controller('ctrl', function ($scope, $state) {
  2898. * $scope.reload = function(){
  2899. * $state.reload();
  2900. * }
  2901. * });
  2902. * </pre>
  2903. *
  2904. * `reload()` is just an alias for:
  2905. * <pre>
  2906. * $state.transitionTo($state.current, $stateParams, {
  2907. * reload: true, inherit: false, notify: true
  2908. * });
  2909. * </pre>
  2910. *
  2911. * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.
  2912. * @example
  2913. * <pre>
  2914. * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item'
  2915. * //and current state is 'contacts.detail.item'
  2916. * var app angular.module('app', ['ui.router']);
  2917. *
  2918. * app.controller('ctrl', function ($scope, $state) {
  2919. * $scope.reload = function(){
  2920. * //will reload 'contact.detail' and 'contact.detail.item' states
  2921. * $state.reload('contact.detail');
  2922. * }
  2923. * });
  2924. * </pre>
  2925. *
  2926. * `reload()` is just an alias for:
  2927. * <pre>
  2928. * $state.transitionTo($state.current, $stateParams, {
  2929. * reload: true, inherit: false, notify: true
  2930. * });
  2931. * </pre>
  2932. * @returns {promise} A promise representing the state of the new transition. See
  2933. * {@link ui.router.state.$state#methods_go $state.go}.
  2934. */
  2935. $state.reload = function reload(state) {
  2936. return $state.transitionTo($state.current, $stateParams, {
  2937. reload: state || true,
  2938. inherit: false,
  2939. notify: true
  2940. });
  2941. };
  2942. /**
  2943. * @ngdoc function
  2944. * @name ui.router.state.$state#go
  2945. * @methodOf ui.router.state.$state
  2946. *
  2947. * @description
  2948. * Convenience method for transitioning to a new state. `$state.go` calls
  2949. * `$state.transitionTo` internally but automatically sets options to
  2950. * `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
  2951. * This allows you to easily use an absolute or relative to path and specify
  2952. * only the parameters you'd like to update (while letting unspecified parameters
  2953. * inherit from the currently active ancestor states).
  2954. *
  2955. * @example
  2956. * <pre>
  2957. * var app = angular.module('app', ['ui.router']);
  2958. *
  2959. * app.controller('ctrl', function ($scope, $state) {
  2960. * $scope.changeState = function () {
  2961. * $state.go('contact.detail');
  2962. * };
  2963. * });
  2964. * </pre>
  2965. * <img src='../ngdoc_assets/StateGoExamples.png'/>
  2966. *
  2967. * @param {string} to Absolute state name or relative state path. Some examples:
  2968. *
  2969. * - `$state.go('contact.detail')` - will go to the `contact.detail` state
  2970. * - `$state.go('^')` - will go to a parent state
  2971. * - `$state.go('^.sibling')` - will go to a sibling state
  2972. * - `$state.go('.child.grandchild')` - will go to grandchild state
  2973. *
  2974. * @param {object=} params A map of the parameters that will be sent to the state,
  2975. * will populate $stateParams. Any parameters that are not specified will be inherited from currently
  2976. * defined parameters. Only parameters specified in the state definition can be overridden, new
  2977. * parameters will be ignored. This allows, for example, going to a sibling state that shares parameters
  2978. * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
  2979. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child
  2980. * will get you all current parameters, etc.
  2981. * @param {object=} options Options object. The options are:
  2982. *
  2983. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  2984. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  2985. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  2986. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  2987. * defines which state to be relative from.
  2988. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  2989. * - **`reload`** (v0.2.5) - {boolean=false|string|object}, If `true` will force transition even if no state or params
  2990. * have changed. It will reload the resolves and views of the current state and parent states.
  2991. * If `reload` is a string (or state object), the state object is fetched (by name, or object reference); and \
  2992. * the transition reloads the resolves and views for that matched state, and all its children states.
  2993. *
  2994. * @returns {promise} A promise representing the state of the new transition.
  2995. *
  2996. * Possible success values:
  2997. *
  2998. * - $state.current
  2999. *
  3000. * <br/>Possible rejection values:
  3001. *
  3002. * - 'transition superseded' - when a newer transition has been started after this one
  3003. * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
  3004. * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
  3005. * when a `$stateNotFound` `event.retry` promise errors.
  3006. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
  3007. * - *resolve error* - when an error has occurred with a `resolve`
  3008. *
  3009. */
  3010. $state.go = function go(to, params, options) {
  3011. return $state.transitionTo(to, params, extend({inherit: true, relative: $state.$current}, options));
  3012. };
  3013. /**
  3014. * @ngdoc function
  3015. * @name ui.router.state.$state#transitionTo
  3016. * @methodOf ui.router.state.$state
  3017. *
  3018. * @description
  3019. * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
  3020. * uses `transitionTo` internally. `$state.go` is recommended in most situations.
  3021. *
  3022. * @example
  3023. * <pre>
  3024. * var app = angular.module('app', ['ui.router']);
  3025. *
  3026. * app.controller('ctrl', function ($scope, $state) {
  3027. * $scope.changeState = function () {
  3028. * $state.transitionTo('contact.detail');
  3029. * };
  3030. * });
  3031. * </pre>
  3032. *
  3033. * @param {string} to State name.
  3034. * @param {object=} toParams A map of the parameters that will be sent to the state,
  3035. * will populate $stateParams.
  3036. * @param {object=} options Options object. The options are:
  3037. *
  3038. * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
  3039. * will not. If string, must be `"replace"`, which will update url and also replace last history record.
  3040. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
  3041. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
  3042. * defines which state to be relative from.
  3043. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
  3044. * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params
  3045. * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
  3046. * use this when you want to force a reload when *everything* is the same, including search params.
  3047. * if String, then will reload the state with the name given in reload, and any children.
  3048. * if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.
  3049. *
  3050. * @returns {promise} A promise representing the state of the new transition. See
  3051. * {@link ui.router.state.$state#methods_go $state.go}.
  3052. */
  3053. $state.transitionTo = function transitionTo(to, toParams, options) {
  3054. toParams = toParams || {};
  3055. options = extend({
  3056. location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
  3057. }, options || {});
  3058. var from = $state.$current, fromParams = $state.params, fromPath = from.path;
  3059. var evt, toState = findState(to, options.relative);
  3060. // Store the hash param for later (since it will be stripped out by various methods)
  3061. var hash = toParams['#'];
  3062. if (!isDefined(toState)) {
  3063. var redirect = {to: to, toParams: toParams, options: options};
  3064. var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
  3065. if (redirectResult) {
  3066. return redirectResult;
  3067. }
  3068. // Always retry once if the $stateNotFound was not prevented
  3069. // (handles either redirect changed or state lazy-definition)
  3070. to = redirect.to;
  3071. toParams = redirect.toParams;
  3072. options = redirect.options;
  3073. toState = findState(to, options.relative);
  3074. if (!isDefined(toState)) {
  3075. if (!options.relative) throw new Error("No such state '" + to + "'");
  3076. throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
  3077. }
  3078. }
  3079. if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
  3080. if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
  3081. if (!toState.params.$$validates(toParams)) return TransitionFailed;
  3082. toParams = toState.params.$$values(toParams);
  3083. to = toState;
  3084. var toPath = to.path;
  3085. // Starting from the root of the path, keep all levels that haven't changed
  3086. var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];
  3087. if (!options.reload) {
  3088. while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {
  3089. locals = toLocals[keep] = state.locals;
  3090. keep++;
  3091. state = toPath[keep];
  3092. }
  3093. } else if (isString(options.reload) || isObject(options.reload)) {
  3094. if (isObject(options.reload) && !options.reload.name) {
  3095. throw new Error('Invalid reload state object');
  3096. }
  3097. var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);
  3098. if (options.reload && !reloadState) {
  3099. throw new Error("No such reload state '" + (isString(options.reload) ? options.reload : options.reload.name) + "'");
  3100. }
  3101. while (state && state === fromPath[keep] && state !== reloadState) {
  3102. locals = toLocals[keep] = state.locals;
  3103. keep++;
  3104. state = toPath[keep];
  3105. }
  3106. }
  3107. // If we're going to the same state and all locals are kept, we've got nothing to do.
  3108. // But clear 'transition', as we still want to cancel any other pending transitions.
  3109. // TODO: We may not want to bump 'transition' if we're called from a location change
  3110. // that we've initiated ourselves, because we might accidentally abort a legitimate
  3111. // transition initiated from code?
  3112. if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {
  3113. if (hash) toParams['#'] = hash;
  3114. $state.params = toParams;
  3115. copy($state.params, $stateParams);
  3116. copy(filterByKeys(to.params.$$keys(), $stateParams), to.locals.globals.$stateParams);
  3117. if (options.location && to.navigable && to.navigable.url) {
  3118. $urlRouter.push(to.navigable.url, toParams, {
  3119. $$avoidResync: true, replace: options.location === 'replace'
  3120. });
  3121. $urlRouter.update(true);
  3122. }
  3123. $state.transition = null;
  3124. return $q.when($state.current);
  3125. }
  3126. // Filter parameters before we pass them to event handlers etc.
  3127. toParams = filterByKeys(to.params.$$keys(), toParams || {});
  3128. // Re-add the saved hash before we start returning things or broadcasting $stateChangeStart
  3129. if (hash) toParams['#'] = hash;
  3130. // Broadcast start event and cancel the transition if requested
  3131. if (options.notify) {
  3132. /**
  3133. * @ngdoc event
  3134. * @name ui.router.state.$state#$stateChangeStart
  3135. * @eventOf ui.router.state.$state
  3136. * @eventType broadcast on root scope
  3137. * @description
  3138. * Fired when the state transition **begins**. You can use `event.preventDefault()`
  3139. * to prevent the transition from happening and then the transition promise will be
  3140. * rejected with a `'transition prevented'` value.
  3141. *
  3142. * @param {Object} event Event object.
  3143. * @param {State} toState The state being transitioned to.
  3144. * @param {Object} toParams The params supplied to the `toState`.
  3145. * @param {State} fromState The current state, pre-transition.
  3146. * @param {Object} fromParams The params supplied to the `fromState`.
  3147. *
  3148. * @example
  3149. *
  3150. * <pre>
  3151. * $rootScope.$on('$stateChangeStart',
  3152. * function(event, toState, toParams, fromState, fromParams){
  3153. * event.preventDefault();
  3154. * // transitionTo() promise will be rejected with
  3155. * // a 'transition prevented' error
  3156. * })
  3157. * </pre>
  3158. */
  3159. if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams, options).defaultPrevented) {
  3160. $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
  3161. //Don't update and resync url if there's been a new transition started. see issue #2238, #600
  3162. if ($state.transition == null) $urlRouter.update();
  3163. return TransitionPrevented;
  3164. }
  3165. }
  3166. // Resolve locals for the remaining states, but don't update any global state just
  3167. // yet -- if anything fails to resolve the current state needs to remain untouched.
  3168. // We also set up an inheritance chain for the locals here. This allows the view directive
  3169. // to quickly look up the correct definition for each view in the current state. Even
  3170. // though we create the locals object itself outside resolveState(), it is initially
  3171. // empty and gets filled asynchronously. We need to keep track of the promise for the
  3172. // (fully resolved) current locals, and pass this down the chain.
  3173. var resolved = $q.when(locals);
  3174. for (var l = keep; l < toPath.length; l++, state = toPath[l]) {
  3175. locals = toLocals[l] = inherit(locals);
  3176. resolved = resolveState(state, toParams, state === to, resolved, locals, options);
  3177. }
  3178. // Once everything is resolved, we are ready to perform the actual transition
  3179. // and return a promise for the new state. We also keep track of what the
  3180. // current promise is, so that we can detect overlapping transitions and
  3181. // keep only the outcome of the last transition.
  3182. var transition = $state.transition = resolved.then(function () {
  3183. var l, entering, exiting;
  3184. if ($state.transition !== transition) {
  3185. $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
  3186. return TransitionSuperseded;
  3187. }
  3188. // Exit 'from' states not kept
  3189. for (l = fromPath.length - 1; l >= keep; l--) {
  3190. exiting = fromPath[l];
  3191. if (exiting.self.onExit) {
  3192. $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
  3193. }
  3194. exiting.locals = null;
  3195. }
  3196. // Enter 'to' states not kept
  3197. for (l = keep; l < toPath.length; l++) {
  3198. entering = toPath[l];
  3199. entering.locals = toLocals[l];
  3200. if (entering.self.onEnter) {
  3201. $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
  3202. }
  3203. }
  3204. // Run it again, to catch any transitions in callbacks
  3205. if ($state.transition !== transition) {
  3206. $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
  3207. return TransitionSuperseded;
  3208. }
  3209. // Update globals in $state
  3210. $state.$current = to;
  3211. $state.current = to.self;
  3212. $state.params = toParams;
  3213. copy($state.params, $stateParams);
  3214. $state.transition = null;
  3215. if (options.location && to.navigable) {
  3216. $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
  3217. $$avoidResync: true, replace: options.location === 'replace'
  3218. });
  3219. }
  3220. if (options.notify) {
  3221. /**
  3222. * @ngdoc event
  3223. * @name ui.router.state.$state#$stateChangeSuccess
  3224. * @eventOf ui.router.state.$state
  3225. * @eventType broadcast on root scope
  3226. * @description
  3227. * Fired once the state transition is **complete**.
  3228. *
  3229. * @param {Object} event Event object.
  3230. * @param {State} toState The state being transitioned to.
  3231. * @param {Object} toParams The params supplied to the `toState`.
  3232. * @param {State} fromState The current state, pre-transition.
  3233. * @param {Object} fromParams The params supplied to the `fromState`.
  3234. */
  3235. $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
  3236. }
  3237. $urlRouter.update(true);
  3238. return $state.current;
  3239. }).then(null, function (error) {
  3240. // propagate TransitionSuperseded error without emitting $stateChangeCancel
  3241. // as it was already emitted in the success handler above
  3242. if (error === TransitionSupersededError) return TransitionSuperseded;
  3243. if ($state.transition !== transition) {
  3244. $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);
  3245. return TransitionSuperseded;
  3246. }
  3247. $state.transition = null;
  3248. /**
  3249. * @ngdoc event
  3250. * @name ui.router.state.$state#$stateChangeError
  3251. * @eventOf ui.router.state.$state
  3252. * @eventType broadcast on root scope
  3253. * @description
  3254. * Fired when an **error occurs** during transition. It's important to note that if you
  3255. * have any errors in your resolve functions (javascript errors, non-existent services, etc)
  3256. * they will not throw traditionally. You must listen for this $stateChangeError event to
  3257. * catch **ALL** errors.
  3258. *
  3259. * @param {Object} event Event object.
  3260. * @param {State} toState The state being transitioned to.
  3261. * @param {Object} toParams The params supplied to the `toState`.
  3262. * @param {State} fromState The current state, pre-transition.
  3263. * @param {Object} fromParams The params supplied to the `fromState`.
  3264. * @param {Error} error The resolve error object.
  3265. */
  3266. evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
  3267. if (!evt.defaultPrevented) {
  3268. $urlRouter.update();
  3269. }
  3270. return $q.reject(error);
  3271. });
  3272. silenceUncaughtInPromise(transition);
  3273. return transition;
  3274. };
  3275. /**
  3276. * @ngdoc function
  3277. * @name ui.router.state.$state#is
  3278. * @methodOf ui.router.state.$state
  3279. *
  3280. * @description
  3281. * Similar to {@link ui.router.state.$state#methods_includes $state.includes},
  3282. * but only checks for the full state name. If params is supplied then it will be
  3283. * tested for strict equality against the current active params object, so all params
  3284. * must match with none missing and no extras.
  3285. *
  3286. * @example
  3287. * <pre>
  3288. * $state.$current.name = 'contacts.details.item';
  3289. *
  3290. * // absolute name
  3291. * $state.is('contact.details.item'); // returns true
  3292. * $state.is(contactDetailItemStateObject); // returns true
  3293. *
  3294. * // relative name (. and ^), typically from a template
  3295. * // E.g. from the 'contacts.details' template
  3296. * <div ng-class="{highlighted: $state.is('.item')}">Item</div>
  3297. * </pre>
  3298. *
  3299. * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.
  3300. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
  3301. * to test against the current active state.
  3302. * @param {object=} options An options object. The options are:
  3303. *
  3304. * - **`relative`** - {string|object} - If `stateOrName` is a relative state name and `options.relative` is set, .is will
  3305. * test relative to `options.relative` state (or name).
  3306. *
  3307. * @returns {boolean} Returns true if it is the state.
  3308. */
  3309. $state.is = function is(stateOrName, params, options) {
  3310. options = extend({relative: $state.$current}, options || {});
  3311. var state = findState(stateOrName, options.relative);
  3312. if (!isDefined(state)) {
  3313. return undefined;
  3314. }
  3315. if ($state.$current !== state) {
  3316. return false;
  3317. }
  3318. return !params || objectKeys(params).reduce(function (acc, key) {
  3319. var paramDef = state.params[key];
  3320. return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]);
  3321. }, true);
  3322. };
  3323. /**
  3324. * @ngdoc function
  3325. * @name ui.router.state.$state#includes
  3326. * @methodOf ui.router.state.$state
  3327. *
  3328. * @description
  3329. * A method to determine if the current active state is equal to or is the child of the
  3330. * state stateName. If any params are passed then they will be tested for a match as well.
  3331. * Not all the parameters need to be passed, just the ones you'd like to test for equality.
  3332. *
  3333. * @example
  3334. * Partial and relative names
  3335. * <pre>
  3336. * $state.$current.name = 'contacts.details.item';
  3337. *
  3338. * // Using partial names
  3339. * $state.includes("contacts"); // returns true
  3340. * $state.includes("contacts.details"); // returns true
  3341. * $state.includes("contacts.details.item"); // returns true
  3342. * $state.includes("contacts.list"); // returns false
  3343. * $state.includes("about"); // returns false
  3344. *
  3345. * // Using relative names (. and ^), typically from a template
  3346. * // E.g. from the 'contacts.details' template
  3347. * <div ng-class="{highlighted: $state.includes('.item')}">Item</div>
  3348. * </pre>
  3349. *
  3350. * Basic globbing patterns
  3351. * <pre>
  3352. * $state.$current.name = 'contacts.details.item.url';
  3353. *
  3354. * $state.includes("*.details.*.*"); // returns true
  3355. * $state.includes("*.details.**"); // returns true
  3356. * $state.includes("**.item.**"); // returns true
  3357. * $state.includes("*.details.item.url"); // returns true
  3358. * $state.includes("*.details.*.url"); // returns true
  3359. * $state.includes("*.details.*"); // returns false
  3360. * $state.includes("item.**"); // returns false
  3361. * </pre>
  3362. *
  3363. * @param {string} stateOrName A partial name, relative name, or glob pattern
  3364. * to be searched for within the current state name.
  3365. * @param {object=} params A param object, e.g. `{sectionId: section.id}`,
  3366. * that you'd like to test against the current active state.
  3367. * @param {object=} options An options object. The options are:
  3368. *
  3369. * - **`relative`** - {string|object=} - If `stateOrName` is a relative state reference and `options.relative` is set,
  3370. * .includes will test relative to `options.relative` state (or name).
  3371. *
  3372. * @returns {boolean} Returns true if it does include the state
  3373. */
  3374. $state.includes = function includes(stateOrName, params, options) {
  3375. options = extend({relative: $state.$current}, options || {});
  3376. if (isString(stateOrName) && isGlob(stateOrName)) {
  3377. if (!doesStateMatchGlob(stateOrName)) {
  3378. return false;
  3379. }
  3380. stateOrName = $state.$current.name;
  3381. }
  3382. var state = findState(stateOrName, options.relative);
  3383. if (!isDefined(state)) {
  3384. return undefined;
  3385. }
  3386. if (!isDefined($state.$current.includes[state.name])) {
  3387. return false;
  3388. }
  3389. if (!params) {
  3390. return true;
  3391. }
  3392. var keys = objectKeys(params);
  3393. for (var i = 0; i < keys.length; i++) {
  3394. var key = keys[i], paramDef = state.params[key];
  3395. if (paramDef && !paramDef.type.equals($stateParams[key], params[key])) {
  3396. return false;
  3397. }
  3398. }
  3399. return objectKeys(params).reduce(function (acc, key) {
  3400. var paramDef = state.params[key];
  3401. return acc && !paramDef || paramDef.type.equals($stateParams[key], params[key]);
  3402. }, true);
  3403. };
  3404. /**
  3405. * @ngdoc function
  3406. * @name ui.router.state.$state#href
  3407. * @methodOf ui.router.state.$state
  3408. *
  3409. * @description
  3410. * A url generation method that returns the compiled url for the given state populated with the given params.
  3411. *
  3412. * @example
  3413. * <pre>
  3414. * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
  3415. * </pre>
  3416. *
  3417. * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
  3418. * @param {object=} params An object of parameter values to fill the state's required parameters.
  3419. * @param {object=} options Options object. The options are:
  3420. *
  3421. * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the
  3422. * first parameter, then the constructed href url will be built from the first navigable ancestor (aka
  3423. * ancestor with a valid url).
  3424. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
  3425. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
  3426. * defines which state to be relative from.
  3427. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
  3428. *
  3429. * @returns {string} compiled state url
  3430. */
  3431. $state.href = function href(stateOrName, params, options) {
  3432. options = extend({
  3433. lossy: true,
  3434. inherit: true,
  3435. absolute: false,
  3436. relative: $state.$current
  3437. }, options || {});
  3438. var state = findState(stateOrName, options.relative);
  3439. if (!isDefined(state)) return null;
  3440. if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);
  3441. var nav = (state && options.lossy) ? state.navigable : state;
  3442. if (!nav || nav.url === undefined || nav.url === null) {
  3443. return null;
  3444. }
  3445. return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {
  3446. absolute: options.absolute
  3447. });
  3448. };
  3449. /**
  3450. * @ngdoc function
  3451. * @name ui.router.state.$state#get
  3452. * @methodOf ui.router.state.$state
  3453. *
  3454. * @description
  3455. * Returns the state configuration object for any specific state or all states.
  3456. *
  3457. * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for
  3458. * the requested state. If not provided, returns an array of ALL state configs.
  3459. * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.
  3460. * @returns {Object|Array} State configuration object or array of all objects.
  3461. */
  3462. $state.get = function (stateOrName, context) {
  3463. if (arguments.length === 0) return map(objectKeys(states), function (name) {
  3464. return states[name].self;
  3465. });
  3466. var state = findState(stateOrName, context || $state.$current);
  3467. return (state && state.self) ? state.self : null;
  3468. };
  3469. function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {
  3470. // Make a restricted $stateParams with only the parameters that apply to this state if
  3471. // necessary. In addition to being available to the controller and onEnter/onExit callbacks,
  3472. // we also need $stateParams to be available for any $injector calls we make during the
  3473. // dependency resolution process.
  3474. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  3475. var locals = {$stateParams: $stateParams};
  3476. // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  3477. // We're also including $stateParams in this; that way the parameters are restricted
  3478. // to the set that should be visible to the state, and are independent of when we update
  3479. // the global $state and $stateParams values.
  3480. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  3481. var promises = [dst.resolve.then(function (globals) {
  3482. dst.globals = globals;
  3483. })];
  3484. if (inherited) promises.push(inherited);
  3485. function resolveViews() {
  3486. var viewsPromises = [];
  3487. // Resolve template and dependencies for all views.
  3488. forEach(state.views, function (view, name) {
  3489. var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
  3490. injectables.$template = [function () {
  3491. return $view.load(name, {
  3492. view: view,
  3493. locals: dst.globals,
  3494. params: $stateParams,
  3495. notify: options.notify
  3496. }) || '';
  3497. }];
  3498. viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {
  3499. // References to the controller (only instantiated at link time)
  3500. if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
  3501. var injectLocals = angular.extend({}, injectables, dst.globals);
  3502. result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
  3503. } else {
  3504. result.$$controller = view.controller;
  3505. }
  3506. // Provide access to the state itself for internal use
  3507. result.$$state = state;
  3508. result.$$controllerAs = view.controllerAs;
  3509. result.$$resolveAs = view.resolveAs;
  3510. dst[name] = result;
  3511. }));
  3512. });
  3513. return $q.all(viewsPromises).then(function () {
  3514. return dst.globals;
  3515. });
  3516. }
  3517. // Wait for all the promises and then return the activation object
  3518. return $q.all(promises).then(resolveViews).then(function (values) {
  3519. return dst;
  3520. });
  3521. }
  3522. return $state;
  3523. }
  3524. function shouldSkipReload(to, toParams, from, fromParams, locals, options) {
  3525. // Return true if there are no differences in non-search (path/object) params, false if there are differences
  3526. function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {
  3527. // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.
  3528. function notSearchParam(key) {
  3529. return fromAndToState.params[key].location != "search";
  3530. }
  3531. var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);
  3532. var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));
  3533. var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);
  3534. return nonQueryParamSet.$$equals(fromParams, toParams);
  3535. }
  3536. // If reload was not explicitly requested
  3537. // and we're transitioning to the same state we're already in
  3538. // and the locals didn't change
  3539. // or they changed in a way that doesn't merit reloading
  3540. // (reloadOnParams:false, or reloadOnSearch.false and only search params changed)
  3541. // Then return true.
  3542. if (!options.reload && to === from &&
  3543. (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {
  3544. return true;
  3545. }
  3546. }
  3547. }
  3548. angular.module('ui.router.state')
  3549. .factory('$stateParams', function () {
  3550. return {};
  3551. })
  3552. .constant("$state.runtime", {autoinject: true})
  3553. .provider('$state', $StateProvider)
  3554. // Inject $state to initialize when entering runtime. #2574
  3555. .run(['$injector', function ($injector) {
  3556. // Allow tests (stateSpec.js) to turn this off by defining this constant
  3557. if ($injector.get("$state.runtime").autoinject) {
  3558. $injector.get('$state');
  3559. }
  3560. }]);
  3561. $ViewProvider.$inject = [];
  3562. function $ViewProvider() {
  3563. this.$get = $get;
  3564. /**
  3565. * @ngdoc object
  3566. * @name ui.router.state.$view
  3567. *
  3568. * @requires ui.router.util.$templateFactory
  3569. * @requires $rootScope
  3570. *
  3571. * @description
  3572. *
  3573. */
  3574. $get.$inject = ['$rootScope', '$templateFactory'];
  3575. function $get($rootScope, $templateFactory) {
  3576. return {
  3577. // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })
  3578. /**
  3579. * @ngdoc function
  3580. * @name ui.router.state.$view#load
  3581. * @methodOf ui.router.state.$view
  3582. *
  3583. * @description
  3584. *
  3585. * @param {string} name name
  3586. * @param {object} options option object.
  3587. */
  3588. load: function load(name, options) {
  3589. var result, defaults = {
  3590. template: null,
  3591. controller: null,
  3592. view: null,
  3593. locals: null,
  3594. notify: true,
  3595. async: true,
  3596. params: {}
  3597. };
  3598. options = extend(defaults, options);
  3599. if (options.view) {
  3600. result = $templateFactory.fromConfig(options.view, options.params, options.locals);
  3601. }
  3602. return result;
  3603. }
  3604. };
  3605. }
  3606. }
  3607. angular.module('ui.router.state').provider('$view', $ViewProvider);
  3608. /**
  3609. * @ngdoc object
  3610. * @name ui.router.state.$uiViewScrollProvider
  3611. *
  3612. * @description
  3613. * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.
  3614. */
  3615. function $ViewScrollProvider() {
  3616. var useAnchorScroll = false;
  3617. /**
  3618. * @ngdoc function
  3619. * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll
  3620. * @methodOf ui.router.state.$uiViewScrollProvider
  3621. *
  3622. * @description
  3623. * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for
  3624. * scrolling based on the url anchor.
  3625. */
  3626. this.useAnchorScroll = function () {
  3627. useAnchorScroll = true;
  3628. };
  3629. /**
  3630. * @ngdoc object
  3631. * @name ui.router.state.$uiViewScroll
  3632. *
  3633. * @requires $anchorScroll
  3634. * @requires $timeout
  3635. *
  3636. * @description
  3637. * When called with a jqLite element, it scrolls the element into view (after a
  3638. * `$timeout` so the DOM has time to refresh).
  3639. *
  3640. * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,
  3641. * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.
  3642. */
  3643. this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {
  3644. if (useAnchorScroll) {
  3645. return $anchorScroll;
  3646. }
  3647. return function ($element) {
  3648. return $timeout(function () {
  3649. $element[0].scrollIntoView();
  3650. }, 0, false);
  3651. };
  3652. }];
  3653. }
  3654. angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);
  3655. /**
  3656. * @ngdoc directive
  3657. * @name ui.router.state.directive:ui-view
  3658. *
  3659. * @requires ui.router.state.$state
  3660. * @requires $compile
  3661. * @requires $controller
  3662. * @requires $injector
  3663. * @requires ui.router.state.$uiViewScroll
  3664. * @requires $document
  3665. *
  3666. * @restrict ECA
  3667. *
  3668. * @description
  3669. * The ui-view directive tells $state where to place your templates.
  3670. *
  3671. * @param {string=} name A view name. The name should be unique amongst the other views in the
  3672. * same state. You can have views of the same name that live in different states.
  3673. *
  3674. * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window
  3675. * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll
  3676. * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you
  3677. * scroll ui-view elements into view when they are populated during a state activation.
  3678. *
  3679. * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)
  3680. * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*
  3681. *
  3682. * @param {string=} onload Expression to evaluate whenever the view updates.
  3683. *
  3684. * @example
  3685. * A view can be unnamed or named.
  3686. * <pre>
  3687. * <!-- Unnamed -->
  3688. * <div ui-view></div>
  3689. *
  3690. * <!-- Named -->
  3691. * <div ui-view="viewName"></div>
  3692. * </pre>
  3693. *
  3694. * You can only have one unnamed view within any template (or root html). If you are only using a
  3695. * single view and it is unnamed then you can populate it like so:
  3696. * <pre>
  3697. * <div ui-view></div>
  3698. * $stateProvider.state("home", {
  3699. * template: "<h1>HELLO!</h1>"
  3700. * })
  3701. * </pre>
  3702. *
  3703. * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#methods_state `views`}
  3704. * config property, by name, in this case an empty name:
  3705. * <pre>
  3706. * $stateProvider.state("home", {
  3707. * views: {
  3708. * "": {
  3709. * template: "<h1>HELLO!</h1>"
  3710. * }
  3711. * }
  3712. * })
  3713. * </pre>
  3714. *
  3715. * But typically you'll only use the views property if you name your view or have more than one view
  3716. * in the same template. There's not really a compelling reason to name a view if its the only one,
  3717. * but you could if you wanted, like so:
  3718. * <pre>
  3719. * <div ui-view="main"></div>
  3720. * </pre>
  3721. * <pre>
  3722. * $stateProvider.state("home", {
  3723. * views: {
  3724. * "main": {
  3725. * template: "<h1>HELLO!</h1>"
  3726. * }
  3727. * }
  3728. * })
  3729. * </pre>
  3730. *
  3731. * Really though, you'll use views to set up multiple views:
  3732. * <pre>
  3733. * <div ui-view></div>
  3734. * <div ui-view="chart"></div>
  3735. * <div ui-view="data"></div>
  3736. * </pre>
  3737. *
  3738. * <pre>
  3739. * $stateProvider.state("home", {
  3740. * views: {
  3741. * "": {
  3742. * template: "<h1>HELLO!</h1>"
  3743. * },
  3744. * "chart": {
  3745. * template: "<chart_thing/>"
  3746. * },
  3747. * "data": {
  3748. * template: "<data_thing/>"
  3749. * }
  3750. * }
  3751. * })
  3752. * </pre>
  3753. *
  3754. * Examples for `autoscroll`:
  3755. *
  3756. * <pre>
  3757. * <!-- If autoscroll present with no expression,
  3758. * then scroll ui-view into view -->
  3759. * <ui-view autoscroll/>
  3760. *
  3761. * <!-- If autoscroll present with valid expression,
  3762. * then scroll ui-view into view if expression evaluates to true -->
  3763. * <ui-view autoscroll='true'/>
  3764. * <ui-view autoscroll='false'/>
  3765. * <ui-view autoscroll='scopeVariable'/>
  3766. * </pre>
  3767. *
  3768. * Resolve data:
  3769. *
  3770. * The resolved data from the state's `resolve` block is placed on the scope as `$resolve` (this
  3771. * can be customized using [[ViewDeclaration.resolveAs]]). This can be then accessed from the template.
  3772. *
  3773. * Note that when `controllerAs` is being used, `$resolve` is set on the controller instance *after* the
  3774. * controller is instantiated. The `$onInit()` hook can be used to perform initialization code which
  3775. * depends on `$resolve` data.
  3776. *
  3777. * Example usage of $resolve in a view template
  3778. * <pre>
  3779. * $stateProvider.state('home', {
  3780. * template: '<my-component user="$resolve.user"></my-component>',
  3781. * resolve: {
  3782. * user: function(UserService) { return UserService.fetchUser(); }
  3783. * }
  3784. * });
  3785. * </pre>
  3786. */
  3787. $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate', '$q'];
  3788. function $ViewDirective($state, $injector, $uiViewScroll, $interpolate, $q) {
  3789. function getService() {
  3790. return ($injector.has) ? function (service) {
  3791. return $injector.has(service) ? $injector.get(service) : null;
  3792. } : function (service) {
  3793. try {
  3794. return $injector.get(service);
  3795. } catch (e) {
  3796. return null;
  3797. }
  3798. };
  3799. }
  3800. var service = getService(),
  3801. $animator = service('$animator'),
  3802. $animate = service('$animate');
  3803. // Returns a set of DOM manipulation functions based on which Angular version
  3804. // it should use
  3805. function getRenderer(attrs, scope) {
  3806. var statics = function () {
  3807. return {
  3808. enter: function (element, target, cb) {
  3809. target.after(element);
  3810. cb();
  3811. },
  3812. leave: function (element, cb) {
  3813. element.remove();
  3814. cb();
  3815. }
  3816. };
  3817. };
  3818. if ($animate) {
  3819. return {
  3820. enter: function (element, target, cb) {
  3821. if (angular.version.minor > 2) {
  3822. $animate.enter(element, null, target).then(cb);
  3823. } else {
  3824. $animate.enter(element, null, target, cb);
  3825. }
  3826. },
  3827. leave: function (element, cb) {
  3828. if (angular.version.minor > 2) {
  3829. $animate.leave(element).then(cb);
  3830. } else {
  3831. $animate.leave(element, cb);
  3832. }
  3833. }
  3834. };
  3835. }
  3836. if ($animator) {
  3837. var animate = $animator && $animator(scope, attrs);
  3838. return {
  3839. enter: function (element, target, cb) {
  3840. animate.enter(element, null, target);
  3841. cb();
  3842. },
  3843. leave: function (element, cb) {
  3844. animate.leave(element);
  3845. cb();
  3846. }
  3847. };
  3848. }
  3849. return statics();
  3850. }
  3851. var directive = {
  3852. restrict: 'ECA',
  3853. terminal: true,
  3854. priority: 400,
  3855. transclude: 'element',
  3856. compile: function (tElement, tAttrs, $transclude) {
  3857. return function (scope, $element, attrs) {
  3858. var previousEl, currentEl, currentScope, latestLocals,
  3859. onloadExp = attrs.onload || '',
  3860. autoScrollExp = attrs.autoscroll,
  3861. renderer = getRenderer(attrs, scope),
  3862. inherited = $element.inheritedData('$uiView');
  3863. scope.$on('$stateChangeSuccess', function () {
  3864. updateView(false);
  3865. });
  3866. updateView(true);
  3867. function cleanupLastView() {
  3868. if (previousEl) {
  3869. previousEl.remove();
  3870. previousEl = null;
  3871. }
  3872. if (currentScope) {
  3873. currentScope.$destroy();
  3874. currentScope = null;
  3875. }
  3876. if (currentEl) {
  3877. var $uiViewData = currentEl.data('$uiViewAnim');
  3878. renderer.leave(currentEl, function () {
  3879. $uiViewData.$$animLeave.resolve();
  3880. previousEl = null;
  3881. });
  3882. previousEl = currentEl;
  3883. currentEl = null;
  3884. }
  3885. }
  3886. function updateView(firstTime) {
  3887. var newScope,
  3888. name = getUiViewName(scope, attrs, $element, $interpolate),
  3889. previousLocals = name && $state.$current && $state.$current.locals[name];
  3890. if (!firstTime && previousLocals === latestLocals) return; // nothing to do
  3891. newScope = scope.$new();
  3892. latestLocals = $state.$current.locals[name];
  3893. /**
  3894. * @ngdoc event
  3895. * @name ui.router.state.directive:ui-view#$viewContentLoading
  3896. * @eventOf ui.router.state.directive:ui-view
  3897. * @eventType emits on ui-view directive scope
  3898. * @description
  3899. *
  3900. * Fired once the view **begins loading**, *before* the DOM is rendered.
  3901. *
  3902. * @param {Object} event Event object.
  3903. * @param {string} viewName Name of the view.
  3904. */
  3905. newScope.$emit('$viewContentLoading', name);
  3906. var clone = $transclude(newScope, function (clone) {
  3907. var animEnter = $q.defer(), animLeave = $q.defer();
  3908. var viewAnimData = {
  3909. $animEnter: animEnter.promise,
  3910. $animLeave: animLeave.promise,
  3911. $$animLeave: animLeave
  3912. };
  3913. clone.data('$uiViewAnim', viewAnimData);
  3914. renderer.enter(clone, $element, function onUiViewEnter() {
  3915. animEnter.resolve();
  3916. if (currentScope) {
  3917. currentScope.$emit('$viewContentAnimationEnded');
  3918. }
  3919. if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {
  3920. $uiViewScroll(clone);
  3921. }
  3922. });
  3923. cleanupLastView();
  3924. });
  3925. currentEl = clone;
  3926. currentScope = newScope;
  3927. /**
  3928. * @ngdoc event
  3929. * @name ui.router.state.directive:ui-view#$viewContentLoaded
  3930. * @eventOf ui.router.state.directive:ui-view
  3931. * @eventType emits on ui-view directive scope
  3932. * @description
  3933. * Fired once the view is **loaded**, *after* the DOM is rendered.
  3934. *
  3935. * @param {Object} event Event object.
  3936. * @param {string} viewName Name of the view.
  3937. */
  3938. currentScope.$emit('$viewContentLoaded', name);
  3939. currentScope.$eval(onloadExp);
  3940. }
  3941. };
  3942. }
  3943. };
  3944. return directive;
  3945. }
  3946. $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];
  3947. function $ViewDirectiveFill($compile, $controller, $state, $interpolate) {
  3948. return {
  3949. restrict: 'ECA',
  3950. priority: -400,
  3951. compile: function (tElement) {
  3952. var initial = tElement.html();
  3953. if (tElement.empty) {
  3954. tElement.empty();
  3955. } else {
  3956. // ng 1.0.0 doesn't have empty(), which cleans up data and handlers
  3957. tElement[0].innerHTML = null;
  3958. }
  3959. return function (scope, $element, attrs) {
  3960. var current = $state.$current,
  3961. name = getUiViewName(scope, attrs, $element, $interpolate),
  3962. locals = current && current.locals[name];
  3963. if (!locals) {
  3964. $element.html(initial);
  3965. $compile($element.contents())(scope);
  3966. return;
  3967. }
  3968. $element.data('$uiView', {name: name, state: locals.$$state});
  3969. $element.html(locals.$template ? locals.$template : initial);
  3970. var resolveData = angular.extend({}, locals);
  3971. scope[locals.$$resolveAs] = resolveData;
  3972. var link = $compile($element.contents());
  3973. if (locals.$$controller) {
  3974. locals.$scope = scope;
  3975. locals.$element = $element;
  3976. var controller = $controller(locals.$$controller, locals);
  3977. if (locals.$$controllerAs) {
  3978. scope[locals.$$controllerAs] = controller;
  3979. scope[locals.$$controllerAs][locals.$$resolveAs] = resolveData;
  3980. }
  3981. if (isFunction(controller.$onInit)) controller.$onInit();
  3982. $element.data('$ngControllerController', controller);
  3983. $element.children().data('$ngControllerController', controller);
  3984. }
  3985. link(scope);
  3986. };
  3987. }
  3988. };
  3989. }
  3990. /**
  3991. * Shared ui-view code for both directives:
  3992. * Given scope, element, and its attributes, return the view's name
  3993. */
  3994. function getUiViewName(scope, attrs, element, $interpolate) {
  3995. var name = $interpolate(attrs.uiView || attrs.name || '')(scope);
  3996. var uiViewCreatedBy = element.inheritedData('$uiView');
  3997. return name.indexOf('@') >= 0 ? name : (name + '@' + (uiViewCreatedBy ? uiViewCreatedBy.state.name : ''));
  3998. }
  3999. angular.module('ui.router.state').directive('uiView', $ViewDirective);
  4000. angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);
  4001. function parseStateRef(ref, current) {
  4002. var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  4003. if (preparsed) ref = current + '(' + preparsed[1] + ')';
  4004. parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  4005. if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  4006. return {state: parsed[1], paramExpr: parsed[3] || null};
  4007. }
  4008. function stateContext(el) {
  4009. var stateData = el.parent().inheritedData('$uiView');
  4010. if (stateData && stateData.state && stateData.state.name) {
  4011. return stateData.state;
  4012. }
  4013. }
  4014. function getTypeInfo(el) {
  4015. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  4016. var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
  4017. var isForm = el[0].nodeName === "FORM";
  4018. return {
  4019. attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
  4020. isAnchor: el.prop("tagName").toUpperCase() === "A",
  4021. clickable: !isForm
  4022. };
  4023. }
  4024. function clickHook(el, $state, $timeout, type, current) {
  4025. return function (e) {
  4026. var button = e.which || e.button, target = current();
  4027. if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
  4028. // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
  4029. var transition = $timeout(function () {
  4030. $state.go(target.state, target.params, target.options);
  4031. });
  4032. e.preventDefault();
  4033. // if the state has no URL, ignore one preventDefault from the <a> directive.
  4034. var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1 : 0;
  4035. e.preventDefault = function () {
  4036. if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);
  4037. };
  4038. }
  4039. };
  4040. }
  4041. function defaultOpts(el, $state) {
  4042. return {relative: stateContext(el) || $state.$current, inherit: true};
  4043. }
  4044. /**
  4045. * @ngdoc directive
  4046. * @name ui.router.state.directive:ui-sref
  4047. *
  4048. * @requires ui.router.state.$state
  4049. * @requires $timeout
  4050. *
  4051. * @restrict A
  4052. *
  4053. * @description
  4054. * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
  4055. * URL, the directive will automatically generate & update the `href` attribute via
  4056. * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
  4057. * the link will trigger a state transition with optional parameters.
  4058. *
  4059. * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
  4060. * handled natively by the browser.
  4061. *
  4062. * You can also use relative state paths within ui-sref, just like the relative
  4063. * paths passed to `$state.go()`. You just need to be aware that the path is relative
  4064. * to the state that the link lives in, in other words the state that loaded the
  4065. * template containing the link.
  4066. *
  4067. * You can specify options to pass to {@link ui.router.state.$state#methods_go $state.go()}
  4068. * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
  4069. * and `reload`.
  4070. *
  4071. * @example
  4072. * Here's an example of how you'd use ui-sref and how it would compile. If you have the
  4073. * following template:
  4074. * <pre>
  4075. * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
  4076. *
  4077. * <ul>
  4078. * <li ng-repeat="contact in contacts">
  4079. * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
  4080. * </li>
  4081. * </ul>
  4082. * </pre>
  4083. *
  4084. * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
  4085. * <pre>
  4086. * <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>
  4087. *
  4088. * <ul>
  4089. * <li ng-repeat="contact in contacts">
  4090. * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
  4091. * </li>
  4092. * <li ng-repeat="contact in contacts">
  4093. * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
  4094. * </li>
  4095. * <li ng-repeat="contact in contacts">
  4096. * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
  4097. * </li>
  4098. * </ul>
  4099. *
  4100. * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
  4101. * </pre>
  4102. *
  4103. * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
  4104. * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()}
  4105. */
  4106. $StateRefDirective.$inject = ['$state', '$timeout'];
  4107. function $StateRefDirective($state, $timeout) {
  4108. return {
  4109. restrict: 'A',
  4110. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  4111. link: function (scope, element, attrs, uiSrefActive) {
  4112. var ref = parseStateRef(attrs.uiSref, $state.current.name);
  4113. var def = {state: ref.state, href: null, params: null};
  4114. var type = getTypeInfo(element);
  4115. var active = uiSrefActive[1] || uiSrefActive[0];
  4116. var unlinkInfoFn = null;
  4117. var hookFn;
  4118. def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {});
  4119. var update = function (val) {
  4120. if (val) def.params = angular.copy(val);
  4121. def.href = $state.href(ref.state, def.params, def.options);
  4122. if (unlinkInfoFn) unlinkInfoFn();
  4123. if (active) unlinkInfoFn = active.$$addStateInfo(ref.state, def.params);
  4124. if (def.href !== null) attrs.$set(type.attr, def.href);
  4125. };
  4126. if (ref.paramExpr) {
  4127. scope.$watch(ref.paramExpr, function (val) {
  4128. if (val !== def.params) update(val);
  4129. }, true);
  4130. def.params = angular.copy(scope.$eval(ref.paramExpr));
  4131. }
  4132. update();
  4133. if (!type.clickable) return;
  4134. hookFn = clickHook(element, $state, $timeout, type, function () {
  4135. return def;
  4136. });
  4137. element[element.on ? 'on' : 'bind']("click", hookFn);
  4138. scope.$on('$destroy', function () {
  4139. element[element.off ? 'off' : 'unbind']("click", hookFn);
  4140. });
  4141. }
  4142. };
  4143. }
  4144. /**
  4145. * @ngdoc directive
  4146. * @name ui.router.state.directive:ui-state
  4147. *
  4148. * @requires ui.router.state.uiSref
  4149. *
  4150. * @restrict A
  4151. *
  4152. * @description
  4153. * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition,
  4154. * params and override options.
  4155. *
  4156. * @param {string} ui-state 'stateName' can be any valid absolute or relative state
  4157. * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#methods_href $state.href()}
  4158. * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#methods_go $state.go()}
  4159. */
  4160. $StateRefDynamicDirective.$inject = ['$state', '$timeout'];
  4161. function $StateRefDynamicDirective($state, $timeout) {
  4162. return {
  4163. restrict: 'A',
  4164. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  4165. link: function (scope, element, attrs, uiSrefActive) {
  4166. var type = getTypeInfo(element);
  4167. var active = uiSrefActive[1] || uiSrefActive[0];
  4168. var group = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null];
  4169. var watch = '[' + group.map(function (val) {
  4170. return val || 'null';
  4171. }).join(', ') + ']';
  4172. var def = {state: null, params: null, options: null, href: null};
  4173. var unlinkInfoFn = null;
  4174. var hookFn;
  4175. function runStateRefLink(group) {
  4176. def.state = group[0];
  4177. def.params = group[1];
  4178. def.options = group[2];
  4179. def.href = $state.href(def.state, def.params, def.options);
  4180. if (unlinkInfoFn) unlinkInfoFn();
  4181. if (active) unlinkInfoFn = active.$$addStateInfo(def.state, def.params);
  4182. if (def.href) attrs.$set(type.attr, def.href);
  4183. }
  4184. scope.$watch(watch, runStateRefLink, true);
  4185. runStateRefLink(scope.$eval(watch));
  4186. if (!type.clickable) return;
  4187. hookFn = clickHook(element, $state, $timeout, type, function () {
  4188. return def;
  4189. });
  4190. element[element.on ? 'on' : 'bind']("click", hookFn);
  4191. scope.$on('$destroy', function () {
  4192. element[element.off ? 'off' : 'unbind']("click", hookFn);
  4193. });
  4194. }
  4195. };
  4196. }
  4197. /**
  4198. * @ngdoc directive
  4199. * @name ui.router.state.directive:ui-sref-active
  4200. *
  4201. * @requires ui.router.state.$state
  4202. * @requires ui.router.state.$stateParams
  4203. * @requires $interpolate
  4204. *
  4205. * @restrict A
  4206. *
  4207. * @description
  4208. * A directive working alongside ui-sref to add classes to an element when the
  4209. * related ui-sref directive's state is active, and removing them when it is inactive.
  4210. * The primary use-case is to simplify the special appearance of navigation menus
  4211. * relying on `ui-sref`, by having the "active" state's menu button appear different,
  4212. * distinguishing it from the inactive menu items.
  4213. *
  4214. * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
  4215. * ui-sref-active found at the same level or above the ui-sref will be used.
  4216. *
  4217. * Will activate when the ui-sref's target state or any child state is active. If you
  4218. * need to activate only when the ui-sref target state is active and *not* any of
  4219. * it's children, then you will use
  4220. * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
  4221. *
  4222. * @example
  4223. * Given the following template:
  4224. * <pre>
  4225. * <ul>
  4226. * <li ui-sref-active="active" class="item">
  4227. * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  4228. * </li>
  4229. * </ul>
  4230. * </pre>
  4231. *
  4232. *
  4233. * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
  4234. * the resulting HTML will appear as (note the 'active' class):
  4235. * <pre>
  4236. * <ul>
  4237. * <li ui-sref-active="active" class="item active">
  4238. * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  4239. * </li>
  4240. * </ul>
  4241. * </pre>
  4242. *
  4243. * The class name is interpolated **once** during the directives link time (any further changes to the
  4244. * interpolated value are ignored).
  4245. *
  4246. * Multiple classes may be specified in a space-separated format:
  4247. * <pre>
  4248. * <ul>
  4249. * <li ui-sref-active='class1 class2 class3'>
  4250. * <a ui-sref="app.user">link</a>
  4251. * </li>
  4252. * </ul>
  4253. * </pre>
  4254. *
  4255. * It is also possible to pass ui-sref-active an expression that evaluates
  4256. * to an object hash, whose keys represent active class names and whose
  4257. * values represent the respective state names/globs.
  4258. * ui-sref-active will match if the current active state **includes** any of
  4259. * the specified state names/globs, even the abstract ones.
  4260. *
  4261. * @Example
  4262. * Given the following template, with "admin" being an abstract state:
  4263. * <pre>
  4264. * <div ui-sref-active="{'active': 'admin.*'}">
  4265. * <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
  4266. * </div>
  4267. * </pre>
  4268. *
  4269. * When the current state is "admin.roles" the "active" class will be applied
  4270. * to both the <div> and <a> elements. It is important to note that the state
  4271. * names/globs passed to ui-sref-active shadow the state provided by ui-sref.
  4272. */
  4273. /**
  4274. * @ngdoc directive
  4275. * @name ui.router.state.directive:ui-sref-active-eq
  4276. *
  4277. * @requires ui.router.state.$state
  4278. * @requires ui.router.state.$stateParams
  4279. * @requires $interpolate
  4280. *
  4281. * @restrict A
  4282. *
  4283. * @description
  4284. * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
  4285. * when the exact target state used in the `ui-sref` is active; no child states.
  4286. *
  4287. */
  4288. $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
  4289. function $StateRefActiveDirective($state, $stateParams, $interpolate) {
  4290. return {
  4291. restrict: "A",
  4292. controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
  4293. var states = [], activeClasses = {}, activeEqClass, uiSrefActive;
  4294. // There probably isn't much point in $observing this
  4295. // uiSrefActive and uiSrefActiveEq share the same directive object with some
  4296. // slight difference in logic routing
  4297. activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
  4298. try {
  4299. uiSrefActive = $scope.$eval($attrs.uiSrefActive);
  4300. } catch (e) {
  4301. // Do nothing. uiSrefActive is not a valid expression.
  4302. // Fall back to using $interpolate below
  4303. }
  4304. uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
  4305. if (isObject(uiSrefActive)) {
  4306. forEach(uiSrefActive, function (stateOrName, activeClass) {
  4307. if (isString(stateOrName)) {
  4308. var ref = parseStateRef(stateOrName, $state.current.name);
  4309. addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
  4310. }
  4311. });
  4312. }
  4313. // Allow uiSref to communicate with uiSrefActive[Equals]
  4314. this.$$addStateInfo = function (newState, newParams) {
  4315. // we already got an explicit state provided by ui-sref-active, so we
  4316. // shadow the one that comes from ui-sref
  4317. if (isObject(uiSrefActive) && states.length > 0) {
  4318. return;
  4319. }
  4320. var deregister = addState(newState, newParams, uiSrefActive);
  4321. update();
  4322. return deregister;
  4323. };
  4324. $scope.$on('$stateChangeSuccess', update);
  4325. function addState(stateName, stateParams, activeClass) {
  4326. var state = $state.get(stateName, stateContext($element));
  4327. var stateHash = createStateHash(stateName, stateParams);
  4328. var stateInfo = {
  4329. state: state || {name: stateName},
  4330. params: stateParams,
  4331. hash: stateHash
  4332. };
  4333. states.push(stateInfo);
  4334. activeClasses[stateHash] = activeClass;
  4335. return function removeState() {
  4336. var idx = states.indexOf(stateInfo);
  4337. if (idx !== -1) states.splice(idx, 1);
  4338. };
  4339. }
  4340. /**
  4341. * @param {string} state
  4342. * @param {Object|string} [params]
  4343. * @return {string}
  4344. */
  4345. function createStateHash(state, params) {
  4346. if (!isString(state)) {
  4347. throw new Error('state should be a string');
  4348. }
  4349. if (isObject(params)) {
  4350. return state + toJson(params);
  4351. }
  4352. params = $scope.$eval(params);
  4353. if (isObject(params)) {
  4354. return state + toJson(params);
  4355. }
  4356. return state;
  4357. }
  4358. // Update route state
  4359. function update() {
  4360. for (var i = 0; i < states.length; i++) {
  4361. if (anyMatch(states[i].state, states[i].params)) {
  4362. addClass($element, activeClasses[states[i].hash]);
  4363. } else {
  4364. removeClass($element, activeClasses[states[i].hash]);
  4365. }
  4366. if (exactMatch(states[i].state, states[i].params)) {
  4367. addClass($element, activeEqClass);
  4368. } else {
  4369. removeClass($element, activeEqClass);
  4370. }
  4371. }
  4372. }
  4373. function addClass(el, className) {
  4374. $timeout(function () {
  4375. el.addClass(className);
  4376. });
  4377. }
  4378. function removeClass(el, className) {
  4379. el.removeClass(className);
  4380. }
  4381. function anyMatch(state, params) {
  4382. return $state.includes(state.name, params);
  4383. }
  4384. function exactMatch(state, params) {
  4385. return $state.is(state.name, params);
  4386. }
  4387. update();
  4388. }]
  4389. };
  4390. }
  4391. angular.module('ui.router.state')
  4392. .directive('uiSref', $StateRefDirective)
  4393. .directive('uiSrefActive', $StateRefActiveDirective)
  4394. .directive('uiSrefActiveEq', $StateRefActiveDirective)
  4395. .directive('uiState', $StateRefDynamicDirective);
  4396. /**
  4397. * @ngdoc filter
  4398. * @name ui.router.state.filter:isState
  4399. *
  4400. * @requires ui.router.state.$state
  4401. *
  4402. * @description
  4403. * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}.
  4404. */
  4405. $IsStateFilter.$inject = ['$state'];
  4406. function $IsStateFilter($state) {
  4407. var isFilter = function (state, params) {
  4408. return $state.is(state, params);
  4409. };
  4410. isFilter.$stateful = true;
  4411. return isFilter;
  4412. }
  4413. /**
  4414. * @ngdoc filter
  4415. * @name ui.router.state.filter:includedByState
  4416. *
  4417. * @requires ui.router.state.$state
  4418. *
  4419. * @description
  4420. * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.
  4421. */
  4422. $IncludedByStateFilter.$inject = ['$state'];
  4423. function $IncludedByStateFilter($state) {
  4424. var includesFilter = function (state, params, options) {
  4425. return $state.includes(state, params, options);
  4426. };
  4427. includesFilter.$stateful = true;
  4428. return includesFilter;
  4429. }
  4430. angular.module('ui.router.state')
  4431. .filter('isState', $IsStateFilter)
  4432. .filter('includedByState', $IncludedByStateFilter);
  4433. })(window, window.angular);