Modals In Ionic Framework 2
27 Mar 2016One of the nice improvements of ionic framework 2 over the first version, is how it handles modals.
In Ionic 1, you had to define and create a modal within your controller:
angular.module('testApp', ['ionic'])
.controller('MyController', function($scope, $ionicModal) {
$ionicModal.fromTemplateUrl('my-modal.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.modal = modal;
});
$scope.openModal = function() {
$scope.modal.show();
};
$scope.closeModal = function() {
$scope.modal.hide();
};
});
If the modal had custom code, you would probably place it in the controller of the page that was calling it.
To avoid cluttering the controller, and to reuse the modal across the app, you had to:
- Define the modal as a directive and have it listen to an event to appear. Or:
- Wrap the modal as a service and show it from the controller
Both of these solutions weren't optimal.
Ionic 2 handles modals in a much better way. First, you define the modal as a Page like you would define any other screen of the app.
A ts file:
import {Page, ViewController} from 'ionic-angular';
@Page({
templateUrl: 'build/pages/sample-modal/sample-modal.html'
})
export class SampleModalPage {
constructor(private viewCtrl: ViewController) {
}
dismiss(data) {
this.viewCtrl.dismiss(data);
}
}
And a template:
<ion-navbar *navbar>
<ion-buttons start>
<button (click)="dismiss()">
Cancel
</button>
</ion-buttons>
<ion-title>Sample Modal</ion-title>
</ion-navbar>
<ion-content padding class="sample-modal-page">
my sample modal page
</ion-content>
This way, any logic this modal requires, can be defined on its own page and this modal can be easily reused across the app.
Then, show the modal from another page:
export class AnotherPage {
constructor(private nav: NavController) {}
showModal() {
const modal = Modal.create(SampleModalPage);
this.nav.present(modal);
}
}