forked from angular-ui/ui-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.js
1200 lines (1096 loc) · 47.8 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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @ngdoc object
* @name ui.router.state.$stateProvider
*
* @requires ui.router.router.$urlRouterProvider
* @requires ui.router.util.$urlMatcherFactoryProvider
*
* @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'];
function $StateProvider( $urlRouterProvider, $urlMatcherFactory) {
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, config = { params: state.params || {} };
if (isString(url)) {
if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);
return (state.parent.navigable || root).url.concat(url, config);
}
if (!url || $urlMatcherFactory.isMatcher(url)) 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.params : state.parent.params;
}
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) {
state.params = state.params || {};
if (!state.parent) {
return objectKeys(state.params);
}
var paramNames = {}; forEach(state.params, function (v, k) { paramNames[k] = true; });
forEach(state.parent.params, function (v, k) {
if (!paramNames[k]) {
throw new Error("Missing required parameter '" + k + "' in state '" + state.name + "'");
}
paramNames[k] = 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) {
if (!stateOrName) return undefined;
var isStr = isString(stateOrName),
name = isStr ? stateOrName : stateOrName.name,
path = isRelative(name);
if (path) {
if (!base) throw new Error("No reference point given for path '" + name + "'");
var rel = name.split("."), i = 0, pathLength = rel.length, current = base;
for (; i < pathLength; i++) {
if (rel[i] === "" && i === 0) {
current = base;
continue;
}
if (rel[i] === "^") {
if (!current.parent) throw new Error("Path '" + name + "' not valid for state '" + base.name + "'");
current = current.parent;
continue;
}
break;
}
rel = rel.slice(i).join(".");
name = current.name + (current.name && rel ? "." : "") + rel;
}
var state = states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
return undefined;
}
function queueState(parentName, state) {
if (!queue[parentName]) {
queue[parentName] = [];
}
queue[parentName].push(state);
}
function registerState(state) {
// Wrap a new object around the state so we can store our private details easily.
state = inherit(state, {
self: state,
resolve: state.resolve || {},
toString: function() { return this.name; }
});
var name = state.name;
if (!isString(name) || name.indexOf('@') >= 0) throw new Error("State must have a valid name");
if (states.hasOwnProperty(name)) throw new Error("State '" + name + "'' is already defined");
// Get parent name
var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))
: (isString(state.parent)) ? state.parent
: '';
// If parent is not registered yet, add state to queue and register later
if (parentName && !states[parentName]) {
return queueState(parentName, state.self);
}
for (var key in stateBuilder) {
if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);
}
states[name] = state;
// Register the state in the global state list and with $urlRouter if necessary.
if (!state[abstractKey] && state.url) {
$urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {
if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {
$state.transitionTo(state, $match, { location: false });
}
}]);
}
// Register any queued children
if (queue[name]) {
for (var i = 0; i < queue[name].length; i++) {
registerState(queue[name][i]);
}
}
return state;
}
// Checks text to see if it looks like a glob.
function isGlob (text) {
return text.indexOf('*') > -1;
}
// Returns true if glob matches current $state name.
function doesStateMatchGlob (glob) {
var globSegments = glob.split('.'),
segments = $state.$current.name.split('.');
//match greedy starts
if (globSegments[0] === '**') {
segments = segments.slice(segments.indexOf(globSegments[1]));
segments.unshift('**');
}
//match greedy ends
if (globSegments[globSegments.length - 1] === '**') {
segments.splice(segments.indexOf(globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);
segments.push('**');
}
if (globSegments.length != segments.length) {
return false;
}
//match single stars
for (var i = 0, l = globSegments.length; i < l; i++) {
if (globSegments[i] === '*') {
segments[i] = '*';
}
}
return segments.join('') === globSegments.join('');
}
// Implicit root state that is always active
root = registerState({
name: '',
url: '^',
views: null,
'abstract': true
});
root.navigable = null;
/**
* @ngdoc function
* @name ui.router.state.$stateProvider#decorator
* @methodOf ui.router.state.$stateProvider
*
* @description
* Allows you to extend (carefully) or override (at your own peril) the
* `stateBuilder` object used internally by `$stateProvider`. This can be used
* to add custom functionality to ui-router, for example inferring templateUrl
* based on the state name.
*
* When passing only a name, it returns the current (original or decorated) builder
* function that matches `name`.
*
* The builder functions that can be decorated are listed below. Though not all
* necessarily have a good use case for decoration, that is up to you to decide.
*
* In addition, users can attach custom decorators, which will generate new
* properties within the state's internal definition. There is currently no clear
* use-case for this beyond accessing internal states (i.e. $state.$current),
* however, expect this to become increasingly relevant as we introduce additional
* meta-programming features.
*
* **Warning**: Decorators should not be interdependent because the order of
* execution of the builder functions in non-deterministic. Builder functions
* should only be dependent on the state definition object and super function.
*
*
* Existing builder functions and current return values:
*
* - **parent** `{object}` - returns the parent state object.
* - **data** `{object}` - returns state data, including any inherited data that is not
* overridden by own values (if any).
* - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}
* or `null`.
* - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is
* navigable).
* - **params** `{object}` - returns an array of state params that are ensured to
* be a super-set of parent's params.
* - **views** `{object}` - returns a views object where each key is an absolute view
* name (i.e. "viewName@stateName") and each value is the config object
* (template, controller) for the view. Even when you don't use the views object
* explicitly on a state config, one is still created for you internally.
* So by decorating this builder function you have access to decorating template
* and controller properties.
* - **ownParams** `{object}` - returns an array of params that belong to the state,
* not including any params defined by ancestor states.
* - **path** `{string}` - returns the full path from the root down to this state.
* Needed for state activation.
* - **includes** `{object}` - returns an object that includes every state that
* would pass a `$state.includes()` test.
*
* @example
* <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.
*
* <a id='template'></a>
*
* - **`template`** - {string|function=} - html template as a string or a function that returns
* an html template as a string which should be used by the uiView directives. This property
* takes precedence over templateUrl.
*
* If `template` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateUrl'></a>
*
* - **`templateUrl`** - {string|function=} - path or function that returns a path to an html
* template that should be used by uiView.
*
* If `templateUrl` is a function, it will be called with the following parameters:
*
* - {array.<object>} - state parameters extracted from the current $location.path() by
* applying the current state
*
* <a id='templateProvider'></a>
*
* - **`templateProvider`** - {function=} - Provider function that returns HTML content
* string.
*
* <a id='controller'></a>
*
* - **`controller`** - {string|function=} - Controller fn that should be associated with newly
* related scope or the name of a registered controller if passed as a string.
*
* <a id='controllerProvider'></a>
*
* - **`controllerProvider`** - {function=} - Injectable provider function that returns
* the actual controller or string.
*
* <a id='controllerAs'></a>
*
* - **`controllerAs`** – {string=} – A controller alias name. If present the controller will be
* published to scope under the controllerAs name.
*
* <a id='resolve'></a>
*
* - **`resolve`** - {object.<string, function>=} - An optional map of dependencies which
* should be injected into the controller. If any of these dependencies are promises,
* the router will wait for them all to be resolved or one to be rejected before the
* controller is instantiated. If all the promises are resolved successfully, the values
* of the resolved promises are injected and $stateChangeSuccess event is fired. If any
* of the promises are rejected the $stateChangeError event is fired. The map object is:
*
* - key - {string}: name of dependency to be injected into controller
* - factory - {string|function}: If string then it is alias for service. Otherwise if function,
* it is injected and return value it treated as dependency. If result is a promise, it is
* resolved before its value is injected into controller.
*
* <a id='url'></a>
*
* - **`url`** - {string=} - A url with optional parameters. When a state is navigated or
* transitioned to, the `$stateParams` service will be populated with any
* parameters that were passed.
*
* <a id='params'></a>
*
* - **`params`** - {object=} - An array of parameter names or regular expressions. Only
* use this within a state if you are not using url. Otherwise you can specify your
* parameters within the url. When a state is navigated or transitioned to, the
* $stateParams service will be populated with any parameters that were passed.
*
* <a id='views'></a>
*
* - **`views`** - {object=} - Use the views property to set up multiple views or to target views
* manually/explicitly.
*
* <a id='abstract'></a>
*
* - **`abstract`** - {boolean=} - An abstract state will never be directly activated,
* but can provide inherited properties to its common children states.
*
* <a id='onEnter'></a>
*
* - **`onEnter`** - {object=} - Callback function for when a state is entered. Good way
* to trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='onExit'></a>
*
* - **`onExit`** - {object=} - Callback function for when a state is exited. Good way to
* trigger an action or dispatch an event, such as opening a dialog.
* If minifying your scripts, make sure to use the `['injection1', 'injection2', function(injection1, injection2){}]` syntax.
*
* <a id='reloadOnSearch'></a>
*
* - **`reloadOnSearch = true`** - {boolean=} - If `false`, will not retrigger the same state
* just because a search/query parameter has changed (via $location.search() or $location.hash()).
* Useful for when you'd like to modify $location.search() without triggering a reload.
*
* <a id='data'></a>
*
* - **`data`** - {object=} - Arbitrary data object, useful for custom configuration.
*
* @example
* <pre>
* // Some state name examples
*
* // stateName can be a single top-level name (must be unique).
* $stateProvider.state("home", {});
*
* // Or it can be a nested state name. This state is a child of the
* // above "home" state.
* $stateProvider.state("home.newest", {});
*
* // Nest states as deeply as needed.
* $stateProvider.state("home.newest.abc.xyz.inception", {});
*
* // state() returns $stateProvider, so you can chain state declarations.
* $stateProvider
* .state("home", {})
* .state("about", {})
* .state("contacts", {});
* </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 configuration object.
*/
this.state = state;
function state(name, definition) {
/*jshint validthis: true */
if (isObject(name)) definition = name;
else definition.name = name;
registerState(definition);
return this;
}
/**
* @ngdoc object
* @name ui.router.state.$state
*
* @requires $rootScope
* @requires $q
* @requires ui.router.state.$view
* @requires $injector
* @requires ui.router.util.$resolve
* @requires ui.router.state.$stateParams
* @requires ui.router.router.$urlRouter
*
* @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.
*/
this.$get = $get;
$get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter'];
function $get( $rootScope, $q, $view, $injector, $resolve, $stateParams, $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'));
// Handles the case where a state which is the target of a transition is not found, and the user
// can optionally retry or defer the transition
function handleRedirect(redirect, state, params, options) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateNotFound
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when a requested state **cannot be found** using the provided state name during transition.
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,
* you can see its three properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.
*
* @param {Object} event Event object.
* @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.
* @param {State} fromState Current state object.
* @param {Object} fromParams Current state params.
*
* @example
*
* <pre>
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", {a:1, b:2}, {inherit:false});
*
* // somewhere else
* $scope.$on('$stateNotFound',
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* })
* </pre>
*/
var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);
if (evt.defaultPrevented) {
$urlRouter.update();
return TransitionAborted;
}
if (!evt.retry) {
return null;
}
// Allow the handler to return a promise to defer state lookup retry
if (options.$retry) {
$urlRouter.update();
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;
});
$urlRouter.update();
return retryTransition;
}
root.locals = { resolve: null, globals: { $stateParams: {} } };
$state = {
params: {},
current: root.self,
$current: root,
transition: null
};
/**
* @ngdoc function
* @name ui.router.state.$state#reload
* @methodOf ui.router.state.$state
*
* @description
* A method that force reloads the current state. All resolves are re-resolved, events are not re-fired,
* and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).
*
* @example
* <pre>
* var app angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.reload = function(){
* $state.reload();
* }
* });
* </pre>
*
* `reload()` is just an alias for:
* <pre>
* $state.transitionTo($state.current, $stateParams, {
* reload: true, inherit: false, notify: false
* });
* </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 currently active ancestor states).
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.go('contact.detail');
* };
* });
* </pre>
* <img src='../ngdoc_assets/StateGoExamples.png'/>
*
* @param {string} to Absolute state name or relative state path. Some examples:
*
* - `$state.go('contact.detail')` - will go to the `contact.detail` state
* - `$state.go('^')` - will go to a parent state
* - `$state.go('^.sibling')` - will go to a sibling state
* - `$state.go('.child.grandchild')` - will go to grandchild state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.
* transitioning to a sibling will get you the parameters for all parents, transitioning to a child
* will get you all current parameters, etc.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition.
*
* Possible success values:
*
* - $state.current
*
* <br/>Possible rejection values:
*
* - 'transition superseded' - when a newer transition has been started after this one
* - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener
* - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or
* when a `$stateNotFound` `event.retry` promise errors.
* - 'transition failed' - when a state has been unsuccessfully found after 2 tries.
* - *resolve error* - when an error has occurred with a `resolve`
*
*/
$state.go = function go(to, params, options) {
return this.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}
* uses `transitionTo` internally. `$state.go` is recommended in most situations.
*
* @example
* <pre>
* var app = angular.module('app', ['ui.router']);
*
* app.controller('ctrl', function ($scope, $state) {
* $scope.changeState = function () {
* $state.transitionTo('contact.detail');
* };
* });
* </pre>
*
* @param {string} to State name.
* @param {object=} toParams A map of the parameters that will be sent to the state,
* will populate $stateParams.
* @param {object=} options Options object. The options are:
*
* - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`
* will not. If string, must be `"replace"`, which will update url and also replace last history record.
* - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.
* - **`relative`** - {object=}, When transitioning with relative path (e.g '^'),
* defines which state to be relative from.
* - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.
* - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params
* have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd
* use this when you want to force a reload when *everything* is the same, including search params.
*
* @returns {promise} A promise representing the state of the new transition. See
* {@link ui.router.state.$state#methods_go $state.go}.
*/
$state.transitionTo = function transitionTo(to, toParams, options) {
toParams = toParams || {};
options = extend({
location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false
}, options || {});
var from = $state.$current, fromParams = $state.params, fromPath = from.path;
var evt, toState = findState(to, options.relative);
if (!isDefined(toState)) {
var redirect = { to: to, toParams: toParams, options: options };
var redirectResult = handleRedirect(redirect, from.self, fromParams, options);
if (redirectResult) {
return redirectResult;
}
// 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("No such state '" + to + "'");
throw new Error("Could not resolve '" + to + "' from state '" + options.relative + "'");
}
}
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 = 0, state = toPath[keep], locals = root.locals, toLocals = [];
if (!options.reload) {
while (state && state === fromPath[keep] && equalForKeys(toParams, fromParams, state.ownParams)) {
locals = toLocals[keep] = state.locals;
keep++;
state = toPath[keep];
}
}
// 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) $urlRouter.update();
$state.transition = null;
return $q.when($state.current);
}
// Filter parameters before we pass them to event handlers etc.
toParams = filterByKeys(objectKeys(to.params), toParams || {});
// Broadcast start event and cancel the transition if requested
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeStart
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when the state transition **begins**. You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*
* @example
*
* <pre>
* $rootScope.$on('$stateChangeStart',
* function(event, toState, toParams, fromState, fromParams){
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* </pre>
*/
if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {
$urlRouter.update();
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;
if (options.location && to.navigable) {
$urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {
replace: options.location === 'replace'
});
}
if (options.notify) {
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeSuccess
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired once the state transition is **complete**.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
*/
$rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);
}
$urlRouter.update(true);
return $state.current;
}, function (error) {
if ($state.transition !== transition) return TransitionSuperseded;
$state.transition = null;
/**
* @ngdoc event
* @name ui.router.state.$state#$stateChangeError
* @eventOf ui.router.state.$state
* @eventType broadcast on root scope
* @description
* Fired when an **error occurs** during transition. It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* @param {Object} event Event object.
* @param {State} toState The state being transitioned to.
* @param {Object} toParams The params supplied to the `toState`.
* @param {State} fromState The current state, pre-transition.
* @param {Object} fromParams The params supplied to the `fromState`.
* @param {Error} error The resolve error object.
*/
evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
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.$current.name = 'contacts.details.item';
*
* // absolute name
* $state.is('contact.details.item'); // returns true
* $state.is(contactDetailItemStateObject); // returns true
*
* // relative name (. and ^), typically from a template
* // E.g. from the 'contacts.details' template
* <div ng-class="{highlighted: $state.is('.item')}">Item</div>
* </pre>
*
* @param {string|object} stateName The state name (absolute or relative) or state object you'd like to check.
* @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like
* to test against the current active state.
* @returns {boolean} Returns true if it is the state.
*/
$state.is = function is(stateOrName, params) {
var state = findState(stateOrName);
if (!isDefined(state)) {
return undefined;
}