/** * State-based routing for AngularJS * @version v0.2.10 * @link http://angular-ui.github.com/ * @license MIT License, http://www.opensource.org/licenses/MIT */ /* commonjs package manager support (eg componentjs) */ if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){ module.exports = 'ui.router'; } (function (window, angular, undefined) { /*jshint globalstrict:true*/ /*global angular:false*/ 'use strict'; var isDefined = angular.isDefined, isFunction = angular.isFunction, isString = angular.isString, isObject = angular.isObject, isArray = angular.isArray, forEach = angular.forEach, extend = angular.extend, copy = angular.copy; function inherit(parent, extra) { return extend(new (extend(function() {}, { prototype: parent }))(), extra); } function merge(dst) { forEach(arguments, function(obj) { if (obj !== dst) { forEach(obj, function(value, key) { if (!dst.hasOwnProperty(key)) dst[key] = value; }); } }); return dst; } /** * Finds the common ancestor path between two states. * * @param {Object} first The first state. * @param {Object} second The second state. * @return {Array} Returns an array of state names in descending order, not including the root. */ function ancestors(first, second) { var path = []; for (var n in first.path) { if (first.path[n] !== second.path[n]) break; path.push(first.path[n]); } return path; } /** * IE8-safe wrapper for `Object.keys()`. * * @param {Object} object A JavaScript object. * @return {Array} Returns the keys of the object as an array. */ function keys(object) { if (Object.keys) { return Object.keys(object); } var result = []; angular.forEach(object, function(val, key) { result.push(key); }); return result; } /** * IE8-safe wrapper for `Array.prototype.indexOf()`. * * @param {Array} array A JavaScript array. * @param {*} value A value to search the array for. * @return {Number} Returns the array index value of `value`, or `-1` if not present. */ function arraySearch(array, value) { if (Array.prototype.indexOf) { return array.indexOf(value, Number(arguments[2]) || 0); } var len = array.length >>> 0, from = Number(arguments[2]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in array && array[from] === value) return from; } return -1; } /** * Merges a set of parameters with all parameters inherited between the common parents of the * current state and a given destination state. * * @param {Object} currentParams The value of the current state parameters ($stateParams). * @param {Object} newParams The set of parameters which will be composited with inherited params. * @param {Object} $current Internal definition of object representing the current state. * @param {Object} $to Internal definition of object representing state to transition to. */ function inheritParams(currentParams, newParams, $current, $to) { var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = []; for (var i in parents) { if (!parents[i].params || !parents[i].params.length) continue; parentParams = parents[i].params; for (var j in parentParams) { if (arraySearch(inheritList, parentParams[j]) >= 0) continue; inheritList.push(parentParams[j]); inherited[parentParams[j]] = currentParams[parentParams[j]]; } } return extend({}, inherited, newParams); } /** * Normalizes a set of values to string or `null`, filtering them by a list of keys. * * @param {Array} keys The list of keys to normalize/return. * @param {Object} values An object hash of values to normalize. * @return {Object} Returns an object hash of normalized string values. */ function normalize(keys, values) { var normalized = {}; forEach(keys, function (name) { var value = values[name]; normalized[name] = (value != null) ? String(value) : null; }); return normalized; } /** * Performs a non-strict comparison of the subset of two objects, defined by a list of keys. * * @param {Object} a The first object. * @param {Object} b The second object. * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified, * it defaults to the list of keys in `a`. * @return {Boolean} Returns `true` if the keys match, otherwise `false`. */ function equalForKeys(a, b, keys) { if (!keys) { keys = []; for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility } for (var i=0; i * * * * * * * * * * * * */ angular.module('ui.router', ['ui.router.state']); angular.module('ui.router.compat', ['ui.router']); /** * @ngdoc object * @name ui.router.util.$resolve * * @requires $q * @requires $injector * * @description * Manages resolution of (acyclic) graphs of promises. */ $Resolve.$inject = ['$q', '$injector']; function $Resolve( $q, $injector) { var VISIT_IN_PROGRESS = 1, VISIT_DONE = 2, NOTHING = {}, NO_DEPENDENCIES = [], NO_LOCALS = NOTHING, NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING }); /** * @ngdoc function * @name ui.router.util.$resolve#study * @methodOf ui.router.util.$resolve * * @description * Studies a set of invocables that are likely to be used multiple times. *
   * $resolve.study(invocables)(locals, parent, self)
   * 
* is equivalent to *
   * $resolve.resolve(invocables, locals, parent, self)
   * 
* but the former is more efficient (in fact `resolve` just calls `study` * internally). * * @param {object} invocables Invocable objects * @return {function} a function to pass in locals, parent and self */ this.study = function (invocables) { if (!isObject(invocables)) throw new Error("'invocables' must be an object"); // Perform a topological sort of invocables to build an ordered plan var plan = [], cycle = [], visited = {}; function visit(value, key) { if (visited[key] === VISIT_DONE) return; cycle.push(key); if (visited[key] === VISIT_IN_PROGRESS) { cycle.splice(0, cycle.indexOf(key)); throw new Error("Cyclic dependency: " + cycle.join(" -> ")); } visited[key] = VISIT_IN_PROGRESS; if (isString(value)) { plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES); } else { var params = $injector.annotate(value); forEach(params, function (param) { if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param); }); plan.push(key, value, params); } cycle.pop(); visited[key] = VISIT_DONE; } forEach(invocables, visit); invocables = cycle = visited = null; // plan is all that's required function isResolve(value) { return isObject(value) && value.then && value.$$promises; } return function (locals, parent, self) { if (isResolve(locals) && self === undefined) { self = parent; parent = locals; locals = null; } if (!locals) locals = NO_LOCALS; else if (!isObject(locals)) { throw new Error("'locals' must be an object"); } if (!parent) parent = NO_PARENT; else if (!isResolve(parent)) { throw new Error("'parent' must be a promise returned by $resolve.resolve()"); } // To complete the overall resolution, we have to wait for the parent // promise and for the promise for each invokable in our plan. var resolution = $q.defer(), result = resolution.promise, promises = result.$$promises = {}, values = extend({}, locals), wait = 1 + plan.length/3, merged = false; function done() { // Merge parent values we haven't got yet and publish our own $$values if (!--wait) { if (!merged) merge(values, parent.$$values); result.$$values = values; result.$$promises = true; // keep for isResolve() resolution.resolve(values); } } function fail(reason) { result.$$failure = reason; resolution.reject(reason); } // Short-circuit if parent has already failed if (isDefined(parent.$$failure)) { fail(parent.$$failure); return result; } // Merge parent values if the parent has already resolved, or merge // parent promises and wait if the parent resolve is still in progress. if (parent.$$values) { merged = merge(values, parent.$$values); done(); } else { extend(promises, parent.$$promises); parent.then(done, fail); } // Process each invocable in the plan, but ignore any where a local of the same name exists. for (var i=0, ii=plan.length; i} The template html as a string, or a promise * for that string. */ this.fromUrl = function (url, params) { if (isFunction(url)) url = url(params); if (url == null) return null; else return $http .get(url, { cache: $templateCache }) .then(function(response) { return response.data; }); }; /** * @ngdoc function * @name ui.router.util.$templateFactory#fromUrl * @methodOf ui.router.util.$templateFactory * * @description * Creates a template by invoking an injectable provider function. * * @param {Function} provider Function to invoke via `$injector.invoke` * @param {Object} params Parameters for the template. * @param {Object} locals Locals to pass to `invoke`. Defaults to * `{ params: params }`. * @return {string|Promise.} The template html as a string, or a promise * for that string. */ this.fromProvider = function (provider, params, locals) { return $injector.invoke(provider, null, locals || { params: params }); }; } angular.module('ui.router.util').service('$templateFactory', $TemplateFactory); /** * @ngdoc object * @name ui.router.util.type:UrlMatcher * * @description * Matches URLs against patterns and extracts named parameters from the path or the search * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list * of search parameters. Multiple search parameter names are separated by '&'. Search parameters * do not influence whether or not a URL is matched, but their values are passed through into * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}. * * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace * syntax, which optionally allows a regular expression for the parameter to be specified: * * * `':'` name - colon placeholder * * `'*'` name - catch-all placeholder * * `'{' name '}'` - curly placeholder * * `'{' name ':' regexp '}'` - curly placeholder with regexp. Should the regexp itself contain * curly braces, they must be in matched pairs or escaped with a backslash. * * Parameter names may contain only word characters (latin letters, digits, and underscore) and * must be unique within the pattern (across both path and search parameters). For colon * placeholders or curly placeholders without an explicit regexp, a path parameter matches any * number of characters other than '/'. For catch-all placeholders the path parameter matches * any number of characters. * * Examples: * * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for * trailing slashes, and patterns have to match the entire path, not just a prefix. * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or * '/user/bob/details'. The second path segment will be captured as the parameter 'id'. * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax. * * `'/user/{id:[^/]*}'` - Same as the previous example. * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id * parameter consists of 1 to 8 hex digits. * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the * path into the parameter 'path'. * * `'/files/*path'` - ditto. * * @param {string} pattern the pattern to compile into a matcher. * * @property {string} prefix A static prefix of this pattern. The matcher guarantees that any * URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns * non-null) will start with this prefix. * * @property {string} source The pattern that was passed into the contructor * * @property {string} sourcePath The path portion of the source property * * @property {string} sourceSearch The search portion of the source property * * @property {string} regex The constructed regex that will be used to match against the url when * it is time to determine which url will match. * * @returns {Object} New UrlMatcher object */ function UrlMatcher(pattern) { // Find all placeholders and create a compiled pattern, using either classic or curly syntax: // '*' name // ':' name // '{' name '}' // '{' name ':' regexp '}' // The regular expression is somewhat complicated due to the need to allow curly braces // inside the regular expression. The placeholder regexp breaks down as follows: // ([:*])(\w+) classic placeholder ($1 / $2) // \{(\w+)(?:\:( ... ))?\} curly brace placeholder ($3) with optional regexp ... ($4) // (?: ... | ... | ... )+ the regexp consists of any number of atoms, an atom being either // [^{}\\]+ - anything other than curly braces or backslash // \\. - a backslash escape // \{(?:[^{}\\]+|\\.)*\} - a matched set of curly braces containing other atoms var placeholder = /([:*])(\w+)|\{(\w+)(?:\:((?:[^{}\\]+|\\.|\{(?:[^{}\\]+|\\.)*\})+))?\}/g, names = {}, compiled = '^', last = 0, m, segments = this.segments = [], params = this.params = []; function addParameter(id) { if (!/^\w+(-+\w+)*$/.test(id)) throw new Error("Invalid parameter name '" + id + "' in pattern '" + pattern + "'"); if (names[id]) throw new Error("Duplicate parameter name '" + id + "' in pattern '" + pattern + "'"); names[id] = true; params.push(id); } function quoteRegExp(string) { return string.replace(/[\\\[\]\^$*+?.()|{}]/g, "\\$&"); } this.source = pattern; // Split into static segments separated by path parameter placeholders. // The number of segments is always 1 more than the number of parameters. var id, regexp, segment; while ((m = placeholder.exec(pattern))) { id = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null regexp = m[4] || (m[1] == '*' ? '.*' : '[^/]*'); segment = pattern.substring(last, m.index); if (segment.indexOf('?') >= 0) break; // we're into the search part compiled += quoteRegExp(segment) + '(' + regexp + ')'; addParameter(id); segments.push(segment); last = placeholder.lastIndex; } segment = pattern.substring(last); // Find any search parameter names and remove them from the last segment var i = segment.indexOf('?'); if (i >= 0) { var search = this.sourceSearch = segment.substring(i); segment = segment.substring(0, i); this.sourcePath = pattern.substring(0, last+i); // Allow parameters to be separated by '?' as well as '&' to make concat() easier forEach(search.substring(1).split(/[&?]/), addParameter); } else { this.sourcePath = pattern; this.sourceSearch = ''; } compiled += quoteRegExp(segment) + '$'; segments.push(segment); this.regexp = new RegExp(compiled); this.prefix = segments[0]; } /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#concat * @methodOf ui.router.util.type:UrlMatcher * * @description * Returns a new matcher for a pattern constructed by appending the path part and adding the * search parameters of the specified pattern to this pattern. The current pattern is not * modified. This can be understood as creating a pattern for URLs that are relative to (or * suffixes of) the current pattern. * * @example * The following two matchers are equivalent: * ``` * new UrlMatcher('/user/{id}?q').concat('/details?date'); * new UrlMatcher('/user/{id}/details?q&date'); * ``` * * @param {string} pattern The pattern to append. * @returns {ui.router.util.type:UrlMatcher} A matcher for the concatenated pattern. */ UrlMatcher.prototype.concat = function (pattern) { // Because order of search parameters is irrelevant, we can add our own search // parameters to the end of the new pattern. Parse the new pattern by itself // and then join the bits together, but it's much easier to do this on a string level. return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch); }; UrlMatcher.prototype.toString = function () { return this.source; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#exec * @methodOf ui.router.util.type:UrlMatcher * * @description * Tests the specified path against this matcher, and returns an object containing the captured * parameter values, or null if the path does not match. The returned object contains the values * of any search parameters that are mentioned in the pattern, but their value may be null if * they are not present in `searchParams`. This means that search parameters are always treated * as optional. * * @example * ``` * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', { x:'1', q:'hello' }); * // returns { id:'bob', q:'hello', r:null } * ``` * * @param {string} path The URL path to match, e.g. `$location.path()`. * @param {Object} searchParams URL search parameters, e.g. `$location.search()`. * @returns {Object} The captured parameter values. */ UrlMatcher.prototype.exec = function (path, searchParams) { var m = this.regexp.exec(path); if (!m) return null; var params = this.params, nTotal = params.length, nPath = this.segments.length-1, values = {}, i; if (nPath !== m.length - 1) throw new Error("Unbalanced capture group in route '" + this.source + "'"); for (i=0; i} An array of parameter names. Must be treated as read-only. If the * pattern has no parameters, an empty array is returned. */ UrlMatcher.prototype.parameters = function () { return this.params; }; /** * @ngdoc function * @name ui.router.util.type:UrlMatcher#format * @methodOf ui.router.util.type:UrlMatcher * * @description * Creates a URL that matches this pattern by substituting the specified values * for the path and search parameters. Null values for path parameters are * treated as empty strings. * * @example * ``` * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' }); * // returns '/user/bob?q=yes' * ``` * * @param {Object} values the values to substitute for the parameters in this pattern. * @returns {string} the formatted URL (path and optionally search part). */ UrlMatcher.prototype.format = function (values) { var segments = this.segments, params = this.params; if (!values) return segments.join(''); var nPath = segments.length-1, nTotal = params.length, result = segments[0], i, search, value; for (i=0; i * var app = angular.module('app', ['ui.router.router']); * * app.config(function ($urlRouterProvider) { * // Here's an example of how you might allow case insensitive urls * $urlRouterProvider.rule(function ($injector, $location) { * var path = $location.path(), * normalized = path.toLowerCase(); * * if (path !== normalized) { * return normalized; * } * }); * }); * * * @param {object} rule Handler function that takes `$injector` and `$location` * services as arguments. You can use them to return a valid path as a string. * * @return {object} $urlRouterProvider - $urlRouterProvider instance */ this.rule = function (rule) { if (!isFunction(rule)) throw new Error("'rule' must be a function"); rules.push(rule); return this; }; /** * @ngdoc object * @name ui.router.router.$urlRouterProvider#otherwise * @methodOf ui.router.router.$urlRouterProvider * * @description * Defines a path that is used when an invalied route is requested. * * @example *
   * var app = angular.module('app', ['ui.router.router']);
   *
   * app.config(function ($urlRouterProvider) {
   *   // if the path doesn't match any of the urls you configured
   *   // otherwise will take care of routing the user to the
   *   // specified url
   *   $urlRouterProvider.otherwise('/index');
   *
   *   // Example of using function rule as param
   *   $urlRouterProvider.otherwise(function ($injector, $location) {
   *     ...
   *   });
   * });
   * 
* * @param {string|object} rule The url path you want to redirect to or a function * rule that returns the url path. The function version is passed two params: * `$injector` and `$location` services. * * @return {object} $urlRouterProvider - $urlRouterProvider instance */ this.otherwise = function (rule) { if (isString(rule)) { var redirect = rule; rule = function () { return redirect; }; } else if (!isFunction(rule)) throw new Error("'rule' must be a function"); otherwise = rule; return this; }; function handleIfMatch($injector, handler, match) { if (!match) return false; var result = $injector.invoke(handler, handler, { $match: match }); return isDefined(result) ? result : true; } /** * @ngdoc function * @name ui.router.router.$urlRouterProvider#when * @methodOf ui.router.router.$urlRouterProvider * * @description * Registers a handler for a given url matching. if handle is a string, it is * treated as a redirect, and is interpolated according to the syyntax of match * (i.e. like String.replace() for RegExp, or like a UrlMatcher pattern otherwise). * * If the handler is a function, it is injectable. It gets invoked if `$location` * matches. You have the option of inject the match object as `$match`. * * The handler can return * * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter` * will continue trying to find another one that matches. * - **string** which is treated as a redirect and passed to `$location.url()` * - **void** or any **truthy** value tells `$urlRouter` that the url was handled. * * @example *
   * var app = angular.module('app', ['ui.router.router']);
   *
   * app.config(function ($urlRouterProvider) {
   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {
   *     if ($state.$current.navigable !== state ||
   *         !equalForKeys($match, $stateParams) {
   *      $state.transitionTo(state, $match, false);
   *     }
   *   });
   * });
   * 
* * @param {string|object} what The incoming path that you want to redirect. * @param {string|object} handler The path you want to redirect your user to. */ this.when = function (what, handler) { var redirect, handlerIsString = isString(handler); if (isString(what)) what = $urlMatcherFactory.compile(what); if (!handlerIsString && !isFunction(handler) && !isArray(handler)) throw new Error("invalid 'handler' in when()"); var strategies = { matcher: function (what, handler) { if (handlerIsString) { redirect = $urlMatcherFactory.compile(handler); handler = ['$match', function ($match) { return redirect.format($match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path(), $location.search())); }, { prefix: isString(what.prefix) ? what.prefix : '' }); }, regex: function (what, handler) { if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky"); if (handlerIsString) { redirect = handler; handler = ['$match', function ($match) { return interpolate(redirect, $match); }]; } return extend(function ($injector, $location) { return handleIfMatch($injector, handler, what.exec($location.path())); }, { prefix: regExpPrefix(what) }); } }; var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp }; for (var n in check) { if (check[n]) { return this.rule(strategies[n](what, handler)); } } throw new Error("invalid 'what' in when()"); }; /** * @ngdoc object * @name ui.router.router.$urlRouter * * @requires $location * @requires $rootScope * @requires $injector * * @description * */ this.$get = [ '$location', '$rootScope', '$injector', function ($location, $rootScope, $injector) { // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree function update(evt) { if (evt && evt.defaultPrevented) return; function check(rule) { var handled = rule($injector, $location); if (handled) { if (isString(handled)) $location.replace().url(handled); return true; } return false; } var n=rules.length, i; for (i=0; i * angular.module('app', ['ui.router']); * .run(function($rootScope, $urlRouter) { * $rootScope.$on('$locationChangeSuccess', function(evt) { * // Halt state change from even starting * evt.preventDefault(); * // Perform custom logic * var meetsRequirement = ... * // Continue with the update and state transition if logic allows * if (meetsRequirement) $urlRouter.sync(); * }); * }); * */ sync: function () { update(); } }; }]; } angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider); /** * @ngdoc object * @name ui.router.state.$stateProvider * * @requires ui.router.router.$urlRouterProvider * @requires ui.router.util.$urlMatcherFactoryProvider * @requires $locationProvider * * @description * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely * on state. * * A state corresponds to a "place" in the application in terms of the overall UI and * navigation. A state describes (via the controller / template / view properties) what * the UI looks like and does at that place. * * States often have things in common, and the primary way of factoring out these * commonalities in this model is via the state hierarchy, i.e. parent/child states aka * nested states. * * The `$stateProvider` provides interfaces to declare these states for your app. */ $StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider']; function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $locationProvider) { var root, states = {}, $state, queue = {}, abstractKey = 'abstract'; // Builds state properties from definition passed to registerState() var stateBuilder = { // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined. // state.children = []; // if (parent) parent.children.push(state); parent: function(state) { if (isDefined(state.parent) && state.parent) return findState(state.parent); // regex matches any valid composite state name // would match "contact.list" but not "contacts" var compositeName = /^(.+)\.[^.]+$/.exec(state.name); return compositeName ? findState(compositeName[1]) : root; }, // inherit 'data' from parent and override by own values (if any) data: function(state) { if (state.parent && state.parent.data) { state.data = state.self.data = extend({}, state.parent.data, state.data); } return state.data; }, // Build a URLMatcher if necessary, either via a relative or absolute URL url: function(state) { var url = state.url; if (isString(url)) { if (url.charAt(0) == '^') { return $urlMatcherFactory.compile(url.substring(1)); } return (state.parent.navigable || root).url.concat(url); } if ($urlMatcherFactory.isMatcher(url) || url == null) { return url; } throw new Error("Invalid url '" + url + "' in state '" + state + "'"); }, // Keep track of the closest ancestor state that has a URL (i.e. is navigable) navigable: function(state) { return state.url ? state : (state.parent ? state.parent.navigable : null); }, // Derive parameters for this state and ensure they're a super-set of parent's parameters params: function(state) { if (!state.params) { return state.url ? state.url.parameters() : state.parent.params; } if (!isArray(state.params)) throw new Error("Invalid params in state '" + state + "'"); if (state.url) throw new Error("Both params and url specicified in state '" + state + "'"); return state.params; }, // If there is no explicit multi-view configuration, make one up so we don't have // to handle both cases in the view directive later. Note that having an explicit // 'views' property will mean the default unnamed view properties are ignored. This // is also a good time to resolve view names to absolute names, so everything is a // straight lookup at link time. views: function(state) { var views = {}; forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) { if (name.indexOf('@') < 0) name += '@' + state.parent.name; views[name] = view; }); return views; }, ownParams: function(state) { if (!state.parent) { return state.params; } var paramNames = {}; forEach(state.params, function (p) { paramNames[p] = true; }); forEach(state.parent.params, function (p) { if (!paramNames[p]) { throw new Error("Missing required parameter '" + p + "' in state '" + state.name + "'"); } paramNames[p] = false; }); var ownParams = []; forEach(paramNames, function (own, p) { if (own) ownParams.push(p); }); return ownParams; }, // Keep a full path from the root down to this state as this is needed for state activation. path: function(state) { return state.parent ? state.parent.path.concat(state) : []; // exclude root from path }, // Speed up $state.contains() as it's used a lot includes: function(state) { var includes = state.parent ? extend({}, state.parent.includes) : {}; includes[state.name] = true; return includes; }, $delegates: {} }; function isRelative(stateName) { return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0; } function findState(stateOrName, base) { var isStr = isString(stateOrName), name = isStr ? stateOrName : stateOrName.name, path = isRelative(name); if (path) { if (!base) throw new Error("No reference point given for path '" + name + "'"); var rel = name.split("."), i = 0, pathLength = rel.length, current = base; for (; i < pathLength; i++) { if (rel[i] === "" && i === 0) { current = base; continue; } if (rel[i] === "^") { if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'"); current = current.parent; continue; } break; } rel = rel.slice(i).join("."); name = current.name + (current.name && rel ? "." : "") + rel; } var state = states[name]; if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) { return state; } return undefined; } function queueState(parentName, state) { if (!queue[parentName]) { queue[parentName] = []; } queue[parentName].push(state); } function registerState(state) { // Wrap a new object around the state so we can store our private details easily. state = inherit(state, { self: state, resolve: state.resolve || {}, toString: function() { return this.name; } }); var name = state.name; if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name"); if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined"); // Get parent name var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.')) : (isString(state.parent)) ? state.parent : ''; // If parent is not registered yet, add state to queue and register later if (parentName && !states[parentName]) { return queueState(parentName, state.self); } for (var key in stateBuilder) { if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]); } states[name] = state; // Register the state in the global state list and with $urlRouter if necessary. if (!state[abstractKey] && state.url) { $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) { if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) { $state.transitionTo(state, $match, { location: false }); } }]); } // Register any queued children if (queue[name]) { for (var i = 0; i < queue[name].length; i++) { registerState(queue[name][i]); } } return state; } // Checks text to see if it looks like a glob. function isGlob (text) { return text.indexOf('*') > -1; } // Returns true if glob matches current $state name. function doesStateMatchGlob (glob) { var globSegments = glob.split('.'), segments = $state.$current.name.split('.'); //match greedy starts if (globSegments[0] === '**') { segments = segments.slice(segments.indexOf(globSegments[1])); segments.unshift('**'); } //match greedy ends if (globSegments[globSegments.length - 1] === '**') { segments.splice(segments.indexOf(globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE); segments.push('**'); } if (globSegments.length != segments.length) { return false; } //match single stars for (var i = 0, l = globSegments.length; i < l; i++) { if (globSegments[i] === '*') { segments[i] = '*'; } } return segments.join('') === globSegments.join(''); } // Implicit root state that is always active root = registerState({ name: '', url: '^', views: null, 'abstract': true }); root.navigable = null; /** * @ngdoc function * @name ui.router.state.$stateProvider#decorator * @methodOf ui.router.state.$stateProvider * * @description * Allows you to extend (carefully) or override (at your own peril) the * `stateBuilder` object used internally by `$stateProvider`. This can be used * to add custom functionality to ui-router, for example inferring templateUrl * based on the state name. * * When passing only a name, it returns the current (original or decorated) builder * function that matches `name`. * * The builder functions that can be decorated are listed below. Though not all * necessarily have a good use case for decoration, that is up to you to decide. * * In addition, users can attach custom decorators, which will generate new * properties within the state's internal definition. There is currently no clear * use-case for this beyond accessing internal states (i.e. $state.$current), * however, expect this to become increasingly relevant as we introduce additional * meta-programming features. * * **Warning**: Decorators should not be interdependent because the order of * execution of the builder functions in non-deterministic. Builder functions * should only be dependent on the state definition object and super function. * * * Existing builder functions and current return values: * * - **parent** `{object}` - returns the parent state object. * - **data** `{object}` - returns state data, including any inherited data that is not * overridden by own values (if any). * - **url** `{object}` - returns a {link ui.router.util.type:UrlMatcher} or null. * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is * navigable). * - **params** `{object}` - returns an array of state params that are ensured to * be a super-set of parent's params. * - **views** `{object}` - returns a views object where each key is an absolute view * name (i.e. "viewName@stateName") and each value is the config object * (template, controller) for the view. Even when you don't use the views object * explicitly on a state config, one is still created for you internally. * So by decorating this builder function you have access to decorating template * and controller properties. * - **ownParams** `{object}` - returns an array of params that belong to the state, * not including any params defined by ancestor states. * - **path** `{string}` - returns the full path from the root down to this state. * Needed for state activation. * - **includes** `{object}` - returns an object that includes every state that * would pass a '$state.includes()' test. * * @example *
   * // Override the internal 'views' builder with a function that takes the state
   * // definition, and a reference to the internal function being overridden:
   * $stateProvider.decorator('views', function ($state, parent) {
   *   var result = {},
   *       views = parent(state);
   *
   *   angular.forEach(view, function (config, name) {
   *     var autoName = (state.name + '.' + name).replace('.', '/');
   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
   *     result[name] = config;
   *   });
   *   return result;
   * });
   *
   * $stateProvider.state('home', {
   *   views: {
   *     'contact.list': { controller: 'ListController' },
   *     'contact.item': { controller: 'ItemController' }
   *   }
   * });
   *
   * // ...
   *
   * $state.go('home');
   * // Auto-populates list and item views with /partials/home/contact/list.html,
   * // and /partials/home/contact/item.html, respectively.
   * 
* * @param {string} name The name of the builder function to decorate. * @param {object} func A function that is responsible for decorating the original * builder function. The function receives two parameters: * * - `{object}` - state - The state config object. * - `{object}` - super - The original builder function. * * @return {object} $stateProvider - $stateProvider instance */ this.decorator = decorator; function decorator(name, func) { /*jshint validthis: true */ if (isString(name) && !isDefined(func)) { return stateBuilder[name]; } if (!isFunction(func) || !isString(name)) { return this; } if (stateBuilder[name] && !stateBuilder.$delegates[name]) { stateBuilder.$delegates[name] = stateBuilder[name]; } stateBuilder[name] = func; return this; } /** * @ngdoc function * @name ui.router.state.$stateProvider#state * @methodOf ui.router.state.$stateProvider * * @description * Registers a state configuration under a given state name. The stateConfig object * has the following acceptable properties. * * * * - **`template`** - {string|function=} - html template as a string or a function that returns * an html template as a string which should be used by the uiView directives. This property * takes precedence over templateUrl. * * If `template` is a function, it will be called with the following parameters: * * - {array.<object>} - state parameters extracted from the current $location.path() by * applying the current state * * * * - **`templateUrl`** - {string|function=} - path or function that returns a path to an html * template that should be used by uiView. * * If `templateUrl` is a function, it will be called with the following parameters: * * - {array.<object>} - state parameters extracted from the current $location.path() by * applying the current state * * * * - **`templateProvider`** - {function=} - Provider function that returns HTML content * string. * * * * - **`controller`** - {string|function=} - Controller fn that should be associated with newly * related scope or the name of a registered controller if passed as a string. * * * * - **`controllerProvider`** - {function=} - Injectable provider function that returns * the actual controller or string. * * * * - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be * published to scope under the controllerAs name. * * * * - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which * should be injected into the controller. If any of these dependencies are promises, * the router will wait for them all to be resolved or one to be rejected before the * controller is instantiated. If all the promises are resolved successfully, the values * of the resolved promises are injected and $stateChangeSuccess event is fired. If any * of the promises are rejected the $stateChangeError event is fired. The map object is: * * - key - {string}: name of dependency to be injected into controller * - factory - {string|function}: If string then it is alias for service. Otherwise if function, * it is injected and return value it treated as dependency. If result is a promise, it is * resolved before its value is injected into controller. * * * * - **`url`** - {string=} - A url with optional parameters. When a state is navigated or * transitioned to, the `$stateParams` service will be populated with any * parameters that were passed. * * * * - **`params`** - {object=} - An array of parameter names or regular expressions. Only * use this within a state if you are not using url. Otherwise you can specify your * parameters within the url. When a state is navigated or transitioned to, the * $stateParams service will be populated with any parameters that were passed. * * * * - **`views`** - {object=} - Use the views property to set up multiple views or to target views * manually/explicitly. * * * * - **`abstract`** - {boolean=} - An abstract state will never be directly activated, * but can provide inherited properties to its common children states. * * * * - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way * to trigger an action or dispatch an event, such as opening a dialog. * * * * - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to * trigger an action or dispatch an event, such as opening a dialog. * * * * - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state * just because a search/query parameter has changed (via $location.search() or $location.hash()). * Useful for when you'd like to modify $location.search() without triggering a reload. * * * * - **`data`** - {object=} - Arbitrary data object, useful for custom configuration. * * @example *
   * // Some state name examples
   *
   * // stateName can be a single top-level name (must be unique).
   * $stateProvider.state("home", {});
   *
   * // Or it can be a nested state name. This state is a child of the 
   * // above "home" state.
   * $stateProvider.state("home.newest", {});
   *
   * // Nest states as deeply as needed.
   * $stateProvider.state("home.newest.abc.xyz.inception", {});
   *
   * // state() returns $stateProvider, so you can chain state declarations.
   * $stateProvider
   *   .state("home", {})
   *   .state("about", {})
   *   .state("contacts", {});
   * 
* * @param {string} name A unique state name, e.g. "home", "about", "contacts". * To create a parent/child state use a dot, e.g. "about.sales", "home.newest". * @param {object} definition State configuration object. */ this.state = state; function state(name, definition) { /*jshint validthis: true */ if (isObject(name)) definition = name; else definition.name = name; registerState(definition); return this; } /** * @ngdoc object * @name ui.router.state.$state * * @requires $rootScope * @requires $q * @requires ui.router.state.$view * @requires $injector * @requires ui.router.util.$resolve * @requires ui.router.state.$stateParams * * @property {object} params A param object, e.g. {sectionId: section.id)}, that * you'd like to test against the current active state. * @property {object} current A reference to the state's config object. However * you passed it in. Useful for accessing custom data. * @property {object} transition Currently pending transition. A promise that'll * resolve or reject. * * @description * `$state` service is responsible for representing states as well as transitioning * between them. It also provides interfaces to ask for current state or even states * you're coming from. */ // $urlRouter is injected just to ensure it gets instantiated this.$get = $get; $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$location', '$urlRouter', '$browser']; function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $location, $urlRouter, $browser) { var TransitionSuperseded = $q.reject(new Error('transition superseded')); var TransitionPrevented = $q.reject(new Error('transition prevented')); var TransitionAborted = $q.reject(new Error('transition aborted')); var TransitionFailed = $q.reject(new Error('transition failed')); var currentLocation = $location.url(); var baseHref = $browser.baseHref(); function syncUrl() { if ($location.url() !== currentLocation) { $location.url(currentLocation); $location.replace(); } } root.locals = { resolve: null, globals: { $stateParams: {} } }; $state = { params: {}, current: root.self, $current: root, transition: null }; /** * @ngdoc function * @name ui.router.state.$state#reload * @methodOf ui.router.state.$state * * @description * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon). * * @example *
     * var app angular.module('app', ['ui.router']);
     *
     * app.controller('ctrl', function ($scope, $state) {
     *   $scope.reload = function(){
     *     $state.reload();
     *   }
     * });
     * 
* * `reload()` is just an alias for: *
     * $state.transitionTo($state.current, $stateParams, { 
     *   reload: true, inherit: false, notify: false 
     * });
     * 
*/ $state.reload = function reload() { $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: false }); }; /** * @ngdoc function * @name ui.router.state.$state#go * @methodOf ui.router.state.$state * * @description * Convenience method for transitioning to a new state. `$state.go` calls * `$state.transitionTo` internally but automatically sets options to * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. * This allows you to easily use an absolute or relative to path and specify * only the parameters you'd like to update (while letting unspecified parameters * inherit from the currently active ancestor states). * * @example *
     * var app = angular.module('app', ['ui.router']);
     *
     * app.controller('ctrl', function ($scope, $state) {
     *   $scope.changeState = function () {
     *     $state.go('contact.detail');
     *   };
     * });
     * 
* * * @param {string} to Absolute state name or relative state path. Some examples: * * - `$state.go('contact.detail')` - will go to the `contact.detail` state * - `$state.go('^')` - will go to a parent state * - `$state.go('^.sibling')` - will go to a sibling state * - `$state.go('.child.grandchild')` - will go to grandchild state * * @param {object=} params A map of the parameters that will be sent to the state, * will populate $stateParams. Any parameters that are not specified will be inherited from currently * defined parameters. This allows, for example, going to a sibling state that shares parameters * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e. * transitioning to a sibling will get you the parameters for all parents, transitioning to a child * will get you all current parameters, etc. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd * use this when you want to force a reload when *everything* is the same, including search params. * * @returns {promise} A promise representing the state of the new transition. * * Possible success values: * * - $state.current * *
Possible rejection values: * * - 'transition superseded' - when a newer transition has been started after this one * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or * when a `$stateNotFound` `event.retry` promise errors. * - 'transition failed' - when a state has been unsuccessfully found after 2 tries. * - *resolve error* - when an error has occurred with a `resolve` * */ $state.go = function go(to, params, options) { return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options)); }; /** * @ngdoc function * @name ui.router.state.$state#transitionTo * @methodOf ui.router.state.$state * * @description * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go} * uses `transitionTo` internally. `$state.go` is recommended in most situations. * * @example *
     * var app = angular.module('app', ['ui.router']);
     *
     * app.controller('ctrl', function ($scope, $state) {
     *   $scope.changeState = function () {
     *     $state.transitionTo('contact.detail');
     *   };
     * });
     * 
* * @param {string} to State name. * @param {object=} toParams A map of the parameters that will be sent to the state, * will populate $stateParams. * @param {object=} options Options object. The options are: * * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false` * will not. If string, must be `"replace"`, which will update url and also replace last history record. * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events. * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params * have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd * use this when you want to force a reload when *everything* is the same, including search params. * * @returns {promise} A promise representing the state of the new transition. See * {@link ui.router.state.$state#methods_go $state.go}. */ $state.transitionTo = function transitionTo(to, toParams, options) { toParams = toParams || {}; options = extend({ location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false }, options || {}); var from = $state.$current, fromParams = $state.params, fromPath = from.path; var evt, toState = findState(to, options.relative); if (!isDefined(toState)) { // Broadcast not found event and abort the transition if prevented var redirect = { to: to, toParams: toParams, options: options }; /** * @ngdoc event * @name ui.router.state.$state#$stateNotFound * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when a requested state **cannot be found** using the provided state name during transition. * The event is broadcast allowing any handlers a single chance to deal with the error (usually by * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler, * you can see its three properties in the example. You can use `event.preventDefault()` to abort the * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value. * * @param {Object} event Event object. * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties. * @param {State} fromState Current state object. * @param {Object} fromParams Current state params. * * @example * *
         * // somewhere, assume lazy.state has not been defined
         * $state.go("lazy.state", {a:1, b:2}, {inherit:false});
         *
         * // somewhere else
         * $scope.$on('$stateNotFound',
         * function(event, unfoundState, fromState, fromParams){
         *     console.log(unfoundState.to); // "lazy.state"
         *     console.log(unfoundState.toParams); // {a:1, b:2}
         *     console.log(unfoundState.options); // {inherit:false} + default options
         * })
         * 
*/ evt = $rootScope.$broadcast('$stateNotFound', redirect, from.self, fromParams); if (evt.defaultPrevented) { syncUrl(); return TransitionAborted; } // Allow the handler to return a promise to defer state lookup retry if (evt.retry) { if (options.$retry) { syncUrl(); return TransitionFailed; } var retryTransition = $state.transition = $q.when(evt.retry); retryTransition.then(function() { if (retryTransition !== $state.transition) return TransitionSuperseded; redirect.options.$retry = true; return $state.transitionTo(redirect.to, redirect.toParams, redirect.options); }, function() { return TransitionAborted; }); syncUrl(); return retryTransition; } // Always retry once if the $stateNotFound was not prevented // (handles either redirect changed or state lazy-definition) to = redirect.to; toParams = redirect.toParams; options = redirect.options; toState = findState(to, options.relative); if (!isDefined(toState)) { if (options.relative) throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'"); throw new Error("No such state '" + to + "'"); } } if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'"); if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState); to = toState; var toPath = to.path; // Starting from the root of the path, keep all levels that haven't changed var keep, state, locals = root.locals, toLocals = []; for (keep = 0, state = toPath[keep]; state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams) && !options.reload; keep++, state = toPath[keep]) { locals = toLocals[keep] = state.locals; } // If we're going to the same state and all locals are kept, we've got nothing to do. // But clear 'transition', as we still want to cancel any other pending transitions. // TODO: We may not want to bump 'transition' if we're called from a location change that we've initiated ourselves, // because we might accidentally abort a legitimate transition initiated from code? if (shouldTriggerReload(to, from, locals, options) ) { if ( to.self.reloadOnSearch !== false ) syncUrl(); $state.transition = null; return $q.when($state.current); } // Normalize/filter parameters before we pass them to event handlers etc. toParams = normalize(to.params, toParams || {}); // Broadcast start event and cancel the transition if requested if (options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$stateChangeStart * @eventOf ui.router.state.$state * @eventType broadcast on root scope * @description * Fired when the state transition **begins**. You can use `event.preventDefault()` * to prevent the transition from happening and then the transition promise will be * rejected with a `'transition prevented'` value. * * @param {Object} event Event object. * @param {State} toState The state being transitioned to. * @param {Object} toParams The params supplied to the `toState`. * @param {State} fromState The current state, pre-transition. * @param {Object} fromParams The params supplied to the `fromState`. * * @example * *
         * $rootScope.$on('$stateChangeStart',
         * function(event, toState, toParams, fromState, fromParams){
         *     event.preventDefault();
         *     // transitionTo() promise will be rejected with
         *     // a 'transition prevented' error
         * })
         * 
*/ evt = $rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams); if (evt.defaultPrevented) { syncUrl(); return TransitionPrevented; } } // Resolve locals for the remaining states, but don't update any global state just // yet -- if anything fails to resolve the current state needs to remain untouched. // We also set up an inheritance chain for the locals here. This allows the view directive // to quickly look up the correct definition for each view in the current state. Even // though we create the locals object itself outside resolveState(), it is initially // empty and gets filled asynchronously. We need to keep track of the promise for the // (fully resolved) current locals, and pass this down the chain. var resolved = $q.when(locals); for (var l=keep; l=keep; l--) { exiting = fromPath[l]; if (exiting.self.onExit) { $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals); } exiting.locals = null; } // Enter 'to' states not kept for (l=keep; l * $state.is('contact.details.item'); // returns true * $state.is(contactDetailItemStateObject); // returns true * * // everything else would return false * * * @param {string|object} stateName The state name or state object you'd like to check. * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like * to test against the current active state. * @returns {boolean} Returns true if it is the state. */ $state.is = function is(stateOrName, params) { var state = findState(stateOrName); if (!isDefined(state)) { return undefined; } if ($state.$current !== state) { return false; } return isDefined(params) && params !== null ? angular.equals($stateParams, params) : true; }; /** * @ngdoc function * @name ui.router.state.$state#includes * @methodOf ui.router.state.$state * * @description * A method to determine if the current active state is equal to or is the child of the * state stateName. If any params are passed then they will be tested for a match as well. * Not all the parameters need to be passed, just the ones you'd like to test for equality. * * @example *
     * $state.$current.name = 'contacts.details.item';
     *
     * $state.includes("contacts"); // returns true
     * $state.includes("contacts.details"); // returns true
     * $state.includes("contacts.details.item"); // returns true
     * $state.includes("contacts.list"); // returns false
     * $state.includes("about"); // returns false
     * 
