同様の要件がありました。必要だった:
- ルートへの変更をトリガーするモーダル ウィンドウ。独自のハッシュ URL があります。
- モーダル URL にアクセスすると、メイン画面が読み込まれ、モーダルが popop にトリガーされます。
- 戻るボタンはモーダルを閉じます (ホーム画面から開始したと仮定します)。
- [OK] または [キャンセル] をクリックすると、モーダルが閉じられ、ルートがホーム画面に戻ります。
- 背景をクリックしてモーダルを閉じると、ルートがホーム画面に戻ります。
これらすべてが連携して動作する良い例は見つかりませんでしたが、断片的な例を見つけることができたので、次のようにそれらをすべてまとめて動作例にしました。
<!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>
plunkr.co/edit/tLyfRP6sx9C9Vee7pOfC:
plunkr.co/edit/tLyfRP6sx9C9Vee7pOfC
plunker の [埋め込みビューを開く] リンクをクリックして、ハッシュ タグが機能していることを確認します。