• Stars
    star
    629
  • Rank 69,043 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Modal service for AngularJS - supports creating popups and modals via a service.

angular-modal-service

CircleCI codecov Dependencies Dev Dependencies Greenkeeper badge GuardRails badge

Modal service for AngularJS - supports creating popups and modals via a service. Full support for Angular 1.5+ components. See a quick fiddle or a full set of samples at dwmkerr.github.io/angular-modal-service.

Usage

Install with Bower (or NPM):

bower install angular-modal-service
# or...
npm install angular-modal-service

Then reference the minified script:

<script src="bower_components/angular-modal-service/dst/angular-modal-service.min.js"></script>

Specify the modal service as a dependency of your application:

var app = angular.module('sampleapp', ['angularModalService']);

Now just inject the modal service into any controller, service or directive where you need it.

app.controller('SampleController', ["$scope", "ModalService", function($scope, ModalService) {

  $scope.showAModal = function() {

  	// Just provide a template url, a controller and call 'showModal'.
    ModalService.showModal({
      templateUrl: "yesno/yesno.html",
      controller: "YesNoController"
    }).then(function(modal) {
      // The modal object has the element built, if this is a bootstrap modal
      // you can call 'modal' to show it, if it's a custom modal just show or hide
      // it as you need to.
      modal.element.modal();
      modal.close.then(function(result) {
        $scope.message = result ? "You said Yes" : "You said No";
      });
    });

  };

}]);

Calling showModal returns a promise which is resolved when the modal DOM element is created and the controller for it is created. The promise returns a modal object which contains the element created, the controller, the scope and two promises: close and closed. Both are resolved to the result of the modal close function, but close is resolved as soon as the modal close function is called, while closed is only resolved once the modal has finished animating and has been completely removed from the DOM.

The modal controller can be any controller that you like, just remember that it is always provided with one extra parameter - the close function. Here's an example controller for a bootstrap modal:

app.controller('SampleModalController', function($scope, close) {

 $scope.dismissModal = function(result) {
 	close(result, 200); // close, but give 200ms for bootstrap to animate
 };

});

The close function is automatically injected to the modal controller and takes the result object (which is passed to the close and closed promises used by the caller). It can take an optional second parameter, the number of milliseconds to wait before destroying the DOM element. This is so that you can have a delay before destroying the DOM element if you are animating the closure. See Global Config for setting a default delay.

Now just make sure the close function is called by your modal controller when the modal should be closed and that's it. Quick hint - if you are using Bootstrap for your modals, then make sure the modal template only contains one root level element, see the FAQ for the gritty details of why.

To pass data into the modal controller, use the inputs field of the modal options. For example:

ModalService.showModal({
  templateUrl: "exampletemplate.html",
  controller: "ExampleController",
  inputs: {
    name: "Fry",
    year: 3001
  }
})

injects the name and year values into the controller:

app.controller('ExampleController', function($scope, name, year, close) {
});

You can also provide a controller function directly to the modal, with or without the controllerAs attribute. But if you provide controller attribute with as syntax and controllerAs attribute together, controllerAs will have high priority.

ModalService.showModal({
  template: "<div>Fry lives in {{futurama.city}}</div>",
  controller: function() {
    this.city = "New New York";
  },
  controllerAs : "futurama"
})

Support for AngularJS 1.5.x Components

It's also possible to specify a component, rather than a template and controller. This can be done by providing a component and an optional bindings value to the showModal function.

ModalService.showModal({
  component: 'myComponent',
  bindings: {
    name: 'Foo',
    myRecord: { id: '123' }
  }
})

ShowModal Options