* * @description * Basic globing patterns will also work. * * @example *
     * $state.$current.name = 'contacts.details.item.url';
     *
     * $state.includes("*.details.*.*"); // returns true
     * $state.includes("*.details.**"); // returns true
     * $state.includes("**.item.**"); // returns true
     * $state.includes("*.details.item.url"); // returns true
     * $state.includes("*.details.*.url"); // returns true
     * $state.includes("*.details.*"); // returns false
     * $state.includes("item.**"); // returns false
     * 
* * @param {string} stateOrName A partial name to be searched for within the current state name. * @param {object} params A param object, e.g. `{sectionId: section.id}`, * that you'd like to test against the current active state. * @returns {boolean} Returns true if it does include the state */ $state.includes = function includes(stateOrName, params) { if (isString(stateOrName) && isGlob(stateOrName)) { if (doesStateMatchGlob(stateOrName)) { stateOrName = $state.$current.name; } else { return false; } } var state = findState(stateOrName); if (!isDefined(state)) { return undefined; } if (!isDefined($state.$current.includes[state.name])) { return false; } var validParams = true; angular.forEach(params, function(value, key) { if (!isDefined($stateParams[key]) || $stateParams[key] !== value) { validParams = false; } }); return validParams; }; /** * @ngdoc function * @name ui.router.state.$state#href * @methodOf ui.router.state.$state * * @description * A url generation method that returns the compiled url for the given state populated with the given params. * * @example *
     * expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
     * 
