关闭模态框实例导致路由跳转至默认状态的问题求助
Hey there, let's break down why this is happening and how to fix it—this is a super common gotcha when working with AngularJS UI-Router and modals (especially UI Bootstrap modals).
The most likely culprit is unblocked default browser behavior from your modal's cancel button:
- If your cancel button is an
<a>tag withhref="#", clicking it tells the browser to jump to the page's anchor point (#). UI-Router interprets this as a route change, and since there's no valid route matching#, your$urlRouterProvider.otherwise('/state1/welcome')kicks in and redirects you to the default route. - Even with a
<button>tag, if you haven't handled the click event properly, it can accidentally trigger route-related default behavior (though this is less common).
Another possible cause: if you've added route-jumping logic (like $state.go()) in the modal's close callbacks (e.g., the catch block of modalInstance.result), that would also force a redirect.
Here are reliable fixes, ordered by simplicity:
1. Fix the Button's HTML Structure
The easiest fix is to avoid tags with built-in navigation behavior:
- Replace
<a href="#" ng-click="cancel()">Cancel</a>with a<button>tag—buttons don't trigger navigation by default:<button ng-click="cancel()">Cancel</button> - If you must use an
<a>tag, replacehref="#"withhref="javascript:void(0)"to disable default navigation:<a href="javascript:void(0)" ng-click="cancel()">Cancel</a>
2. Prevent Default Behavior in the Click Event
If you don't want to change the tag structure, block the browser's default behavior directly in the ng-click or controller function:
- In the template, add
$event.preventDefault()to the click handler:<button ng-click="cancel(); $event.preventDefault()">Cancel</button> - Or handle it in the controller by accepting the
$eventparameter:
Then pass the event in the template:$scope.cancel = function($event) { // Block the browser's default action $event.preventDefault(); // Close the modal $scope.modalInstance.dismiss("Cancel"); };<button ng-click="cancel($event)">Cancel</button>
3. Check Modal Close Callbacks for Route Logic
Double-check your controller code for accidental route jumps in modal close callbacks. For example:
$scope.modalInstance.result.catch(function(reason) { // If you have code like $state.go('/state1/welcome') here, it will cause the redirect // Remove or modify this logic });
Delete any unintended route-jumping code here.
4. Verify Your Route State Configuration
Make sure your state2.welcome state is configured correctly to avoid UI-Router losing track of the current state:
$stateProvider .state('state2', { abstract: true, templateUrl: 'state2.html' }) .state('state2.welcome', { url: '/welcome', templateUrl: 'state2-welcome.html' });
Ensure parent and child state structures are properly defined so UI-Router can maintain the state2.welcome state after the modal closes.
内容的提问来源于stack exchange,提问作者Instinct

