Skip to content

Instantly share code, notes, and snippets.

@jkristoffer
Last active August 10, 2017 08:02
Show Gist options
  • Save jkristoffer/ef203b17418959136a51f6c1c1c8183e to your computer and use it in GitHub Desktop.
Save jkristoffer/ef203b17418959136a51f6c1c1c8183e to your computer and use it in GitHub Desktop.
Angular 1.5.x Bootstap-like Dialog Service in Typescript
/// <reference path="./index.d.ts" />
import * as ng from 'angular';
let style = require('./dialog.scss');
const DialogComponentModule = ng.module('Components.dialog', []);
let dialogService: ng.Injectable<Function> = function (
$document: ng.IDocumentService,
$compile: ng.ICompileService,
$controller: ng.IControllerService,
$templateRequest: ng.ITemplateRequestService,
$rootScope: ng.IRootScopeService,
$q: ng.IQService) {
'ngInject';
const $body = $document.find('body');
let dialogService: DialogService = {
open: function (options: dialogOptions) {
let $ctrlAs = '$ctrl';
let closeEventInit = $e => () => ($e.remove(), !!options.onClose && options.onClose());
let decorateTemplate = tpl => `<div class="${style.dialog}"> ${tpl} </div> `;
const $p: ng.IPromise<any> = $q((resolve, reject) => {
if (!!options.template) resolve(options.template);
else if (!!options.templateUrl) resolve($templateRequest(options.templateUrl));
else reject('No template/templateURL found!');
})
.then(decorateTemplate)
.then((template: string) => {
let controller = options.controller || function () { };
let _scope = $rootScope.$new();
let controllerInitFn: any = $controller(options.controller, { '$scope': _scope }, true, $ctrlAs);
let $elem = $compile(template)(_scope);
$body.append($elem);
let closeFn = closeEventInit($elem);
controllerInitFn['instance']['close'] = closeFn;
controllerInitFn();
return closeFn;
})
.catch(err => console.error(err));
return {
close: () => $p.then(closeFn => closeFn())
}
}
}
return dialogService;
};
DialogComponentModule.service('dialogService', dialogService);
export const Dialog = DialogComponentModule.name;
type dialogOptions = {
template?: string
templateUrl?: string
onClose?: Function
controller: angular.IControllerConstructor
}
type DialogService = {
open(dialogOptions): {
close: () => ng.IPromise<any>
}
}
.dialog {
position: fixed;
top: 100px;
min-width: 400px;
height: auto;
max-height: 600px;
overflow: auto;
background: #fff;
left: calc(50%);
z-index: 1000;
box-shadow: (-2px) 2px 6px rgba(0, 0, 0, 0.25), 0px 0px 50px rgba(0, 0, 0, 0.15), 0 0 0 2000px rgba(0, 0, 0, 0.25);
transform: translateX(-50%);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment