Disclaimer: Originally this was answer on stackoverflow... Question was removed, so - answer was not published. But it is good as an example how to do modals or something like in angular
At first, take a look at ui-bootstrap modal implementation, it is a good example how modals can be implemented in angular.
Recently, I have some experience implementing my own modals for states in ui-router
, my implementation was inspired by ui-bootstrap modal.
Main part is modal
service(js file below), it is responsible for:
- template loading
- resolving and injection parameters for modal controller
- creating scope, displaying modal (add compiled template into DOM, applying some styles required to properly display it...)
- closing modal (removing modal from DOM, destroying scope...)
This service can be used without ui-router - it just displays modal.
Example of use:
app.controller('MainCtrl', function($scope, modal) {
var counter = 0;
$scope.openModal = function(){
modal({
template:'<div class="modal"> Hello from modal <button ng-click="close()">x</button></div>',
resolve:{...},
controller:function($scope, $modalInstance, ...){
$scope.close = function(){
$modalInstance.close('name from modal #'+number);
}
}
}).then(function(modalInstance){
modalInstance.open().then(function(v){
// do something when modal was closed
});
});
}
});
template:
<div ng-controller="MainCtrl">
<button ng-click="openModal()">Open Modal</button>
</div>
To use this modal service with ui-router state, you can onEnter
and onExit
callbacks and resolve for state:
$stateProvider.state('modal', {
url: '/modal',
resolve: {
modalInstance: function (modal) {
return modal({
templateUrl: 'views/modal.html',
controller: 'ModalCtrl'
});
}
},
onEnter: function (modalInstance) {
modalInstance.open();
},
onExit: function (modalInstance) {
modalInstance.close();
}
})