angular-ui-router.js 168 KB

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