我有类似的要求。我需要:
- 触发路由更改的模态窗口,因此它有自己的哈希 url。
- 当您访问模态 url 时,主屏幕加载然后触发模态弹出。
- 后退按钮关闭模式(假设您从主屏幕开始)。
- 当您单击“确定”或“取消”时,模式关闭并且路线更改回主屏幕。
- 当您单击背景关闭模式时,路线会变回主屏幕。
我找不到所有这些一起工作的好例子,但我能找到零碎的例子,所以我把它们放在一个工作示例中,如下所示:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.11/angular-ui-router.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.11.2/ui-bootstrap-tpls.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.css" rel="stylesheet">
<script>
// init the app with ui.router and ui.bootstrap modules
var app = angular.module('app', ['ui.router', 'ui.bootstrap']);
// make back button handle closing the modal
app.run(['$rootScope', '$modalStack',
function($rootScope, $modalStack) {
$rootScope.$on('$stateChangeStart', function() {
var top = $modalStack.getTop();
if (top) {
$modalStack.dismiss(top.key);
}
});
}
]);
// configure the stateProvider
app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// default page to be "/" (home)
$urlRouterProvider.otherwise('/');
// configure the route states
$stateProvider
// define home route "/"
.state('home', {
url: '/'
})
// define modal route "/modal"
.state('modal', {
url: '/modal',
// trigger the modal to open when this route is active
onEnter: ['$stateParams', '$state', '$modal',
function($stateParams, $state, $modal) {
$modal
// handle modal open
.open({
template: '<div class="modal-header"><h3 class="modal-title">Modal</h3></div><div class="modal-body">The modal body...</div><div class="modal-footer"><button class="btn btn-primary" ng-click="ok()">OK</button><button class="btn btn-warning" ng-click="cancel()">Cancel</button></div>',
controller: ['$scope',
function($scope) {
// handle after clicking Cancel button
$scope.cancel = function() {
$scope.$dismiss();
};
// close modal after clicking OK button
$scope.ok = function() {
$scope.$close(true);
};
}
]
})
// change route after modal result
.result.then(function() {
// change route after clicking OK button
$state.transitionTo('home');
}, function() {
// change route after clicking Cancel button or clicking background
$state.transitionTo('home');
});
}
]
});
}
]);
</script>
</head>
<body>
<a href="#/modal" class="btn btn-default">POPUP!</a>
<div ui-view></div>
</body>
</html>
您可以在 plunker 查看它的实际操作:http:
//plnkr.co/edit/tLyfRP6sx9C9Vee7pOfC
单击 plunker 中的“打开嵌入式视图”链接以查看哈希标签的工作情况。