In my controller, I have two modals that are launched. The code for one of them is:
function setUpEditCommentModal() {
$ionicModal.fromTemplateUrl('app/recent/edit-comment-modal.html', {
scope: $scope, // so close methods available.
animation: 'fade-in-scale'
}).then(function (modal) {
$scope.editCommentModal = modal;
});
$scope.closeEditCommentModal = function () {
$scope.editCommentModal.hide();
};
$scope.returnFromSavingCommentInModal = function () {
var modifiedComment = commentSelector.getComment();
vm.selectedComment.Comment = modifiedComment.Comment; // just note part.
$scope.closeEditCommentModal();
};
//Cleanup the modal when we're done with it!
$scope.$on('$destroy', function () {
$scope.editCommentModal.remove();
});
// Execute action on hide modal
$scope.$on('modal.hidden', function () {
// Execute action
$ionicListDelegate.closeOptionButtons();
});
// Execute action on remove modal
$scope.$on('modal.removed', function () {
// Execute action
});
}
and the other modal code is even longer. What is the best way to refactor this code so that my controller class is not too big?
Should I move this code into a service?
You can create a
ModalService
which will have aregister()
method. This can register multiple modals at a time and return a promise. The ressolved value of the promise can be either saved locally or can be used by reference from the service. In order to use it via reference, we need to store a list of all the currently active modals in the service. The service will look something like below:The simpler implementation for 2 modals in a controller using the above factory is present in this JSBin: https://jsbin.com/busepey/2/edit?html,js,output. Additionally you can implement the list of active modals in a local array within the service and add or remove based on new/ deleted modals.
UPDATE: Service for reusable method to show modals : https://forum.ionicframework.com/t/ionic-modal-service-with-extras/15357