forked from angular-ui/ui-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.js
924 lines (840 loc) · 35.4 KB
/
state.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
/**
* @ngdoc object
* @name ui.router.state.$stateProvider
*
* @requires ui.router.router.$urlRouterProvider
* @requires ui.router.util.$urlMatcherFactoryProvider
* @requires $locationProvider
*
* @description
* The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely
* on state.
*
* A state corresponds to a "place" in the application in terms of the overall UI and
* navigation. A state describes (via the controller / template / view properties) what
* the UI looks like and does at that place.
*
* States often have things in common, and the primary way of factoring out these
* commonalities in this model is via the state hierarchy, i.e. parent/child states aka
* nested states.
*
* The `$stateProvider` provides interfaces to declare these states for your app.
*/
$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider', '$locationProvider'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $locationProvider) {
var root, states = {}, $state, queue = {}, abstractKey = 'abstract';
// Builds state properties from definition passed to registerState()
var stateBuilder = {
// Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.
// state.children = [];
// if (parent) parent.children.push(state);
parent: function(state) {
if (isDefined(state.parent) && state.parent) return findState(state.parent);
// regex matches any valid composite state name
// would match "contact.list" but not "contacts"
var compositeName = /^(.+)\.[^.]+$/.exec(state.name);
return compositeName ? findState(compositeName[1]) : root;
},
// inherit 'data' from parent and override by own values (if any)
data: function(state) {
if (state.parent && state.parent.data) {
state.data = state.self.data = extend({}, state.parent.data, state.data);
}
return state.data;
},
// Build a URLMatcher if necessary, either via a relative or absolute URL
url: function(state) {
var url = state.url;
if (isString(url)) {
if (url.charAt(0) == '^') {
return $urlMatcherFactory.compile(url.substring(1), state.strict);
}
return (state.parent.navigable || root).url.concat(url, state.strict);
}
if ($urlMatcherFactory.isMatcher(url) || url == null) {
return url;
}
throw new Error("Invalid url '" + url + "' in state '" + state + "'");
},
// Keep track of the closest ancestor state that has a URL (i.e. is navigable)
navigable: function(state) {
return state.url ? state : (state.parent ? state.parent.navigable : null);
},
// Derive parameters for this state and ensure they're a super-set of parent's parameters
params: function(state) {
if (!state.params) {
return state.url ? state.url.parameters() : state.parent.params;
}
if (!isArray(state.params)) throw new Error("Invalid params in state '" + state + "'");
if (state.url) throw new Error("Both params and url specicified in state '" + state + "'");
return state.params;
},
// If there is no explicit multi-view configuration, make one up so we don't have
// to handle both cases in the view directive later. Note that having an explicit
// 'views' property will mean the default unnamed view properties are ignored. This
// is also a good time to resolve view names to absolute names, so everything is a
// straight lookup at link time.
views: function(state) {
var views = {};
forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {
if (name.indexOf('@') < 0) name += '@' + state.parent.name;
views[name] = view;
});
return views;
},
ownParams: function(state) {
if (!state.parent) {
return state.params;
}
var paramNames = {}; forEach(state.params, function (p) { paramNames[p] = true; });
forEach(state.parent.params, function (p) {
if (!paramNames[p]) {
throw new Error("Missing required parameter '" + p + "' in state '" + state.name + "'");
}
paramNames[p] = false;
});
var ownParams = [];
forEach(paramNames, function (own, p) {
if (own) ownParams.push(p);
});
return ownParams;
},
// Keep a full path from the root down to this state as this is needed for state activation.
path: function(state) {
return state.parent ? state.parent.path.concat(state) : []; // exclude root from path
},
// Speed up $state.contains() as it's used a lot
includes: function(state) {
var includes = state.parent ? extend({}, state.parent.includes) : {};
includes[state.name] = true;
return includes;
},
$delegates: {}
};
function isRelative(stateName) {
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
}
function findState(stateOrName, base) {
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function queueState(parentName, state) {
if (!queue[parentName]) {
queue[parentName] = [];
}
queue[parentName].push(state);
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
// Get parent name
var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
: (isString(state.parent)) ? state.parent
: '';
// If parent is not registered yet, add state to queue and register later
if (parentName && !states[parentName]) {
return queueState(parentName, state.self);
}
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams, state.ownParams)) {
$state.transitionTo(state, $match, { location: false });
}
}]);
}
// Register any queued children
if (queue[name]) {
for (var i = 0; i < queue[name].length; i++) {
registerState(queue[name][i]);
}
}
return state;
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#decorator
* @methodOf ui.router.state.$stateProvider
*
* @description
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by `$stateProvider`. This can be used
* to add custom functionality to ui-router, for example inferring templateUrl
* based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in nondeterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - parent - `{object}` - returns the parent state object.
* - data - `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - url - `{object}` - returns a UrlMatcher or null.
* - navigable - returns closest ancestor state that has a URL (aka is
* navigable).
* - params - `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - views - `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - ownParams - `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - path - `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - includes - `{object}` - returns an object that includes every state that
* would pass a '$state.includes()' test.
*
* @example
* <pre>
* // Override the internal 'views' builder with a function that takes the state
* // definition, and a reference to the internal function being overridden:
* $stateProvider.decorator('views', function ($state, parent) {
* var result = {},
* views = parent(state);
*
* angular.forEach(view, function (config, name) {
* var autoName = (state.name + '.' + name).replace('.', '/');
* config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';
* result[name] = config;
* });
* return result;
* });
*
* $stateProvider.state('home', {
* views: {
* 'contact.list': { controller: 'ListController' },
* 'contact.item': { controller: 'ItemController' }
* }
* });
*
* // ...
*
* $state.go('home');
* // Auto-populates list and item views with /partials/home/contact/list.html,
* // and /partials/home/contact/item.html, respectively.
* </pre>
*
* @param {string} name The name of the builder function to decorate.
* @param {object} func A function that is responsible for decorating the original
* builder function. The function receives two parameters:
*
* - `{object}` - state - The state config object.
* - `{object}` - super - The original builder function.
*
* @return {object} $stateProvider - $stateProvider instance
*/
this.decorator = decorator;
function decorator(name, func) {
/*jshint validthis: true */
if (isString(name) && !isDefined(func)) {
return stateBuilder[name];
}
if (!isFunction(func) || !isString(name)) {
return this;
}
if (stateBuilder[name] && !stateBuilder.$delegates[name]) {
stateBuilder.$delegates[name] = stateBuilder[name];
}
stateBuilder[name] = func;
return this;
}
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#state
* @methodOf ui.router.state.$stateProvider
*
* @description
* Registers a state configuration under a given state name. The stateConfig object
* has the following acceptable properties.
*
* - [`template`, `templateUrl`, `templateProvider`] - There are three ways to setup
* your templates.
*
* - `{string|object}` - template - String HTML content, or function that returns an HTML
* string.
* - `{string}` - templateUrl - String URL path to template file OR function,
* that returns URL path string.
* - `{object}` - templateProvider - Provider function that returns HTML content
* string.
*
* - [`controller`, `controllerProvider`] - A controller paired to the state. You can
* either use a controller, or a controller provider.
*
* - `{string|object}` - controller - Controller function or controller name.
* - `{object}` - controllerProvider - Injectable provider function that returns
* the actual controller or string.
*
* - `{object}` - resolve - A map of dependencies which should be injected into the
* controller.
*
* - `{string}` - url - A url with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* - `{object}` - params - An array of parameter names or regular expressions. Only
* use this within a state if you are not using url. Otherwise you can specify your
* parameters within the url. When a state is navigated or transitioned to, the
* $stateParams service will be populated with any parameters that were passed.
*
* - `{object}` - views - Use the views property to set up multiple views.
* If you don't need multiple views within a single state this property is not
* needed. Tip: remember that often nested views are more useful and powerful
* than multiple sibling views.
*
* - `{boolean}` - abstract - An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
*
* - `{object}` - onEnter - Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
*
* - `{object}` - onExit - Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
*
* - `{object}` - data - Arbitrary data object, useful for custom configuration.
*
* @example
* <pre>
* // The state() method takes a unique stateName (String) and a stateConfig (Object)
* $stateProvider.state(stateName, stateConfig);
*
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* </pre>
*
* @param {string} name A unique state name, e.g. "home", "about", "contacts".
* To create a parent/child state use a dot, e.g. "about.sales", "home.newest".
* @param {object} definition State configuratino object.
*/
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
/**
* @ngdoc object
* @name ui.router.state.$state
*
* @requires $rootScope
* @requires $q
* @requires ui.router.state.$view
* @requires $injector
* @requires ui.router.util.$resolve
* @requires ui.router.state.$stateParams
*
* @property {object} params A param object, e.g. {sectionId: section.id)}, that
* you'd like to test against the current active state.
* @property {object} current A reference to the state's config object. However
* you passed it in. Useful for accessing custom data.
* @property {object} transition Currently pending transition. A promise that'll
* resolve or reject.
*
* @description
* `$state` service is responsible for representing states as well as transitioning
* between them. It also provides interfaces to ask for current state or even states
* you're coming from.
*/
// $urlRouter is injected just to ensure it gets instantiated
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$location', '$urlRouter'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $location, $urlRouter) {
var TransitionSuperseded = $q.reject(new Error('transition superseded'));
var TransitionPrevented = $q.reject(new Error('transition prevented'));
var TransitionAborted = $q.reject(new Error('transition aborted'));
var TransitionFailed = $q.reject(new Error('transition failed'));
var currentLocation = $location.url();
function syncUrl() {
if ($location.url() !== currentLocation) {
$location.url(currentLocation);
$location.replace();
}
}
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* Reloads the current state by re-transitioning to it.
*
* @example
* <pre>
* var app angular.module('app', ['ui.router.state']);
*
* app.controller('ctrl', function ($state) {
* $state.reload();
* });
* </pre>
*/
$state.reload = function reload() {
$state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: false });
};
/**
* @ngdoc function
* @name ui.router.state.$state#go
* @methodOf ui.router.state.$state
*
* @description
* Convenience method for transitioning to a new state. `$state.go` calls
* `$state.transitionTo` internally but automatically sets options to
* `{ location: true, inherit: true, relative: $state.$current, notify: true }`.
* This allows you to easily use an absolute or relative to path and specify
* only the parameters you'd like to update (while letting unspecified parameters
* inherit from the current state.
*
* Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.state']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
*
* @param {string} to Absolute State Name or Relative State Path.
* @param {object} params A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object} options If Object is passed, object is an options hash.
*/
$state.go = function go(to, params, options) {
return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router.state']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string} to Absolute State Name or Relative State Path.
* @param {object} params A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object} options If Object is passed, object is an options hash.
*/
$state.transitionTo = function transitionTo(to, toParams, options) {
toParams = toParams || {};
options = extend({
location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
}, options || {});
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var evt, toState = findState(to, options.relative);
if (!isDefined(toState)) {
// Broadcast not found event and abort the transition if prevented
var redirect = { to: to, toParams: toParams, options: options };
evt = $rootScope.$broadcast('$stateNotFound', redirect, from.self, fromParams);
if (evt.defaultPrevented) {
syncUrl();
return TransitionAborted;
}
// Allow the handler to return a promise to defer state lookup retry
if (evt.retry) {
if (options.$retry) {
syncUrl();
return TransitionFailed;
}
var retryTransition = $state.transition = $q.when(evt.retry);
retryTransition.then(function() {
if (retryTransition !== $state.transition) return TransitionSuperseded;
redirect.options.$retry = true;
return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);
}, function() {
return TransitionAborted;
});
syncUrl();
return retryTransition;
}
// Always retry once if the $stateNotFound was not prevented
// (handles either redirect changed or state lazy-definition)
to = redirect.to;
toParams = redirect.toParams;
options = redirect.options;
toState = findState(to, options.relative);
if (!isDefined(toState)) {
if (options.relative) throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
throw new Error("No such state '" + to + "'");
}
}
if (toState[abstractKey]) throw new Error("Cannot transition to abstract state '" + to + "'");
if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);
to = toState;
var toPath = to.path;
// Starting from the root of the path, keep all levels that haven't changed
var keep, state, locals = root.locals, toLocals = [];
for (keep = 0, state = toPath[keep];
state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams) && !options.reload;
keep++, state = toPath[keep]) {
locals = toLocals[keep] = state.locals;
}
// If we're going to the same state and all locals are kept, we've got nothing to do.
// But clear 'transition', as we still want to cancel any other pending transitions.
// TODO: We may not want to bump 'transition' if we're called from a location change that we've initiated ourselves,
// because we might accidentally abort a legitimate transition initiated from code?
if (shouldTriggerReload(to, from, locals, options) ) {
if ( to.self.reloadOnSearch !== false )
syncUrl();
$state.transition = null;
return $q.when($state.current);
}
// Normalize/filter parameters before we pass them to event handlers etc.
toParams = normalize(to.params, toParams || {});
// Broadcast start event and cancel the transition if requested
if (options.notify) {
evt = $rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams);
if (evt.defaultPrevented) {
syncUrl();
return TransitionPrevented;
}
}
// Resolve locals for the remaining states, but don't update any global state just
// yet -- if anything fails to resolve the current state needs to remain untouched.
// We also set up an inheritance chain for the locals here. This allows the view directive
// to quickly look up the correct definition for each view in the current state. Even
// though we create the locals object itself outside resolveState(), it is initially
// empty and gets filled asynchronously. We need to keep track of the promise for the
// (fully resolved) current locals, and pass this down the chain.
var resolved = $q.when(locals);
for (var l=keep; l<toPath.length; l++, state=toPath[l]) {
locals = toLocals[l] = inherit(locals);
resolved = resolveState(state, toParams, state===to, resolved, locals);
}
// Once everything is resolved, we are ready to perform the actual transition
// and return a promise for the new state. We also keep track of what the
// current promise is, so that we can detect overlapping transitions and
// keep only the outcome of the last transition.
var transition = $state.transition = resolved.then(function () {
var l, entering, exiting;
if ($state.transition !== transition) return TransitionSuperseded;
// Exit 'from' states not kept
for (l=fromPath.length-1; l>=keep; l--) {
exiting = fromPath[l];
if (exiting.self.onExit) {
$injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);
}
exiting.locals = null;
}
// Enter 'to' states not kept
for (l=keep; l<toPath.length; l++) {
entering = toPath[l];
entering.locals = toLocals[l];
if (entering.self.onEnter) {
$injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);
}
}
// Run it again, to catch any transitions in callbacks
if ($state.transition !== transition) return TransitionSuperseded;
// Update globals in $state
$state.$current = to;
$state.current = to.self;
$state.params = toParams;
copy($state.params, $stateParams);
$state.transition = null;
// Update $location
var toNav = to.navigable;
if (options.location && toNav) {
$location.url(toNav.url.format(toNav.locals.globals.$stateParams));
if (options.location === 'replace') {
$location.replace();
}
}
if (options.notify) {
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
}
currentLocation = $location.url();
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
$rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
syncUrl();
return $q.reject(error);
});
return transition;
};
/**
* @ngdoc function
* @name ui.router.state.$state#is
* @methodOf ui.router.state.$state
*
* @description
* Similar to {@link ui.router.state.$state#methods_includes $state.includes},
* but only checks for the full state name. If params is supplied then it will be
* tested for strict equality against the current active params object, so all params
* must match with none missing and no extras.
*
* @example
* <pre>
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // everything else would return false
* </pre>
*
* @param {string|object} stateName The state name or state object you'd like to check.
* @param {object} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @returns {boolean} Returns true or false whether its the state or not.
*/
$state.is = function is(stateOrName, params) {
var state = findState(stateOrName);
if (!isDefined(state)) {
return undefined;
}
if ($state.$current !== state) {
return false;
}
return isDefined(params) && params !== null ? angular.equals($stateParams, params) : true;
};
/**
* @ngdoc function
* @name ui.router.state.$state#includes
* @methodOf ui.router.state.$state
*
* @description
* A method to determine if the current active state is equal to or is the child of the
* state stateName. If any params are passed then they will be tested for a match as well.
* Not all the parameters need to be passed, just the ones you'd like to test for equality.
*
* @example
* <pre>
* $state.includes("contacts"); // returns true
* $state.includes("contacts.details"); // returns true
* $state.includes("contacts.details.item"); // returns true
* $state.includes("contacts.list"); // returns false
* $state.includes("about"); // returns false
* </pre>
*
* @param {string} stateOrName A partial name to be searched for within the current state name.
* @param {object} params A param object, e.g. `{sectionId: section.id}`,
* that you'd like to test against the current active state.
* @returns {boolean} True or false
*/
$state.includes = function includes(stateOrName, params) {
var state = findState(stateOrName);
if (!isDefined(state)) {
return undefined;
}
if (!isDefined($state.$current.includes[state.name])) {
return false;
}
var validParams = true;
angular.forEach(params, function(value, key) {
if (!isDefined($stateParams[key]) || $stateParams[key] !== value) {
validParams = false;
}
});
return validParams;
};
/**
* @ngdoc function
* @name ui.router.state.$state#href
* @methodOf ui.router.state.$state
*
* @description
* A url generation method that returns the compiled url for the given state populated with the given params.
*
* @example
* <pre>
* expect($state.href("about.person", { person: "bob" })).toEqual("/about/bob");
* </pre>
*
* @param {string|object} stateOrName The state name or state object you'd like to generate a url from.
* @param {object} params An object of parameter values to fill the state's required parameters.
* @returns {string} url
*/
$state.href = function href(stateOrName, params, options) {
options = extend({ lossy: true, inherit: false, absolute: false, relative: $state.$current }, options || {});
var state = findState(stateOrName, options.relative);
if (!isDefined(state)) return null;
params = inheritParams($stateParams, params || {}, $state.$current, state);
var nav = (state && options.lossy) ? state.navigable : state;
var url = (nav && nav.url) ? nav.url.format(normalize(state.params, params || {})) : null;
if (!$locationProvider.html5Mode() && url) {
url = "#" + $locationProvider.hashPrefix() + url;
}
if (options.absolute && url) {
url = $location.protocol() + '://' +
$location.host() +
($location.port() == 80 || $location.port() == 443 ? '' : ':' + $location.port()) +
(!$locationProvider.html5Mode() && url ? '/' : '') +
url;
}
return url;
};
/**
* @ngdoc function
* @name ui.router.state.$state#get
* @methodOf ui.router.state.$state
*
* @description
* Returns the state configuration object for any state by passing the name
* as a string. Without any arguments it'll return a array of all configured
* state objects.
*
* @param {string|object} stateOrName The name of the state for which you'd like
* to get the original state configuration object for.
* @returns {object} State configuration object or array of all objects.
*/
$state.get = function (stateOrName, context) {
if (!isDefined(stateOrName)) {
var list = [];
forEach(states, function(state) { list.push(state.self); });
return list;
}
var state = findState(stateOrName, context);
return (state && state.self) ? state.self : null;
};
function resolveState(state, params, paramsAreFiltered, inherited, dst) {
// Make a restricted $stateParams with only the parameters that apply to this state if
// necessary. In addition to being available to the controller and onEnter/onExit callbacks,
// we also need $stateParams to be available for any $injector calls we make during the
// dependency resolution process.
var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params, params);
var locals = { $stateParams: $stateParams };
// Resolve 'global' dependencies for the state, i.e. those not specific to a view.
// We're also including $stateParams in this; that way the parameters are restricted
// to the set that should be visible to the state, and are independent of when we update
// the global $state and $stateParams values.
dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
var promises = [ dst.resolve.then(function (globals) {
dst.globals = globals;
}) ];
if (inherited) promises.push(inherited);
// Resolve template and dependencies for all views.
forEach(state.views, function (view, name) {
var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});
injectables.$template = [ function () {
return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: false }) || '';
}];
promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
// References to the controller (only instantiated at link time)
if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {
var injectLocals = angular.extend({}, injectables, locals);
result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);
} else {
result.$$controller = view.controller;
}
// Provide access to the state itself for internal use
result.$$state = state;
dst[name] = result;
}));
});
// Wait for all the promises and then return the activation object
return $q.all(promises).then(function (values) {
return dst;
});
}
return $state;
}
function shouldTriggerReload(to, from, locals, options) {
if ( to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false)) ) {
return true;
}
}
}
angular.module('ui.router.state')
.value('$stateParams', {})
.provider('$state', $StateProvider);