angular-ui-router.js 153 KB

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