* * @param {string|object} stateOrName The state name or state object you'd like to generate a url from. * @param {object=} params An object of parameter values to fill the state's required parameters. * @param {object=} options Options object. The options are: * * - **`lossy`** - {boolean=true} - If true, and if there is no url associated with the state provided in the * first parameter, then the constructed href url will be built from the first navigable ancestor (aka * ancestor with a valid url). * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url. * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), * defines which state to be relative from. * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl". * * @returns {string} compiled state url */ $state.href = function href(stateOrName, params, options) { options = extend({ lossy: true, inherit: false, absolute: false, relative: $state.$current }, options || {}); var state = findState(stateOrName, options.relative); if (!isDefined(state)) return null; params = inheritParams($stateParams, params || {}, $state.$current, state); var nav = (state && options.lossy) ? state.navigable : state; var url = (nav && nav.url) ? nav.url.format(normalize(state.params, params || {})) : null; if (!$locationProvider.html5Mode() && url) { url = "#" + $locationProvider.hashPrefix() + url; } if (baseHref !== '/') { if ($locationProvider.html5Mode()) { url = baseHref.slice(0, -1) + url; } else if (options.absolute){ url = baseHref.slice(1) + url; } } if (options.absolute && url) { url = $location.protocol() + '://' + $location.host() + ($location.port() == 80 || $location.port() == 443 ? '' : ':' + $location.port()) + (!$locationProvider.html5Mode() && url ? '/' : '') + url; } return url; }; /** * @ngdoc function * @name ui.router.state.$state#get * @methodOf ui.router.state.$state * * @description * Returns the state configuration object for any specific state or all states. * * @param {string|object=} stateOrName If provided, will only get the config for * the requested state. If not provided, returns an array of ALL state configs. * @returns {object|array} State configuration object or array of all objects. */ $state.get = function (stateOrName, context) { if (!isDefined(stateOrName)) { var list = []; forEach(states, function(state) { list.push(state.self); }); return list; } var state = findState(stateOrName, context); return (state && state.self) ? state.self : null; }; function resolveState(state, params, paramsAreFiltered, inherited, dst) { // Make a restricted $stateParams with only the parameters that apply to this state if // necessary. In addition to being available to the controller and onEnter/onExit callbacks, // we also need $stateParams to be available for any $injector calls we make during the // dependency resolution process. var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params, params); var locals = { $stateParams: $stateParams }; // Resolve 'global' dependencies for the state, i.e. those not specific to a view. // We're also including $stateParams in this; that way the parameters are restricted // to the set that should be visible to the state, and are independent of when we update // the global $state and $stateParams values. dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state); var promises = [ dst.resolve.then(function (globals) { dst.globals = globals; }) ]; if (inherited) promises.push(inherited); // Resolve template and dependencies for all views. forEach(state.views, function (view, name) { var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {}); injectables.$template = [ function () { return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: false }) || ''; }]; promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) { // References to the controller (only instantiated at link time) if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) { var injectLocals = angular.extend({}, injectables, locals); result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals); } else { result.$$controller = view.controller; } // Provide access to the state itself for internal use result.$$state = state; result.$$controllerAs = view.controllerAs; dst[name] = result; })); }); // Wait for all the promises and then return the activation object return $q.all(promises).then(function (values) { return dst; }); } return $state; } function shouldTriggerReload(to, from, locals, options) { if ( to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false)) ) { return true; } } } angular.module('ui.router.state') .value('$stateParams', {}) .provider('$state', $StateProvider); $ViewProvider.$inject = []; function $ViewProvider() { this.$get = $get; /** * @ngdoc object * @name ui.router.state.$view * * @requires ui.router.util.$templateFactory * @requires $rootScope * * @description * */ $get.$inject = ['$rootScope', '$templateFactory']; function $get( $rootScope, $templateFactory) { return { // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... }) /** * @ngdoc function * @name ui.router.state.$view#load * @methodOf ui.router.state.$view * * @description * * @param {string} name name * @param {object} options option object. */ load: function load(name, options) { var result, defaults = { template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {} }; options = extend(defaults, options); if (options.view) { result = $templateFactory.fromConfig(options.view, options.params, options.locals); } if (result && options.notify) { /** * @ngdoc event * @name ui.router.state.$state#$viewContentLoading * @eventOf ui.router.state.$view * @eventType broadcast on root scope * @description * * Fired once the view **begins loading**, *before* the DOM is rendered. * * @param {Object} event Event object. * @param {Object} viewConfig The view config properties (template, controller, etc). * * @example * *
         * $scope.$on('$viewContentLoading',
         * function(event, viewConfig){
         *     // Access to all the view config properties.
         *     // and one special property 'targetView'
         *     // viewConfig.targetView
         * });
         * 
