Skip to content

Commit f8ac46e

Browse files
committed
fix 1699: support preventDefault() for $routeChangeStart
1 parent b7b08ee commit f8ac46e

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/ng/route.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,11 @@ function $RouteProvider(){
275275
* defined in `resolve` route property. Once all of the dependencies are resolved
276276
* `$routeChangeSuccess` is fired.
277277
*
278+
* Call event.preventDefault() to prevent changing route but leave the browser Url
279+
* to it's new location (as opposed to calling event.preventDefault() on $location's
280+
* $locationChangeStart event which cancels changing the browser's Url).
281+
*
282+
*
278283
* @param {Route} next Future route information.
279284
* @param {Route} current Current route information.
280285
*/
@@ -405,7 +410,9 @@ function $RouteProvider(){
405410
$rootScope.$broadcast('$routeUpdate', last);
406411
} else if (next || last) {
407412
forceReload = false;
408-
$rootScope.$broadcast('$routeChangeStart', next, last);
413+
if ( $rootScope.$broadcast('$routeChangeStart', next, last).defaultPrevented ){
414+
return;
415+
}
409416
$route.current = next;
410417
if (next) {
411418
if (next.redirectTo) {

test/ng/routeSpec.js

+22
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,28 @@ describe('$route', function() {
205205
});
206206

207207

208+
it('should not change route when $routeChangeStart is canceled', function() {
209+
module(function($routeProvider) {
210+
$routeProvider.when('/somePath', {template: 'some path'});
211+
});
212+
inject(function($route, $location, $rootScope, $log) {
213+
$rootScope.$on('$routeChangeStart', function(event) {
214+
$log.info('$routeChangeStart');
215+
event.preventDefault();
216+
});
217+
218+
$rootScope.$on('$routeChangeSuccess', function(event) {
219+
throw new Error('Should not get here');
220+
});
221+
222+
$location.path('/somePath');
223+
$rootScope.$digest();
224+
225+
expect($log.info.logs.shift()).toEqual(['$routeChangeStart']);
226+
});
227+
});
228+
229+
208230
describe('should match a route that contains special chars in the path', function() {
209231
beforeEach(module(function($routeProvider) {
210232
$routeProvider.when('/$test.23/foo*(bar)/:baz', {templateUrl: 'test.html'});

0 commit comments

Comments
 (0)