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