angular_master 0.1.0

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