angular-ui-router.js 152 KB

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