angular-ui-router.js 159KB

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