3 * @name ui.router.router.$urlRouterProvider
5 * @requires ui.router.util.$urlMatcherFactoryProvider
6 * @requires $locationProvider
9 * `$urlRouterProvider` has the responsibility of watching `$location`.
10 * When `$location` changes it runs through a list of rules one by one until a
11 * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify
12 * a url in a state configuration. All urls are compiled into a UrlMatcher object.
14 * There are several methods on `$urlRouterProvider` that make it useful to use directly
15 * in your module config.
17 $UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
18 function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {
19 var rules = [], otherwise = null, interceptDeferred = false, listener;
21 // Returns a string that is a prefix of all strings matching the RegExp
22 function regExpPrefix(re) {
23 var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
24 return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
27 // Interpolates matched values into a String.replace()-style pattern
28 function interpolate(pattern, match) {
29 return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
30 return match[what === '$' ? 0 : Number(what)];
36 * @name ui.router.router.$urlRouterProvider#rule
37 * @methodOf ui.router.router.$urlRouterProvider
40 * Defines rules that are used by `$urlRouterProvider` to find matches for
45 * var app = angular.module('app', ['ui.router.router']);
47 * app.config(function ($urlRouterProvider) {
48 * // Here's an example of how you might allow case insensitive urls
49 * $urlRouterProvider.rule(function ($injector, $location) {
50 * var path = $location.path(),
51 * normalized = path.toLowerCase();
53 * if (path !== normalized) {
60 * @param {object} rule Handler function that takes `$injector` and `$location`
61 * services as arguments. You can use them to return a valid path as a string.
63 * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
65 this.rule = function (rule) {
66 if (!isFunction(rule)) throw new Error("'rule' must be a function");
73 * @name ui.router.router.$urlRouterProvider#otherwise
74 * @methodOf ui.router.router.$urlRouterProvider
77 * Defines a path that is used when an invalid route is requested.
81 * var app = angular.module('app', ['ui.router.router']);
83 * app.config(function ($urlRouterProvider) {
84 * // if the path doesn't match any of the urls you configured
85 * // otherwise will take care of routing the user to the
87 * $urlRouterProvider.otherwise('/index');
89 * // Example of using function rule as param
90 * $urlRouterProvider.otherwise(function ($injector, $location) {
91 * return '/a/valid/url';
96 * @param {string|object} rule The url path you want to redirect to or a function
97 * rule that returns the url path. The function version is passed two params:
98 * `$injector` and `$location` services, and must return a url string.
100 * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance
102 this.otherwise = function (rule) {
103 if (isString(rule)) {
105 rule = function () { return redirect; };
107 else if (!isFunction(rule)) throw new Error("'rule' must be a function");
113 function handleIfMatch($injector, handler, match) {
114 if (!match) return false;
115 var result = $injector.invoke(handler, handler, { $match: match });
116 return isDefined(result) ? result : true;
121 * @name ui.router.router.$urlRouterProvider#when
122 * @methodOf ui.router.router.$urlRouterProvider
125 * Registers a handler for a given url matching. if handle is a string, it is
126 * treated as a redirect, and is interpolated according to the syntax of match
127 * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).
129 * If the handler is a function, it is injectable. It gets invoked if `$location`
130 * matches. You have the option of inject the match object as `$match`.
132 * The handler can return
134 * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`
135 * will continue trying to find another one that matches.
136 * - **string** which is treated as a redirect and passed to `$location.url()`
137 * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.
141 * var app = angular.module('app', ['ui.router.router']);
143 * app.config(function ($urlRouterProvider) {
144 * $urlRouterProvider.when($state.url, function ($match, $stateParams) {
145 * if ($state.$current.navigable !== state ||
146 * !equalForKeys($match, $stateParams) {
147 * $state.transitionTo(state, $match, false);
153 * @param {string|object} what The incoming path that you want to redirect.
154 * @param {string|object} handler The path you want to redirect your user to.
156 this.when = function (what, handler) {
157 var redirect, handlerIsString = isString(handler);
158 if (isString(what)) what = $urlMatcherFactory.compile(what);
160 if (!handlerIsString && !isFunction(handler) && !isArray(handler))
161 throw new Error("invalid 'handler' in when()");
164 matcher: function (what, handler) {
165 if (handlerIsString) {
166 redirect = $urlMatcherFactory.compile(handler);
167 handler = ['$match', function ($match) { return redirect.format($match); }];
169 return extend(function ($injector, $location) {
170 return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
172 prefix: isString(what.prefix) ? what.prefix : ''
175 regex: function (what, handler) {
176 if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
178 if (handlerIsString) {
180 handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
182 return extend(function ($injector, $location) {
183 return handleIfMatch($injector, handler, what.exec($location.path()));
185 prefix: regExpPrefix(what)
190 var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
192 for (var n in check) {
193 if (check[n]) return this.rule(strategies[n](what, handler));
196 throw new Error("invalid 'what' in when()");
201 * @name ui.router.router.$urlRouterProvider#deferIntercept
202 * @methodOf ui.router.router.$urlRouterProvider
205 * Disables (or enables) deferring location change interception.
207 * If you wish to customize the behavior of syncing the URL (for example, if you wish to
208 * defer a transition but maintain the current URL), call this method at configuration time.
209 * Then, at run time, call `$urlRouter.listen()` after you have configured your own
210 * `$locationChangeSuccess` event handler.
214 * var app = angular.module('app', ['ui.router.router']);
216 * app.config(function ($urlRouterProvider) {
218 * // Prevent $urlRouter from automatically intercepting URL changes;
219 * // this allows you to configure custom behavior in between
220 * // location changes and route synchronization:
221 * $urlRouterProvider.deferIntercept();
223 * }).run(function ($rootScope, $urlRouter, UserService) {
225 * $rootScope.$on('$locationChangeSuccess', function(e) {
226 * // UserService is an example service for managing user state
227 * if (UserService.isLoggedIn()) return;
229 * // Prevent $urlRouter's default handler from firing
230 * e.preventDefault();
232 * UserService.handleLogin().then(function() {
233 * // Once the user has logged in, sync the current URL
239 * // Configures $urlRouter's listener *after* your custom listener
240 * $urlRouter.listen();
244 * @param {boolean} defer Indicates whether to defer location change interception. Passing
245 no parameter is equivalent to `true`.
247 this.deferIntercept = function (defer) {
248 if (defer === undefined) defer = true;
249 interceptDeferred = defer;
254 * @name ui.router.router.$urlRouter
256 * @requires $location
257 * @requires $rootScope
258 * @requires $injector
265 $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
266 function $get( $location, $rootScope, $injector, $browser) {
268 var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;
270 function appendBasePath(url, isHtml5, absolute) {
271 if (baseHref === '/') return url;
272 if (isHtml5) return baseHref.slice(0, -1) + url;
273 if (absolute) return baseHref.slice(1) + url;
277 // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
278 function update(evt) {
279 if (evt && evt.defaultPrevented) return;
280 var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;
281 lastPushedUrl = undefined;
282 if (ignoreUpdate) return true;
284 function check(rule) {
285 var handled = rule($injector, $location);
287 if (!handled) return false;
288 if (isString(handled)) $location.replace().url(handled);
291 var n = rules.length, i;
293 for (i = 0; i < n; i++) {
294 if (check(rules[i])) return;
296 // always check otherwise last to allow dynamic updates to the set of rules
297 if (otherwise) check(otherwise);
301 listener = listener || $rootScope.$on('$locationChangeSuccess', update);
305 if (!interceptDeferred) listen();
310 * @name ui.router.router.$urlRouter#sync
311 * @methodOf ui.router.router.$urlRouter
314 * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.
315 * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,
316 * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed
317 * with the transition by calling `$urlRouter.sync()`.
321 * angular.module('app', ['ui.router'])
322 * .run(function($rootScope, $urlRouter) {
323 * $rootScope.$on('$locationChangeSuccess', function(evt) {
324 * // Halt state change from even starting
325 * evt.preventDefault();
326 * // Perform custom logic
327 * var meetsRequirement = ...
328 * // Continue with the update and state transition if logic allows
329 * if (meetsRequirement) $urlRouter.sync();
342 update: function(read) {
344 location = $location.url();
347 if ($location.url() === location) return;
349 $location.url(location);
353 push: function(urlMatcher, params, options) {
354 $location.url(urlMatcher.format(params || {}));
355 lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;
356 if (options && options.replace) $location.replace();
361 * @name ui.router.router.$urlRouter#href
362 * @methodOf ui.router.router.$urlRouter
365 * A URL generation method that returns the compiled URL for a given
366 * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.
370 * $bob = $urlRouter.href(new UrlMatcher("/about/:person"), {
373 * // $bob == "/about/bob";
376 * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.
377 * @param {object=} params An object of parameter values to fill the matcher's required parameters.
378 * @param {object=} options Options object. The options are:
380 * - **`absolute`** - {boolean=false}, If true will generate an absolute url, e.g. "http://www.example.com/fullurl".
382 * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`
384 href: function(urlMatcher, params, options) {
385 if (!urlMatcher.validates(params)) return null;
387 var isHtml5 = $locationProvider.html5Mode();
388 if (angular.isObject(isHtml5)) {
389 isHtml5 = isHtml5.enabled;
392 var url = urlMatcher.format(params);
393 options = options || {};
395 if (!isHtml5 && url !== null) {
396 url = "#" + $locationProvider.hashPrefix() + url;
398 url = appendBasePath(url, isHtml5, options.absolute);
400 if (!options.absolute || !url) {
404 var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();
405 port = (port === 80 || port === 443 ? '' : ':' + port);
407 return [$location.protocol(), '://', $location.host(), port, slash, url].join('');
413 angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);