stateDirectives.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. function parseStateRef(ref, current) {
  2. var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
  3. if (preparsed) ref = current + '(' + preparsed[1] + ')';
  4. parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
  5. if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'");
  6. return { state: parsed[1], paramExpr: parsed[3] || null };
  7. }
  8. function stateContext(el) {
  9. var stateData = el.parent().inheritedData('$uiView');
  10. if (stateData && stateData.state && stateData.state.name) {
  11. return stateData.state;
  12. }
  13. }
  14. /**
  15. * @ngdoc directive
  16. * @name ui.router.state.directive:ui-sref
  17. *
  18. * @requires ui.router.state.$state
  19. * @requires $timeout
  20. *
  21. * @restrict A
  22. *
  23. * @description
  24. * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
  25. * URL, the directive will automatically generate & update the `href` attribute via
  26. * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
  27. * the link will trigger a state transition with optional parameters.
  28. *
  29. * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
  30. * handled natively by the browser.
  31. *
  32. * You can also use relative state paths within ui-sref, just like the relative
  33. * paths passed to `$state.go()`. You just need to be aware that the path is relative
  34. * to the state that the link lives in, in other words the state that loaded the
  35. * template containing the link.
  36. *
  37. * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
  38. * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
  39. * and `reload`.
  40. *
  41. * @example
  42. * Here's an example of how you'd use ui-sref and how it would compile. If you have the
  43. * following template:
  44. * <pre>
  45. * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
  46. *
  47. * <ul>
  48. * <li ng-repeat="contact in contacts">
  49. * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
  50. * </li>
  51. * </ul>
  52. * </pre>
  53. *
  54. * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
  55. * <pre>
  56. * <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>
  57. *
  58. * <ul>
  59. * <li ng-repeat="contact in contacts">
  60. * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
  61. * </li>
  62. * <li ng-repeat="contact in contacts">
  63. * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
  64. * </li>
  65. * <li ng-repeat="contact in contacts">
  66. * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
  67. * </li>
  68. * </ul>
  69. *
  70. * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
  71. * </pre>
  72. *
  73. * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
  74. * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
  75. */
  76. $StateRefDirective.$inject = ['$state', '$timeout'];
  77. function $StateRefDirective($state, $timeout) {
  78. var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];
  79. return {
  80. restrict: 'A',
  81. require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
  82. link: function(scope, element, attrs, uiSrefActive) {
  83. var ref = parseStateRef(attrs.uiSref, $state.current.name);
  84. var params = null, url = null, base = stateContext(element) || $state.$current;
  85. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  86. var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  87. 'xlink:href' : 'href';
  88. var newHref = null, isAnchor = element.prop("tagName").toUpperCase() === "A";
  89. var isForm = element[0].nodeName === "FORM";
  90. var attr = isForm ? "action" : hrefKind, nav = true;
  91. var options = { relative: base, inherit: true };
  92. var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};
  93. angular.forEach(allowedOptions, function(option) {
  94. if (option in optionsOverride) {
  95. options[option] = optionsOverride[option];
  96. }
  97. });
  98. var update = function(newVal) {
  99. if (newVal) params = angular.copy(newVal);
  100. if (!nav) return;
  101. newHref = $state.href(ref.state, params, options);
  102. var activeDirective = uiSrefActive[1] || uiSrefActive[0];
  103. if (activeDirective) {
  104. activeDirective.$$addStateInfo(ref.state, params);
  105. }
  106. if (newHref === null) {
  107. nav = false;
  108. return false;
  109. }
  110. attrs.$set(attr, newHref);
  111. };
  112. if (ref.paramExpr) {
  113. scope.$watch(ref.paramExpr, function(newVal, oldVal) {
  114. if (newVal !== params) update(newVal);
  115. }, true);
  116. params = angular.copy(scope.$eval(ref.paramExpr));
  117. }
  118. update();
  119. if (isForm) return;
  120. element.bind("click", function(e) {
  121. var button = e.which || e.button;
  122. if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {
  123. // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
  124. var transition = $timeout(function() {
  125. $state.go(ref.state, params, options);
  126. });
  127. e.preventDefault();
  128. // if the state has no URL, ignore one preventDefault from the <a> directive.
  129. var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;
  130. e.preventDefault = function() {
  131. if (ignorePreventDefaultCount-- <= 0)
  132. $timeout.cancel(transition);
  133. };
  134. }
  135. });
  136. }
  137. };
  138. }
  139. /**
  140. * @ngdoc directive
  141. * @name ui.router.state.directive:ui-sref-active
  142. *
  143. * @requires ui.router.state.$state
  144. * @requires ui.router.state.$stateParams
  145. * @requires $interpolate
  146. *
  147. * @restrict A
  148. *
  149. * @description
  150. * A directive working alongside ui-sref to add classes to an element when the
  151. * related ui-sref directive's state is active, and removing them when it is inactive.
  152. * The primary use-case is to simplify the special appearance of navigation menus
  153. * relying on `ui-sref`, by having the "active" state's menu button appear different,
  154. * distinguishing it from the inactive menu items.
  155. *
  156. * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
  157. * ui-sref-active found at the same level or above the ui-sref will be used.
  158. *
  159. * Will activate when the ui-sref's target state or any child state is active. If you
  160. * need to activate only when the ui-sref target state is active and *not* any of
  161. * it's children, then you will use
  162. * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
  163. *
  164. * @example
  165. * Given the following template:
  166. * <pre>
  167. * <ul>
  168. * <li ui-sref-active="active" class="item">
  169. * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  170. * </li>
  171. * </ul>
  172. * </pre>
  173. *
  174. *
  175. * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
  176. * the resulting HTML will appear as (note the 'active' class):
  177. * <pre>
  178. * <ul>
  179. * <li ui-sref-active="active" class="item active">
  180. * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
  181. * </li>
  182. * </ul>
  183. * </pre>
  184. *
  185. * The class name is interpolated **once** during the directives link time (any further changes to the
  186. * interpolated value are ignored).
  187. *
  188. * Multiple classes may be specified in a space-separated format:
  189. * <pre>
  190. * <ul>
  191. * <li ui-sref-active='class1 class2 class3'>
  192. * <a ui-sref="app.user">link</a>
  193. * </li>
  194. * </ul>
  195. * </pre>
  196. */
  197. /**
  198. * @ngdoc directive
  199. * @name ui.router.state.directive:ui-sref-active-eq
  200. *
  201. * @requires ui.router.state.$state
  202. * @requires ui.router.state.$stateParams
  203. * @requires $interpolate
  204. *
  205. * @restrict A
  206. *
  207. * @description
  208. * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
  209. * when the exact target state used in the `ui-sref` is active; no child states.
  210. *
  211. */
  212. $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
  213. function $StateRefActiveDirective($state, $stateParams, $interpolate) {
  214. return {
  215. restrict: "A",
  216. controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
  217. var states = [], activeClass;
  218. // There probably isn't much point in $observing this
  219. // uiSrefActive and uiSrefActiveEq share the same directive object with some
  220. // slight difference in logic routing
  221. activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);
  222. // Allow uiSref to communicate with uiSrefActive[Equals]
  223. this.$$addStateInfo = function (newState, newParams) {
  224. var state = $state.get(newState, stateContext($element));
  225. states.push({
  226. state: state || { name: newState },
  227. params: newParams
  228. });
  229. update();
  230. };
  231. $scope.$on('$stateChangeSuccess', update);
  232. // Update route state
  233. function update() {
  234. if (anyMatch()) {
  235. $element.addClass(activeClass);
  236. } else {
  237. $element.removeClass(activeClass);
  238. }
  239. }
  240. function anyMatch() {
  241. for (var i = 0; i < states.length; i++) {
  242. if (isMatch(states[i].state, states[i].params)) {
  243. return true;
  244. }
  245. }
  246. return false;
  247. }
  248. function isMatch(state, params) {
  249. if (typeof $attrs.uiSrefActiveEq !== 'undefined') {
  250. return $state.is(state.name, params);
  251. } else {
  252. return $state.includes(state.name, params);
  253. }
  254. }
  255. }]
  256. };
  257. }
  258. angular.module('ui.router.state')
  259. .directive('uiSref', $StateRefDirective)
  260. .directive('uiSrefActive', $StateRefActiveDirective)
  261. .directive('uiSrefActiveEq', $StateRefActiveDirective);