Skip to content

Instantly share code, notes, and snippets.

@mlegenhausen
Created May 6, 2015 10:28
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlegenhausen/1043c6d12bc596032e3f to your computer and use it in GitHub Desktop.
Save mlegenhausen/1043c6d12bc596032e3f to your computer and use it in GitHub Desktop.
Ionic Modal Directive

This directive allows you to write you modal windows inline in your html code without writing the same boilerplate code for open and closing a popup. It also supports view caching and is scope destroy aware so you do not need to hide it manually when you switching a view.

<html>
<head>
<title>Modal Directive</title>
</head>
<body>
<modal show="true">
<ion-modal-view>
<ion-header-bar>
<h1 class="title">My Modal title</h1>
</ion-header-bar>
<ion-content>
Hello!
</ion-content>
</ion-modal-view>
</modal>
</body>
</html>
import _ from 'lodash';
import angular from 'angular';
export default angular.module('directives.modal', [])
.directive('modal', ModalDirective);
ModalDirective.$inject = ['$rootScope', '$ionicModal'];
function ModalDirective($rootScope, $ionicModal) {
return {
restrict: 'E',
scope: {
show: '=',
animate: '@'
},
compile
};
function compile(element) {
// Get original html code before angular processes it
const template = _.pluck(element.children(), 'outerHTML').join('');
// Remove the content from the DOM
element.empty();
return scope => {
const modal = $ionicModal.fromTemplate(template, {
scope: scope.$parent,
animate: scope.animate
});
// Listen to view leave events
scope.$on('$destroy', $rootScope.$on('$ionicView.beforeLeave', () => modal.hide()));
// Listen to scope destroy events
scope.$on('$destroy', () => modal.remove());
scope.$watch('show', show => modal[show ? 'show' : 'hide']());
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment