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.
Created
May 6, 2015 10:28
-
-
Save mlegenhausen/1043c6d12bc596032e3f to your computer and use it in GitHub Desktop.
Ionic Modal Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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