tobbbe
9/9/2016 - 9:39 AM

Modal service

angular.module('app').factory('ModalService', function($compile) {
    const initilized = false;
    const bodyEl = angular.element(document.querySelector('body'));
    const htmlEl = angular.element(document.querySelector('html'));
    const backdropEl = angular.element('<div id="modal-backdrop"></div>').css({
        position: 'fixed', 
        top: '0',
        bottom: '0',
        left: '0',
        width: '100%',
        background: 'rgba(0,0,0,.7)',
        'z-index': '10000',
        visibility: 'hidden',
        opacity: 0,
        transition: 'opacity .1s'
    })
    const contentEl = angular.element('<div id="modal-content"></div>').css({
        width: '80%',
        'max-height': '80%',
        background: '#fff',
        padding: '5%',
        'overflow-y': 'auto',
        position: 'absolute',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%, -50%)',
        '-ms-transform': 'translate(-50%, -50%)'
    })

    bodyEl.append(backdropEl)
    backdropEl.append(contentEl)

    backdropEl.on('click', (e) => {
        if (e.target.id === 'modal-backdrop') {
            hide();
        }        
    })
    
    function show(content, scope) {
        if (scope) {
            contentEl.append($compile(content)(scope))
        }
        else {
            contentEl.append(content)
        }
        backdropEl.css({ visibility: 'visible', opacity: 1 })
        htmlEl.css({ overflow: 'hidden' })
    }

    function hide() {
        backdropEl.css({visibility:'hidden', opacity: 0})        
        htmlEl.css({overflow: ''})
        contentEl.empty()
    }

    return {
        show,
        hide
    }
})