*/ $rootScope.$broadcast('$viewContentLoading', options); } return result; } }; } } angular.module('ui.router.state').provider('$view', $ViewProvider); /** * @ngdoc object * @name ui.router.state.$uiViewScrollProvider * * @description * Provider that returns the {@link ui.router.state.$uiViewScroll} service function. */ function $ViewScrollProvider() { var useAnchorScroll = false; /** * @ngdoc function * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll * @methodOf ui.router.state.$uiViewScrollProvider * * @description * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for * scrolling based on the url anchor. */ this.useAnchorScroll = function () { useAnchorScroll = true; }; /** * @ngdoc object * @name ui.router.state.$uiViewScroll * * @requires $anchorScroll * @requires $timeout * * @description * When called with a jqLite element, it scrolls the element into view (after a * `$timeout` so the DOM has time to refresh). * * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor, * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}. */ this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) { if (useAnchorScroll) { return $anchorScroll; } return function ($element) { $timeout(function () { $element[0].scrollIntoView(); }, 0, false); }; }]; } angular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider); /** * @ngdoc directive * @name ui.router.state.directive:ui-view * * @requires ui.router.state.$state * @requires $compile * @requires $controller * @requires $injector * @requires ui.router.state.$uiViewScroll * @requires $document * * @restrict ECA * * @description * The ui-view directive tells $state where to place your templates. * * @param {string=} ui-view A view name. The name should be unique amongst the other views in the * same state. You can have views of the same name that live in different states. * * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you * scroll ui-view elements into view when they are populated during a state activation. * * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.* * * @param {string=} onload Expression to evaluate whenever the view updates. * * @example * A view can be unnamed or named. *
 * 
 * 
* * *
*
* * You can only have one unnamed view within any template (or root html). If you are only using a * single view and it is unnamed then you can populate it like so: *
 * 
* $stateProvider.state("home", { * template: "

HELLO!

" * }) *
* * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`} * config property, by name, in this case an empty name: *
 * $stateProvider.state("home", {
 *   views: {
 *     "": {
 *       template: "

HELLO!

" * } * } * }) *
* * But typically you'll only use the views property if you name your view or have more than one view * in the same template. There's not really a compelling reason to name a view if its the only one, * but you could if you wanted, like so: *
 * 
*
*
 * $stateProvider.state("home", {
 *   views: {
 *     "main": {
 *       template: "

HELLO!

" * } * } * }) *
* * Really though, you'll use views to set up multiple views: *
 * 
*
*
*
* *
 * $stateProvider.state("home", {
 *   views: {
 *     "": {
 *       template: "

HELLO!

" * }, * "chart": { * template: "" * }, * "data": { * template: "" * } * } * }) *
* * Examples for `autoscroll`: * *
 * 
 * 
 *
 * 
 * 
 * 
 * 
 * 
*/ $ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll']; function $ViewDirective( $state, $injector, $uiViewScroll) { function getService() { return ($injector.has) ? function(service) { return $injector.has(service) ? $injector.get(service) : null; } : function(service) { try { return $injector.get(service); } catch (e) { return null; } }; } var service = getService(), $animator = service('$animator'), $animate = service('$animate'); // Returns a set of DOM manipulation functions based on which Angular version // it should use function getRenderer(attrs, scope) { var statics = function() { return { enter: function (element, target, cb) { target.after(element); cb(); }, leave: function (element, cb) { element.remove(); cb(); } }; }; if ($animate) { return { enter: function(element, target, cb) { $animate.enter(element, null, target, cb); }, leave: function(element, cb) { $animate.leave(element, cb); } }; } if ($animator) { var animate = $animator && $animator(scope, attrs); return { enter: function(element, target, cb) {animate.enter(element, null, target); cb(); }, leave: function(element, cb) { animate.leave(element); cb(); } }; } return statics(); } var directive = { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', compile: function (tElement, tAttrs, $transclude) { return function (scope, $element, attrs) { var previousEl, currentEl, currentScope, latestLocals, onloadExp = attrs.onload || '', autoScrollExp = attrs.autoscroll, renderer = getRenderer(attrs, scope); scope.$on('$stateChangeSuccess', function() { updateView(false); }); scope.$on('$viewContentLoading', function() { updateView(false); }); updateView(true); function cleanupLastView() { if (previousEl) { previousEl.remove(); previousEl = null; } if (currentScope) { currentScope.$destroy(); currentScope = null; } if (currentEl) { renderer.leave(currentEl, function() { previousEl = null; }); previousEl = currentEl; currentEl = null; } } function updateView(firstTime) { var newScope = scope.$new(), name = currentEl && currentEl.data('$uiViewName'), previousLocals = name && $state.$current && $state.$current.locals[name]; if (!firstTime && previousLocals === latestLocals) return; // nothing to do var clone = $transclude(newScope, function(clone) { renderer.enter(clone, $element, function onUiViewEnter() { if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) { $uiViewScroll(clone); } }); cleanupLastView(); }); latestLocals = $state.$current.locals[clone.data('$uiViewName')]; currentEl = clone; currentScope = newScope; /** * @ngdoc event * @name ui.router.state.directive:ui-view#$viewContentLoaded * @eventOf ui.router.state.directive:ui-view * @eventType emits on ui-view directive scope * @description * * Fired once the view is **loaded**, *after* the DOM is rendered. * * @param {Object} event Event object. */ currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } }; } }; return directive; } $ViewDirectiveFill.$inject = ['$compile', '$controller', '$state']; function $ViewDirectiveFill ($compile, $controller, $state) { return { restrict: 'ECA', priority: -400, compile: function (tElement) { var initial = tElement.html(); return function (scope, $element, attrs) { var name = attrs.uiView || attrs.name || '', inherited = $element.inheritedData('$uiView'); if (name.indexOf('@') < 0) { name = name + '@' + (inherited ? inherited.state.name : ''); } $element.data('$uiViewName', name); var current = $state.$current, locals = current && current.locals[name]; if (! locals) { return; } $element.data('$uiView', { name: name, state: locals.$$state }); $element.html(locals.$template ? locals.$template : initial); var link = $compile($element.contents()); if (locals.$$controller) { locals.$scope = scope; var controller = $controller(locals.$$controller, locals); if (locals.$$controllerAs) { scope[locals.$$controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); }; } }; } angular.module('ui.router.state').directive('uiView', $ViewDirective); angular.module('ui.router.state').directive('uiView', $ViewDirectiveFill); function parseStateRef(ref) { var parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/); if (!parsed || parsed.length !== 4) throw new Error("Invalid state ref '" + ref + "'"); return { state: parsed[1], paramExpr: parsed[3] || null }; } function stateContext(el) { var stateData = el.parent().inheritedData('$uiView'); if (stateData && stateData.state && stateData.state.name) { return stateData.state; } } /** * @ngdoc directive * @name ui.router.state.directive:ui-sref * * @requires ui.router.state.$state * @requires $timeout * * @restrict A * * @description * A directive that binds a link (`` tag) to a state. If the state has an associated * URL, the directive will automatically generate & update the `href` attribute via * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking * the link will trigger a state transition with optional parameters. * * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be * handled natively by the browser. * * You can also use relative state paths within ui-sref, just like the relative * paths passed to `$state.go()`. You just need to be aware that the path is relative * to the state that the link lives in, in other words the state that loaded the * template containing the link. * * You can specify options to pass to {@link ui.router.state.$state#go $state.go()} * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`, * and `reload`. * * @example * Here's an example of how you'd use ui-sref and how it would compile. If you have the * following template: *
 * Home | About
 * 
 * 
 * 
* * Then the compiled html would be (assuming Html5Mode is off): *
 * Home | About
 * 
 * 
 *
 * Home
 * 
* * @param {string} ui-sref 'stateName' can be any valid absolute or relative state * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()} */ $StateRefDirective.$inject = ['$state', '$timeout']; function $StateRefDirective($state, $timeout) { var allowedOptions = ['location', 'inherit', 'reload']; return { restrict: 'A', require: '?^uiSrefActive', link: function(scope, element, attrs, uiSrefActive) { var ref = parseStateRef(attrs.uiSref); var params = null, url = null, base = stateContext(element) || $state.$current; var isForm = element[0].nodeName === "FORM"; var attr = isForm ? "action" : "href", nav = true; var options = { relative: base }; var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {}; angular.forEach(allowedOptions, function(option) { if (option in optionsOverride) { options[option] = optionsOverride[option]; } }); var update = function(newVal) { if (newVal) params = newVal; if (!nav) return; var newHref = $state.href(ref.state, params, options); if (uiSrefActive) { uiSrefActive.$$setStateInfo(ref.state, params); } if (!newHref) { nav = false; return false; } element[0][attr] = newHref; }; if (ref.paramExpr) { scope.$watch(ref.paramExpr, function(newVal, oldVal) { if (newVal !== params) update(newVal); }, true); params = scope.$eval(ref.paramExpr); } update(); if (isForm) return; element.bind("click", function(e) { var button = e.which || e.button; if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) { // HACK: This is to allow ng-clicks to be processed before the transition is initiated: $timeout(function() { $state.go(ref.state, params, options); }); e.preventDefault(); } }); } }; } /** * @ngdoc directive * @name ui.router.state.directive:ui-sref-active * * @requires ui.router.state.$state * @requires ui.router.state.$stateParams * @requires $interpolate * * @restrict A * * @description * A directive working alongside ui-sref to add classes to an element when the * related ui-sref directive's state is active, and removing them when it is inactive. * The primary use-case is to simplify the special appearance of navigation menus * relying on `ui-sref`, by having the "active" state's menu button appear different, * distinguishing it from the inactive menu items. * * @example * Given the following template: *
 * 
 * 
* * When the app state is "app.user", and contains the state parameter "user" with value "bilbobaggins", * the resulting HTML will appear as (note the 'active' class): *
 * 
 * 
* * The class name is interpolated **once** during the directives link time (any further changes to the * interpolated value are ignored). * * Multiple classes may be specified in a space-separated format: *
 * 
 * 
*/ $StateActiveDirective.$inject = ['$state', '$stateParams', '$interpolate']; function $StateActiveDirective($state, $stateParams, $interpolate) { return { restrict: "A", controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) { var state, params, activeClass; // There probably isn't much point in $observing this activeClass = $interpolate($attrs.uiSrefActive || '', false)($scope); // Allow uiSref to communicate with uiSrefActive this.$$setStateInfo = function(newState, newParams) { state = $state.get(newState, stateContext($element)); params = newParams; update(); }; $scope.$on('$stateChangeSuccess', update); // Update route state function update() { if ($state.$current.self === state && matchesParams()) { $element.addClass(activeClass); } else { $element.removeClass(activeClass); } } function matchesParams() { return !params || equalForKeys(params, $stateParams); } }] }; } angular.module('ui.router.state') .directive('uiSref', $StateRefDirective) .directive('uiSrefActive', $StateActiveDirective); /** * @ngdoc filter * @name ui.router.state.filter:isState * * @requires ui.router.state.$state * * @description * Translates to {@link ui.router.state.$state#methods_is $state.is("stateName")}. */ $IsStateFilter.$inject = ['$state']; function $IsStateFilter($state) { return function(state) { return $state.is(state); }; } /** * @ngdoc filter * @name ui.router.state.filter:includedByState * * @requires ui.router.state.$state * * @description * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}. */ $IncludedByStateFilter.$inject = ['$state']; function $IncludedByStateFilter($state) { return function(state) { return $state.includes(state); }; } angular.module('ui.router.state') .filter('isState', $IsStateFilter) .filter('includedByState', $IncludedByStateFilter); /* * @ngdoc object * @name ui.router.compat.$routeProvider * * @requires ui.router.state.$stateProvider * @requires ui.router.router.$urlRouterProvider * * @description * `$routeProvider` of the `ui.router.compat` module overwrites the existing * `routeProvider` from the core. This is done to provide compatibility between * the UI Router and the core router. * * It also provides a `when()` method to register routes that map to certain urls. * Behind the scenes it actually delegates either to * {@link ui.router.router.$urlRouterProvider $urlRouterProvider} or to the * {@link ui.router.state.$stateProvider $stateProvider} to postprocess the given * router definition object. */ $RouteProvider.$inject = ['$stateProvider', '$urlRouterProvider']; function $RouteProvider( $stateProvider, $urlRouterProvider) { var routes = []; onEnterRoute.$inject = ['$$state']; function onEnterRoute( $$state) { /*jshint validthis: true */ this.locals = $$state.locals.globals; this.params = this.locals.$stateParams; } function onExitRoute() { /*jshint validthis: true */ this.locals = null; this.params = null; } this.when = when; /* * @ngdoc function * @name ui.router.compat.$routeProvider#when * @methodOf ui.router.compat.$routeProvider * * @description * Registers a route with a given route definition object. The route definition * object has the same interface the angular core route definition object has. * * @example *
   * var app = angular.module('app', ['ui.router.compat']);
   *
   * app.config(function ($routeProvider) {
   *   $routeProvider.when('home', {
   *     controller: function () { ... },
   *     templateUrl: 'path/to/template'
   *   });
   * });
   * 
* * @param {string} url URL as string * @param {object} route Route definition object * * @return {object} $routeProvider - $routeProvider instance */ function when(url, route) { /*jshint validthis: true */ if (route.redirectTo != null) { // Redirect, configure directly on $urlRouterProvider var redirect = route.redirectTo, handler; if (isString(redirect)) { handler = redirect; // leave $urlRouterProvider to handle } else if (isFunction(redirect)) { // Adapt to $urlRouterProvider API handler = function (params, $location) { return redirect(params, $location.path(), $location.search()); }; } else { throw new Error("Invalid 'redirectTo' in when()"); } $urlRouterProvider.when(url, handler); } else { // Regular route, configure as state $stateProvider.state(inherit(route, { parent: null, name: 'route:' + encodeURIComponent(url), url: url, onEnter: onEnterRoute, onExit: onExitRoute })); } routes.push(route); return this; } /* * @ngdoc object * @name ui.router.compat.$route * * @requires ui.router.state.$state * @requires $rootScope * @requires $routeParams * * @property {object} routes - Array of registered routes. * @property {object} params - Current route params as object. * @property {string} current - Name of the current route. * * @description * The `$route` service provides interfaces to access defined routes. It also let's * you access route params through `$routeParams` service, so you have fully * control over all the stuff you would actually get from angular's core `$route` * service. */ this.$get = $get; $get.$inject = ['$state', '$rootScope', '$routeParams']; function $get( $state, $rootScope, $routeParams) { var $route = { routes: routes, params: $routeParams, current: undefined }; function stateAsRoute(state) { return (state.name !== '') ? state : undefined; } $rootScope.$on('$stateChangeStart', function (ev, to, toParams, from, fromParams) { $rootScope.$broadcast('$routeChangeStart', stateAsRoute(to), stateAsRoute(from)); }); $rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) { $route.current = stateAsRoute(to); $rootScope.$broadcast('$routeChangeSuccess', stateAsRoute(to), stateAsRoute(from)); copy(toParams, $route.params); }); $rootScope.$on('$stateChangeError', function (ev, to, toParams, from, fromParams, error) { $rootScope.$broadcast('$routeChangeError', stateAsRoute(to), stateAsRoute(from), error); }); return $route; } } angular.module('ui.router.compat') .provider('$route', $RouteProvider) .directive('ngView', $ViewDirective); })(window, window.angular);