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 };
9 function stateContext(el) {
10 var stateData = el.parent().inheritedData('$uiView');
12 if (stateData && stateData.state && stateData.state.name) {
13 return stateData.state;
17 function getTypeInfo(el) {
18 // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
19 var isSvg = Object.prototype.toString.call(el.prop('href')) === '[object SVGAnimatedString]';
20 var isForm = el[0].nodeName === "FORM";
23 attr: isForm ? "action" : (isSvg ? 'xlink:href' : 'href'),
24 isAnchor: el.prop("tagName").toUpperCase() === "A",
29 function clickHook(el, $state, $timeout, type, current) {
31 var button = e.which || e.button, target = current();
33 if (!(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || el.attr('target'))) {
34 // HACK: This is to allow ng-clicks to be processed before the transition is initiated:
35 var transition = $timeout(function() {
36 $state.go(target.state, target.params, target.options);
40 // if the state has no URL, ignore one preventDefault from the <a> directive.
41 var ignorePreventDefaultCount = type.isAnchor && !target.href ? 1: 0;
43 e.preventDefault = function() {
44 if (ignorePreventDefaultCount-- <= 0) $timeout.cancel(transition);
50 function defaultOpts(el, $state) {
51 return { relative: stateContext(el) || $state.$current, inherit: true };
56 * @name ui.router.state.directive:ui-sref
58 * @requires ui.router.state.$state
64 * A directive that binds a link (`<a>` tag) to a state. If the state has an associated
65 * URL, the directive will automatically generate & update the `href` attribute via
66 * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking
67 * the link will trigger a state transition with optional parameters.
69 * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be
70 * handled natively by the browser.
72 * You can also use relative state paths within ui-sref, just like the relative
73 * paths passed to `$state.go()`. You just need to be aware that the path is relative
74 * to the state that the link lives in, in other words the state that loaded the
75 * template containing the link.
77 * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}
78 * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,
82 * Here's an example of how you'd use ui-sref and how it would compile. If you have the
85 * <a ui-sref="home">Home</a> | <a ui-sref="about">About</a> | <a ui-sref="{page: 2}">Next page</a>
88 * <li ng-repeat="contact in contacts">
89 * <a ui-sref="contacts.detail({ id: contact.id })">{{ contact.name }}</a>
94 * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):
96 * <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>
99 * <li ng-repeat="contact in contacts">
100 * <a href="#/contacts/1" ui-sref="contacts.detail({ id: contact.id })">Joe</a>
102 * <li ng-repeat="contact in contacts">
103 * <a href="#/contacts/2" ui-sref="contacts.detail({ id: contact.id })">Alice</a>
105 * <li ng-repeat="contact in contacts">
106 * <a href="#/contacts/3" ui-sref="contacts.detail({ id: contact.id })">Bob</a>
110 * <a ui-sref="home" ui-sref-opts="{reload: true}">Home</a>
113 * @param {string} ui-sref 'stateName' can be any valid absolute or relative state
114 * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}
116 $StateRefDirective.$inject = ['$state', '$timeout'];
117 function $StateRefDirective($state, $timeout) {
120 require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
121 link: function(scope, element, attrs, uiSrefActive) {
122 var ref = parseStateRef(attrs.uiSref, $state.current.name);
123 var def = { state: ref.state, href: null, params: null };
124 var type = getTypeInfo(element);
125 var active = uiSrefActive[1] || uiSrefActive[0];
127 def.options = extend(defaultOpts(element, $state), attrs.uiSrefOpts ? scope.$eval(attrs.uiSrefOpts) : {});
129 var update = function(val) {
130 if (val) def.params = angular.copy(val);
131 def.href = $state.href(ref.state, def.params, def.options);
133 if (active) active.$$addStateInfo(ref.state, def.params);
134 if (def.href !== null) attrs.$set(type.attr, def.href);
138 scope.$watch(ref.paramExpr, function(val) { if (val !== def.params) update(val); }, true);
139 def.params = angular.copy(scope.$eval(ref.paramExpr));
143 if (!type.clickable) return;
144 element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
151 * @name ui.router.state.directive:ui-state
153 * @requires ui.router.state.uiSref
158 * Much like ui-sref, but will accept named $scope properties to evaluate for a state definition,
159 * params and override options.
161 * @param {string} ui-state 'stateName' can be any valid absolute or relative state
162 * @param {Object} ui-state-params params to pass to {@link ui.router.state.$state#href $state.href()}
163 * @param {Object} ui-state-opts options to pass to {@link ui.router.state.$state#go $state.go()}
165 $StateRefDynamicDirective.$inject = ['$state', '$timeout'];
166 function $StateRefDynamicDirective($state, $timeout) {
169 require: ['?^uiSrefActive', '?^uiSrefActiveEq'],
170 link: function(scope, element, attrs, uiSrefActive) {
171 var type = getTypeInfo(element);
172 var active = uiSrefActive[1] || uiSrefActive[0];
173 var group = [attrs.uiState, attrs.uiStateParams || null, attrs.uiStateOpts || null];
174 var watch = '[' + group.map(function(val) { return val || 'null'; }).join(', ') + ']';
175 var def = { state: null, params: null, options: null, href: null };
177 function runStateRefLink (group) {
178 def.state = group[0]; def.params = group[1]; def.options = group[2];
179 def.href = $state.href(def.state, def.params, def.options);
181 if (active) active.$$addStateInfo(def.state, def.params);
182 if (def.href) attrs.$set(type.attr, def.href);
185 scope.$watch(watch, runStateRefLink, true);
186 runStateRefLink(scope.$eval(watch));
188 if (!type.clickable) return;
189 element.bind("click", clickHook(element, $state, $timeout, type, function() { return def; }));
197 * @name ui.router.state.directive:ui-sref-active
199 * @requires ui.router.state.$state
200 * @requires ui.router.state.$stateParams
201 * @requires $interpolate
206 * A directive working alongside ui-sref to add classes to an element when the
207 * related ui-sref directive's state is active, and removing them when it is inactive.
208 * The primary use-case is to simplify the special appearance of navigation menus
209 * relying on `ui-sref`, by having the "active" state's menu button appear different,
210 * distinguishing it from the inactive menu items.
212 * ui-sref-active can live on the same element as ui-sref or on a parent element. The first
213 * ui-sref-active found at the same level or above the ui-sref will be used.
215 * Will activate when the ui-sref's target state or any child state is active. If you
216 * need to activate only when the ui-sref target state is active and *not* any of
217 * it's children, then you will use
218 * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}
221 * Given the following template:
224 * <li ui-sref-active="active" class="item">
225 * <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
231 * When the app state is "app.user" (or any children states), and contains the state parameter "user" with value "bilbobaggins",
232 * the resulting HTML will appear as (note the 'active' class):
235 * <li ui-sref-active="active" class="item active">
236 * <a ui-sref="app.user({user: 'bilbobaggins'})" href="/users/bilbobaggins">@bilbobaggins</a>
241 * The class name is interpolated **once** during the directives link time (any further changes to the
242 * interpolated value are ignored).
244 * Multiple classes may be specified in a space-separated format:
247 * <li ui-sref-active='class1 class2 class3'>
248 * <a ui-sref="app.user">link</a>
253 * It is also possible to pass ui-sref-active an expression that evaluates
254 * to an object hash, whose keys represent active class names and whose
255 * values represent the respective state names/globs.
256 * ui-sref-active will match if the current active state **includes** any of
257 * the specified state names/globs, even the abstract ones.
260 * Given the following template, with "admin" being an abstract state:
262 * <div ui-sref-active="{'active': 'admin.*'}">
263 * <a ui-sref-active="active" ui-sref="admin.roles">Roles</a>
267 * When the current state is "admin.roles" the "active" class will be applied
268 * to both the <div> and <a> elements. It is important to note that the state
269 * names/globs passed to ui-sref-active shadow the state provided by ui-sref.
274 * @name ui.router.state.directive:ui-sref-active-eq
276 * @requires ui.router.state.$state
277 * @requires ui.router.state.$stateParams
278 * @requires $interpolate
283 * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate
284 * when the exact target state used in the `ui-sref` is active; no child states.
287 $StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];
288 function $StateRefActiveDirective($state, $stateParams, $interpolate) {
291 controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
292 var states = [], activeClasses = {}, activeEqClass, uiSrefActive;
294 // There probably isn't much point in $observing this
295 // uiSrefActive and uiSrefActiveEq share the same directive object with some
296 // slight difference in logic routing
297 activeEqClass = $interpolate($attrs.uiSrefActiveEq || '', false)($scope);
300 uiSrefActive = $scope.$eval($attrs.uiSrefActive);
302 // Do nothing. uiSrefActive is not a valid expression.
303 // Fall back to using $interpolate below
305 uiSrefActive = uiSrefActive || $interpolate($attrs.uiSrefActive || '', false)($scope);
306 if (isObject(uiSrefActive)) {
307 forEach(uiSrefActive, function(stateOrName, activeClass) {
308 if (isString(stateOrName)) {
309 var ref = parseStateRef(stateOrName, $state.current.name);
310 addState(ref.state, $scope.$eval(ref.paramExpr), activeClass);
315 // Allow uiSref to communicate with uiSrefActive[Equals]
316 this.$$addStateInfo = function (newState, newParams) {
317 // we already got an explicit state provided by ui-sref-active, so we
318 // shadow the one that comes from ui-sref
319 if (isObject(uiSrefActive) && states.length > 0) {
322 addState(newState, newParams, uiSrefActive);
326 $scope.$on('$stateChangeSuccess', update);
328 function addState(stateName, stateParams, activeClass) {
329 var state = $state.get(stateName, stateContext($element));
330 var stateHash = createStateHash(stateName, stateParams);
333 state: state || { name: stateName },
338 activeClasses[stateHash] = activeClass;
342 * @param {string} state
343 * @param {Object|string} [params]
346 function createStateHash(state, params) {
347 if (!isString(state)) {
348 throw new Error('state should be a string');
350 if (isObject(params)) {
351 return state + toJson(params);
353 params = $scope.$eval(params);
354 if (isObject(params)) {
355 return state + toJson(params);
360 // Update route state
362 for (var i = 0; i < states.length; i++) {
363 if (anyMatch(states[i].state, states[i].params)) {
364 addClass($element, activeClasses[states[i].hash]);
366 removeClass($element, activeClasses[states[i].hash]);
369 if (exactMatch(states[i].state, states[i].params)) {
370 addClass($element, activeEqClass);
372 removeClass($element, activeEqClass);
377 function addClass(el, className) { $timeout(function () { el.addClass(className); }); }
378 function removeClass(el, className) { el.removeClass(className); }
379 function anyMatch(state, params) { return $state.includes(state.name, params); }
380 function exactMatch(state, params) { return $state.is(state.name, params); }
387 angular.module('ui.router.state')
388 .directive('uiSref', $StateRefDirective)
389 .directive('uiSrefActive', $StateRefActiveDirective)
390 .directive('uiSrefActiveEq', $StateRefActiveDirective)
391 .directive('uiState', $StateRefDynamicDirective);