The showModal function takes an object with these fields:

  • controller: The name of the controller to create. It could be a function.
  • controllerAs : The name of the variable on the scope instance of the controller is assigned to - (optional).
  • templateUrl: The URL of the HTML template to use for the modal.
  • template: If templateUrl is not specified, you can specify template as raw HTML for the modal.
  • inputs: A set of values to pass as inputs to the controller. Each value provided is injected into the controller constructor.
  • component: Renders a modal with the provided component as its template
  • bindings: Optional. If component is provided, all properties in bindings will be bound to the rendered component.
  • appendElement: The custom angular element or selector (such as #element-id) to append the modal to instead of default body element.
  • scope: Optional. If provided, the modal controller will use a new scope as a child of scope (created by calling scope.$new()) rather than a new scope created as a child of $rootScope.
  • bodyClass: Optional. The custom css class to append to the body while the modal is open (optional, useful when not using Bootstrap).
  • preClose: Optional. A function which will be called before the process of closing a modal starts. The signature is function preClose(modal, result, delay). It is provided the modal object, the result which was passed to close and the delay which was passed to close.
  • locationChangeSuccess: Optional. Allows the closing of the modal when the location changes to be configured. If no value is set, the modal is closed immediately when the $locationChangeSuccess event fires. If false is set, event is not fired. If a number n is set, then the event fires after n milliseconds.

The Modal Object

The modal object returned by showModal has this structure:

  • modal.element - The created DOM element. This is a jquery lite object (or jquery if full jquery is used). If you are using a bootstrap modal, you can call modal on this object to show the modal.
  • modal.scope - The new scope created for the modal DOM and controller.
  • modal.controller - The new controller created for the modal.
  • modal.close - A promise which is resolved when the modal close function is called.
  • modal.closed - A promise which is resolved once the modal has finished animating out of the DOM.

The Modal Controller

The controller that is used for the modal always has one extra parameter injected, a function called close. Call this function with any parameter (the result). This result parameter is then passed as the parameter of the close and closed promises used by the caller.

Closing All Modals

Sometimes you may way to forcibly close all open modals, for example if you are going to transition routes. You can use the ModalService.closeModals function for this:

ModalService.closeModals(optionalResult, optionalDelay);

The optionalResult parameter is pased into all close promises, the optionalDelay parameter has the same effect as the controller close function delay parameter.

Animation

ModalService cooperates with Angular's $animate service to allow easy implementation of custom animation. Specifically, showModal will trigger the ng-enter hook, and calling close will trigger the ng-leave hook. For example, if the ngAnimate module is installed, the following CSS rules will add fade in/fade out animations to a modal with the class modal:

.modal.ng-enter {
  transition: opacity .5s ease-out;
  opacity: 0;
}
.modal.ng-enter.ng-enter-active {
  opacity: 1;
}
.modal.ng-leave {
  transition: opacity .5s ease-out;
  opacity: 1;
}
.modal.ng-leave.ng-leave-active {
  opacity: 0;
}

Error Handing

As the ModalService exposes only one function, showModal, error handling is always performed in the same way. The showModal function returns a promise - if any part of the process fails, the promise will be rejected, meaning that a promise error handling function or catch function can be used to get the error details:

ModalService.showModal({
  templateUrl: "some/template.html",
  controller: "SomeController"
}).then(function(modal) {
  // only called on success...
}).catch(function(error) {
  // error contains a detailed error message.
  console.log(error);
});

Global Options Configuration

To configure the default options that will apply to all modals call configureOptions on the ModalServiceProvider.

app.config(["ModalServiceProvider", function(ModalServiceProvider) {

  ModalServiceProvider.configureOptions({closeDelay:500});

}]);

Here are the available global options:

  • closeDelay - This sets the default number of milliseconds to use in the close handler. This delay will also be used in the closeModals method and as the default for locationChangeSuccess.

Developing

To work with the code, just run:

npm install
npm test
npm start

The dependencies will install, the tests will be run (always a useful sanity check after a clean checkout) and the code will run. You can open the browser at localhost:8080 to see the samples. As you change the code in the src/ folder, it will be re-built and the browser will be updated.

The easiest way to adapt the code is to play with some of the examples in the samples folder.

Tests

Run tests with:

npm test

A coverage report is written to build\coverage.

Debug tests with:

npm run test-debug

This will run the tests in Chrome, allowing you to debug.

Releasing

To create a release:

  • Create the dst pack with npm run build
  • Merge your work to master
  • Use npm run release to tag, bump the version numbers and update the changelog
  • Push and deploy git push --follow-tags && npm publish

FAQ

Having problems? Check this FAQ first.

I'm using a Bootstrap Modal and the backdrop doesn't fade away

This can happen if your modal template contains more than one top level element. Imagine this case:

<!-- Some comment -->
<div>...some modal</div>

When you create the modal, the Angular Modal Service will add both of these elements to the page, then pass the elements to you as a jQuery selector. When you call bootstrap's modal function on it, like this:

modal.element.modal();

It will try and make both elements into a modal. This means both elements will get a backdrop. In this case, either remove the extra elements, or find the specific element you need from the provided modal.element property.

The backdrop STILL does not fade away after I call close OR I don't want to use the 'data-dismiss' attribute on a button, how can I close a modal manually?

You can check the 'Complex' sample (complexcontroller.js). The 'Cancel' button closes without using the data-dismiss attribute. In this case, just use the preClose option to ensure the bootstrap modal is removed:

ModalService.showModal({
  templateUrl: "some/bootstrap-template.html",
  controller: "SomeController",
  preClose: (modal) => { modal.element.modal('hide'); }
}).then(function(modal) {
  // etc
});

Another option is to grab the modal element in your controller, then call the bootstrap modal function to manually close the modal. Then call the close function as normal:

app.controller('ExampleModalController', [
  '$scope', '$element', 'close',
  function($scope, $element, close) {

  $scope.closeModal = function() {

    //  Manually hide the modal using bootstrap.
    $element.modal('hide');

    //  Now close as normal, but give 500ms for bootstrap to animate
    close(null, 500);
  };

}]);

I'm using a Bootstrap Modal and the dialog doesn't show up

Code is entered exactly as shown the example but when the showAModal() function fires the modal template html is appended to the body while the console outputs:

TypeError: undefined is not a function

Pointing to the code: modal.element.modal();. This occurs if you are using a Bootstap modal but have not included the Bootstrap JavaScript. The recommendation is to include the modal JavaScript before AngularJS.

How can I prevent a Bootstrap modal from being closed?

If you are using a bootstrap modal and want to make sure that only the close function will close the modal (not a click outside or escape), use the following attributes:

<div class="modal" data-backdrop="static" data-keyboard="false">

To do this programatically, use:

ModalService.showModal({
  templateUrl: "whatever.html",
  controller: "WhateverController"
}).then(function(modal) {
  modal.element.modal({
    backdrop: 'static',
    keyboard: false
  });
  modal.close.then(function(result) {
    //  ...etc
  });
});

Thanks lindamarieb and ledgeJumper!

Problems with Nested Modals

If you are trying to nest Bootstrap modals, you will run into issues. From Bootstrap:

Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.

See: https://v4-alpha.getbootstrap.com/components/modal/#how-it-works

Some people have been able to get them working (see #176). Unfortunately, due to the lack of support in Bootstrap is has proven troublesome to support this in angular-modal-service.

Thanks

Thanks go the the following contributors:

  • DougKeller - Adding support for Angular 1.5 components.
  • joshvillbrandt - Adding support for $templateCache.
  • cointilt - Allowing the modal to be added to a custom element, not just the body.
  • kernowjoe - controllerAs
  • poporul - Improving the core logic around compilation and inputs.
  • jonasnas - Fixing template cache logic.
  • maxdow - Added support for controller inlining.
  • kernowjoe - Robustness around locationChange
  • arthur-xavier - Robustness when body element changes.
  • stormpooper - The new bodyClass feature.
  • decherneyge - Provider features, global configuration, appendElement improvements.

More Repositories

1

hacker-laws

💻📖 Laws, Theories, Principles and Patterns that developers will find useful. #hackerlaws
Shell
25,245
star
2

sharpshell

SharpShell makes it easy to create Windows Shell Extensions using the .NET Framework.
C#
1,444
star
3

sharpgl

Use OpenGL in .NET applications. SharpGL wraps all modern OpenGL features and offers a powerful scene graph to aid development.
C#
720
star
4

consolecontrol

ConsoleControl is a C# class library that lets you embed a console in a WinForms or WPF application.
C#
672
star
5

effective-shell

Text, samples and website for my 'Effective Shell' series.
JavaScript
649
star
6

app-icon

Icon management for Mobile Apps. Create icons, generate all required sizes, label and annotate. Supports Native, Cordova, React Native, Xamarin and more. Inspired by cordova-icon.
Java
563
star
7

wait-port

Simple binary to wait for a port to open. Useful for docker-compose and general server side activities.
JavaScript
321
star
8

docker-dynamodb

It's DynamoDB - in Docker!
Shell
230
star
9

spaceinvaders

Classic Space Invaders game written in JavaScript as a learning exercise.
JavaScript
189
star
10

terraform-aws-openshift

Create infrastructure with Terraform and AWS, install OpenShift. Party!
HCL
170
star
11

node-docker-microservice

Demonstrates how to build a testable, deployable, scalable microservice with NodeJS and Docker.
JavaScript
166
star
12

dotfiles

My personal setup. Vim, Tmux, Shells, etc.
Shell
77
star
13

mongo-monitor

CLI to monitor the status of a MongoDB cluster real-time 📈
JavaScript
77
star
14

crosswords-js

Tiny, lightweight crossword control for the web.
JavaScript
57
star
15

terraform-consul-cluster

Demonstrates how to create a resilient Consul cluster on AWS, using Terraform. Companion to my article on dwmkerr.com.
HCL
56
star
16

glmnet

GlmNet is a .NET version of the excellent OpenGL Mathematics library (GLM).
C++
52
star
17

starfield

A nice starfield background using built using HTML and vanilla JavaScript as a learning exercise.
HTML
49
star
18

architecture-as-code

A project to help define architecture logically as code, and generate living, interactive diagrams.
JavaScript
47
star
19

linux-kernel-module

A simple Linux Kernel Module, written as a learning exercise.
C
30
star
20

app-splash

Automatic splash screen generation and resizing for Mobile Apps. Supports Native, React Native, Cordova, Xamarin and more. The little brother of 'app-icon'.
Java
29
star
21

angular-memory-leaks

A small and leaky AngularJS application used to demonstrate how to identify, analyse and resolve memory leaks in JavaScript applications. A companion to the write-up at www.dwmkerr.com/fixing-memory-leaks-in-angularjs-applications
JavaScript
28
star
22

gacmanager

GAC Manager is an open source project that comes in two parts - a fully functional application to manage the Global Assembly Cache on your computer, and a C# API to allow you to manage the GAC yourself.
C#
25
star
23

langtonsant

Langton's Ant implemented in Javascript
JavaScript
23
star
24

sil

Sil is an application and addin for Visual Studio that lets you disassemble your C# code.
C#
21
star
25

file-format-wavefront

A simple .NET library to load data from Wavefront *.obj and *.mlb files.
C#
20
star
26

java-maven-standard-version-sample

This simple module demos how to use Conventional Commits, Git Hooks to enforce Conventional Commits and Semantic Versioning in a Java project built with Maven.
Shell
18
star
27

beautifully-simple-app-ci

This repository demonstrates some beautifully simple techniques for handling CI and CI for mobile apps. These techniques are appliclable to many mobile technologies and development platforms and compliment many different CI/CD toolchains.
Makefile
17
star
28

google-it

Command line tool to quickly look something up on Google!
Go
16
star
29

docker-terraform-ci

A base image for working with Terraform in CI scenarios. Provides Terraform, tflint, AWS CLI, etc.
Dockerfile
14
star
30

learn-a-language

A set of ideas and projects to work on that are great to help you learn a programming language.
14
star
31

react-es6-starter

A simple starter template for a React ES6 web app
JavaScript
12
star
32

dotnet-windows-registry

A simple, unit and integration test friendly wrapper around the Windows Registry, which is 100% compliant with the existing Microsoft.Win32.Registry package.
C#
12
star
33

lex-starter-kit

A starter kit for building chatbots using AWS Lex and Lambda.
Shell
11
star
34

switch

Switch is an Addin for Visual Studio that lets you quickly switch between related files, such as *.cpp and *.h or XAML and code-behind.
C#
9
star
35

svg-smile

Procedurally animated smiley face with SVG and pure JavaScript 😀🙂😐🙁☹️
HTML
8
star
36

node-imagemagick-cli

Access the ImageMagick CLI tools from Node. No dependencies, cross-platform, with support for ImageMagick 6 and 7.
JavaScript
8
star
37

effective-container-engineering

Practical tips and patterns for building good container citizens
JavaScript
7
star
38

terraform-aws-vpc-example

An example terraform module to create an AWS VPC with a cluster of web servers.
HCL
7
star
39

chatgpt-diagrams-extension

A Chrome browser extension that renders diagrams in the ChatGPT website inline.
HTML
7
star
40

lex-chat

A simple CLI for chatting to AWS Lex ChatBots. Great for development!
JavaScript
6
star
41

jsonclient

JsonClient .NET is a lightweight .NET class library that lets you access Json web services
C#
6
star
42

git-speed

Speed up your git flow with these advanced techniques.
Shell
6
star
43

docs

Useful guides, documents, snippets for working with tech.
Shell
5
star
44

firekeys

FireKeys is a Windows Application that lets you assign hotkeys to your favourite programs, URLs or actions.
C#
5
star
45

java-gradle-standard-version-sample

This simple module demos how to use Conventional Commits, Git Hooks to enforce Conventional Commits and Semantic Versioning in a Java project built with Maven.
Java
5
star
46

mongo-connection-string

Handle mongodb connection strings with ease.
JavaScript
4
star
47

makefile-help

A simple snippet that allows you to quickly add a 'help' command to a Makefile to show command documentation.
Shell
4
star
48

microservices-playground

☁️🐳 Spin up microservice platforms on the cloud in seconds - use it to evaluate them or try new technologies!
JavaScript
4
star
49

better-specs

Great specs can be in markdown.
4
star
50

apex

C#
3
star
51

ContentEditableMvc

ContentEditableMvc is a small library for ASP MVC 4 web pages that lets you use the power of the HTML5 contenteditable attribute and Ajax to update content from the client.
C#
3
star
52

docker-shells

A Debian Image will the most popular shells pre-installed. Useful for comparing features between shells.
Makefile
3
star
53

dwmkerr.com

The 'dwmkerr.com' website content and setup. Static site managed with Hugo.
JavaScript
3
star
54

vsix-tools

A set of Powershell functions to help with vsix files.
PowerShell
3
star
55

effective-shell-installer

This is the install script for the https://effective-shell.com samples. This repo hosts the https://effective.sh installer.
Shell
3
star
56

QuickAccent

Windows utility to allow quick selection of accents and symbols to the clipboard.
C#
3
star
57

effective-nodejs-debugging

Presentation, code samples and notes for a talk at JSChannel 2016
HTML
3
star
58

html5base

My personal preferences for a base HTML5 page - includes a css reset and some minor typography tweaks, as well as hyperlink styling.
CSS
2
star
59

terraform-aws-ecs-cluster

Build an Amazon Elastic Container Services Cluster with Terraform.
HCL
2
star
60

dotnet-com-admin

The COM Admin library provides APIs to manage the installation and registration of .NET Framework and .NET Core COM Servers and Shell Extensions
C#
2
star
61

terraform-aws-kubernetes

Create infrastructure with Terraform and AWS, install Kubernetes. Party! http://www.dwmkerr.com/get-up-and-run…
HCL
2
star
62

microservice-zapp

A super simple microservice I often use when demoing docker. Spits out quotes from Zapp Brannigan!
Python
1
star
63

deusnovum

Deus Novum is an HTML5/JS game that lets you take control of a Universe - manipulate time, space and physics to complete challenges.
JavaScript
1
star
64

pythonexperiments

A set of experiments in Python, good for learning.
Python
1
star
65

fsharpexperiments

A general repo for F# projects as learning exercises.
F#
1
star
66

puzlog

Hobby project. Track crossword progress.
HTML
1
star
67

node-configuration

Simple configuration for Node applications, load from files, environment variables or parameters.
1
star
68

template-nodejs-module

A template for a Node.js module that has basic standards for linting, testing, build pipelines, NPM deployment, documentation and contributors.
Shell
1
star
69

seed-node

Starter project for Node.js.
JavaScript
1
star
70

on

A simple tool which helps when working with environment variables, devops and 12 factor apps.
JavaScript
1
star
71

homebrew-tools

A Homebrew Tap for tools which I maintain and publish.
1
star
72

app-version

Version management for Mobile Apps. Simple tool to set version for Native, React Native, Cordova, Xamarin and more.
JavaScript
1
star
73

slack-backend

A demo repository showing how Slack can be useful when building backend systems
1
star