angular-ui-router.js 129 KB

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