From ecefb758cb445e41620b62a272aafa3638613d7a Mon Sep 17 00:00:00 2001 From: Robert Pocklington Date: Sat, 28 Mar 2015 21:09:32 +1100 Subject: [PATCH] feat($state): broadcast $stateChangeCancel event when event.preventDefault() is called in $stateChangeStart handler --- src/state.js | 1 + test/stateSpec.js | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/state.js b/src/state.js index 730e719f8..ca1ead9d4 100644 --- a/src/state.js +++ b/src/state.js @@ -1028,6 +1028,7 @@ function $StateProvider( $urlRouterProvider, $urlMatcherFactory) { * */ if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) { + $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams); $urlRouter.update(); return TransitionPrevented; } diff --git a/test/stateSpec.js b/test/stateSpec.js index 77c9373c6..2cba88ec4 100644 --- a/test/stateSpec.js +++ b/test/stateSpec.js @@ -123,6 +123,7 @@ describe('state', function () { log = ''; logEvents = logEnterExit = false; $rootScope.$on('$stateChangeStart', eventLogger); + $rootScope.$on('$stateChangeCancel', eventLogger); $rootScope.$on('$stateChangeSuccess', eventLogger); $rootScope.$on('$stateChangeError', eventLogger); $rootScope.$on('$stateNotFound', eventLogger); @@ -215,6 +216,25 @@ describe('state', function () { expect(resolvedError(promise)).toBeTruthy(); })); + it('can be cancelled by preventDefault() in $stateChangeStart and broadcasts $stateChangeCancel', inject(function ($state, $q, $rootScope) { + initStateTo(A); + var called, cancelEventCalled; + $rootScope.$on('$stateChangeStart', function (ev) { + ev.preventDefault(); + called = true; + }); + $rootScope.$on('$stateChangeCancel', function (ev) { + ev.preventDefault(); + cancelEventCalled = true; + }); + var promise = $state.transitionTo(B, {}); + $q.flush(); + expect(called).toBeTruthy(); + expect(cancelEventCalled).toBeTruthy(); + expect($state.current).toBe(A); + expect(resolvedError(promise)).toBeTruthy(); + })); + it('triggers $stateNotFound', inject(function ($state, $q, $rootScope) { initStateTo(E, { i: 'iii' }); var called;