- Notifications
You must be signed in to change notification settings - Fork687
Modals and popups provider for Angular.js applications
likeastore/ngDialog
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Modal dialogs and popups provider forAngularJS applications.
ngDialog is ~10KB (minified), has minimalistic API, is highly customizable through themes and has only AngularJS as dependency.
You can download all necessary ngDialog files manually, or install it with bower:
bower install ng-dialog
or npm:
npm install ng-dialog
You need only to includengDialog.js
,ngDialog.css
andngDialog-theme-default.css
(as minimal setup) to your project and then you can start using thengDialog
provider in your directives, controllers and services. For example:
<linkrel="stylesheet"href="lib/ng-dialog/css/ngDialog.min.css"><linkrel="stylesheet"href="lib/ng-dialog/css/ngDialog-theme-default.min.css"><scriptsrc="lib/ng-dialog/js/ngDialog.min.js"></script>
Define the className to be thengDialog-theme-default
.
For example in controllers:
varapp=angular.module('exampleApp',['ngDialog']);app.controller('MainCtrl',function($scope,ngDialog){$scope.clickToOpen=function(){ngDialog.open({template:'popupTmpl.html',className:'ngdialog-theme-default'});};});
Your help is appreciated! If you've found a bug or if something is not clear, please raise an issue.
Ideally, if you've found an issue, you will submit a PR that meets ourcontributor guidelines.
git clone git@github.com:likeastore/ngDialog.gitcd ngDialognpm inpm runtest
ngDialog service provides easy to use and minimalistic API, but in the same time it's powerful enough. Here is the list of accessible methods that you can use:
===
Method allows to open dialog window, creates new dialog instance on each call. It acceptsoptions
object as the only argument.
Dialog template can be loaded throughpath
to external html template or<script>
tag withtext/ng-template
:
<scripttype="text/ng-template"id="templateId"><h1>Template heading</h1><p>Contentgoeshere</p></script>
ngDialog.open({template:'templateId'});
Also it is possible to use a simple string as template together withplain
option.
It's not always necessary to place your external html template inside<script>
tag. You could put these templates into$templateCache
like this:
angular.module('dialog.templates').run(['$templateCache',function($templateCache){$templateCache.put('templateId','template content');}]);
Then it would be possible to include thedialog.templates
module into the dependencies of your main module and start using this template astemplateId
.
There is no need to do these actions manually.You could use one of the plugins specifically for these purposes. They are available for different build systems including most popular Gulp / Grunt:
You could find more detailed examples on each of these pages.
Iftrue
allows to use plain string as template, defaultfalse
:
ngDialog.open({template:'<p>my template</p>',plain:true});
Controller that will be used for the dialog window if necessary. The controller can be specified either by referring it by name or directly inline.
ngDialog.open({template:'externalTemplate.html',controller:'SomeController'});
or
ngDialog.open({template:'externalTemplate.html',controller:['$scope','otherService',function($scope,otherService){// controller logic}]});
You could optionally specifycontrollerAs
parameter for your controller. Then inside your template it will be possible to refer this controller by the value specified bycontrollerAs
.
Usage ofcontrollerAs
syntax is currently recommended by the AngularJS team.
An optional map of dependencies which should be injected into the controller.If any of these dependencies are promises, ngDialog will wait for them all to be resolvedor one to be rejected before the controller is instantiated.
If all the promises are resolved successfully, the values of the resolved promises areinjected.
The map objectis:
key
–{String}
: a name of a dependency to be injected into the controller.factory
-{String | Function}
: IfString
then it is an alias for a service.Otherwise ifFunction
, then it is injected using$injector.invoke
and the returnvalue is treated as the dependency. If the result is a promise, it is resolvedbefore its value is injected into the controller.
ngDialog.open({controller:functionCtrl(dep){/*...*/},resolve:{dep:functiondepFactory(){return'dep value';}}});
Scope object that will be passed to the dialog. If you use a controller with separate$scope
service this object will be passed to the$scope.$parent
param:
$scope.value=true;ngDialog.open({template:'externalTemplate.html',className:'ngdialog-theme-plain',scope:$scope});
<scripttype="text/ng-template"id="externalTemplate.html"><p>External scope:<code>{{value}}</code></p></script>
In addition.closeThisDialog(value)
method gets injected to passed$scope
. This allows you to close the dialog straight from the handler in a popup element, for example:
<divclass="dialog-contents"><inputtype="text"/><inputtype="button"value="OK"ng-click="checkInput() && closeThisDialog('Some value')"/></div>
Any value passed to this function will be attached to the object which resolves on the close promise for this dialog. For dialogs opened with theopenConfirm()
method the value is used as the reject reason.
Any serializable data that you want to be stored in the controller's dialog scope. ($scope.ngDialogData
). From version0.3.6
$scope.ngDialogData
keeps references to the objects instead of copying them.
Additionally, you will have the dialog id available as$scope.ngDialogId
. If you are using$scope.ngDialogData
, it'll be also available under$scope.ngDialogData.ngDialogId
.
This option allows you to control the dialog's look, you can use built-inthemes or create your own styled modals.
This example enables one of the built-in ngDialog themes -ngdialog-theme-default
(do not forget to include necessary css files):
ngDialog.open({template:'templateId',className:'ngdialog-theme-default'});
Note: If the className is not mentioned, the dialog will not display correctly.
Checkthemes block to learn more.
Unlike theclassName
property, which overrides any default classes specified through thesetDefaults()
method (see docs),appendClassName
allows for the addition of a class on top of any defaults.
For example, the following would add both thengdialog-theme-default
andngdialog-custom
classes to the dialog opened:
ngDialogProvider.setDefaults({className:'ngdialog-theme-default'});
ngDialog.open({template:'template.html',appendClassName:'ngdialog-custom'});
Iftrue
then animation for the dialog will be disabled, defaultfalse
.
Iffalse
it allows to hide the overlay div behind the modals, defaulttrue
.
Iffalse
it allows to hide the close button on modals, defaulttrue
.
It allows to close modals by clicking theEsc
key, defaulttrue
.
This will close all open modals if there are several of them opened at the same time.
It allows to close modals on state change (history.back, $state.go, etc.), defaultfalse
.Compatible with ui-router and angular-router.Set this value to true if you want your modal to close when you go back or change state.Set this value to false if you want your modal to stay open when you change state within your app.
This will close all open modals if there are several of them opened at the same time.
It allows to close modals by clicking on overlay background, defaulttrue
. IfHammer.js is loaded, it will listen fortap
instead ofclick
.
Specify your element where to append dialog instance, accepts selector string (e.g.#yourId
,.yourClass
). If not specified appends dialog tobody
as default behavior.
Passfalse
to disable template caching. Useful for developing purposes, default istrue
.
Give a name for a dialog instance. It is useful for identifying specific dialog if there are multiple dialog boxes opened.
Provide either the name of a function or a function to be called after the dialog is opened. This callback can be used instead of thengdialog.opened
event.It provides with a way to register a hook for when the dialog is appended to the DOM and about to be shown to the user.
Provide either the name of a function or a function to be called before the dialog is closed. If the callback function specified in the option returnsfalse
then the dialog will not be closed. Alternatively, if the callback function returns a promise that gets resolved the dialog will be closed.
ThepreCloseCallback
function receives as a parametervalue
which is the same value sent to.close(id, value)
.
The primary use case for this feature is a dialog which contains user actions (e.g. editing data) for which you want the ability to confirm whether to discard unsaved changes upon exiting the dialog (e.g. via the escape key).
This example uses an inline function with awindow.confirm
call in thepreCloseCallback
function:
ngDialog.open({preCloseCallback:function(value){if(confirm('Are you sure you want to close without saving your changes?')){returntrue;}returnfalse;}});
In another example, a callback function with a nested confirm ngDialog is used:
ngDialog.open({preCloseCallback:function(value){varnestedConfirmDialog=ngDialog.openConfirm({template:'\ <p>Are you sure you want to close the parent dialog?</p>\ <div>\ <button type="button" ng-click="closeThisDialog(0)">No</button>\ <button type="button" ng-click="confirm(1)">Yes</button>\ </div>',plain:true});// NOTE: return the promise from openConfirmreturnnestedConfirmDialog;}});
Whentrue
, ensures that the focused element remains within the dialog to conform to accessibility recommendations. Default value istrue
Whentrue
, closing the dialog restores focus to the element that launched it. Designed to improve keyboard accessibility. Default value istrue
Whentrue
, automatically selects appropriate values for any unspecified accessibility attributes. Default value istrue
SeeAccessibility for more information.
Specifies the value for therole
attribute that should be applied to the dialog element. Default value isnull
(unspecified)
SeeAccessibility for more information.
Specifies the value for thearia-labelledby
attribute that should be applied to the dialog element. Default value isnull
(unspecified)
If specified, the value is not validated against the DOM. SeeAccessibility for more information.
Specifies the CSS selector for the element to be referenced by thearia-labelledby
attribute on the dialog element. Default value isnull
(unspecified)
If specified, the first matching element is used. SeeAccessibility for more information.
Specifies the value for thearia-describedby
attribute that should be applied to the dialog element. Default value isnull
(unspecified)
If specified, the value is not validated against the DOM. SeeAccessibility for more information.
Specifies the CSS selector for the element to be referenced by thearia-describedby
attribute on the dialog element. Default value isnull
(unspecified)
If specified, the first matching element is used. SeeAccessibility for more information.
This option allows you to control the dialog's width. Default value isnull
(unspecified)
If you provide a Number, 'px' will be appended. To use a custom metric, use a String, e.g.'40%'
.
For example, the following will addwidth: 400px;
to the dialog when opened:
ngDialog.open({ template: 'template.html', width: 400});
In another example, the following will addwidth: 40%;
:
ngDialog.open({ template: 'template.html', width: '40%'});
This option allows you to control the dialog's height. Default value isnull
(unspecified)
If you provide a Number, 'px' will be appended. To use a custom metric, use a String, e.g.'40%'
.
For example, the following will addheight: 400px;
to the dialog when opened:
ngDialog.open({ template: 'template.html', height: 400});
In another example, the following will addheight: 40%;
:
ngDialog.open({ template: 'template.html', height: '40%'});
Theopen()
method returns an object with some useful properties.
This is the ID of the dialog which was just created. It is the ID on the dialog's DOM element.
This is a function which will close the dialog which was opened by the current call toopen()
. It takes an optional value to pass to the close promise.
A promise which will resolve when the dialog is closed. It is resolved with an object containing:id
- the ID of the closed dialog,value
- the value the dialog was closed with,$dialog
- the dialog element which at this point has been removed from the DOM andremainingDialogs
- the number of dialogs still open.
The value property will be a special string if the dialog is dismissed by one of the built in mechanisms:'$escape'
,'$closeButton'
or'$document'
.
This allows you do to something like this:
vardialog=ngDialog.open({template:'templateId'});dialog.closePromise.then(function(data){console.log(data.id+' has been dismissed.');});
===
You're able to set default settings throughngDialogProvider
:
varapp=angular.module('myApp',['ngDialog']);app.config(['ngDialogProvider',function(ngDialogProvider){ngDialogProvider.setDefaults({className:'ngdialog-theme-default',plain:true,showClose:true,closeByDocument:true,closeByEscape:true});}]);
===
Opens a dialog that by default does not close when hitting escape or clicking outside the dialog window. The function returns a promise that is either resolved or rejected depending on the way the dialog was closed.
The options are the same as the regular.open()
method with an extra function added to the scope:
In addition to the.closeThisDialog()
method. The method.confirm()
is also injected to passed$scope
. Use this method to close the dialog andresolve
the promise that was returned when opening the modal.
The function accepts a single optional parameter which is used as the value of the resolved promise.
<divclass="dialog-contents"> Some message<buttonng-click="closeThisDialog()">Cancel</button><buttonng-click="confirm()">Confirm</button></div>
An Angular promise object that is resolved if the.confirm()
function is used to close the dialog, otherwise the promise is rejected. The resolve value and the reject reason is defined by the value passed to theconfirm()
orcloseThisDialog()
call respectively.
===
Method accepts dialog'sid
and returns aBoolean
value indicating whether the specified dialog is open.
===
Method accepts dialog'sid
as string argument to close specific dialog window, ifid
is not specified it will close all currently active modals (same behavior as.closeAll()
). Takes an optional value to resolve the dialog promise with (or all dialog promises).
===
Method manages closing all active modals on the page. Takes an optional value to resolve all of the dialog promises with.
===
Method that returns array which includes the ids of opened dialogs.
===
Adds an additional listener on every$locationChangeSuccess
event and gets update version ofhtml
into dialog. May be useful in some rare cases when you're dependant on DOM changes, defaults tofalse
. Use it in module's config as provider instance:
varapp=angular.module('exampleApp',['ngDialog']);app.config(function(ngDialogProvider){ngDialogProvider.setForceHtmlReload(true);});
===
Adds additional listener on every$locationChangeSuccess
event and gets updated version ofbody
into dialog. Maybe useful in some rare cases when you're dependant on DOM changes, defaults tofalse
. Use it in module's config as provider instance:
varapp=angular.module('exampleApp',['ngDialog']);app.config(function(ngDialogProvider){ngDialogProvider.setForceBodyReload(true);});
===
Default value: false
Define whether or not opening a dialog with the same name more than once simultaneously is allowed. Assigning true prevents opening a second dialog.
Setting it in the ngDialogProvider:
varapp=angular.module('exampleApp',['ngDialog']);app.config(function(ngDialogProvider){ngDialogProvider.setOpenOnePerName(true);});
Make sure to remember to add a 'name' when opening a dialog.ngDialog 'open' and 'openConfirm' functions will returnundefined
if the dialog was not opened.
By default the ngDialog module is served with thengDialog
directive which can be used as attribute for buttons, links, etc. Almost all.open()
options are available through tag attributes as well, the only difference is thatng-template
id or path of template file is required.
Some imaginary button, for example, will look like:
<buttontype="button"ng-dialog="templateId.html"ng-dialog-class="ngdialog-theme-flat"ng-dialog-controller="ModalCtrl"ng-dialog-close-previous> Open modal text</button>
You could optionally useng-dialog-bind-to-controller
to bind scope you've defined via parameter of directive to controller.More information about bindToController is availablehere.
Directive contains one more additional but very useful option, it's an attribute namedng-dialog-close-previous
. It allows you to close previously opened dialogs automatically.
Everytime ngDialog is opened or closed we're broadcasting three events (dispatching events downwards to all child scopes):
ngDialog.opened
ngDialog.closing
ngDialog.closed
This allows you to register your own listeners, example:
$rootScope.$on('ngDialog.opened',function(e,$dialog){console.log('ngDialog opened: '+$dialog.attr('id'));});
ngDialog.closing
is different thanngDialog.closed
in that it is fired immediately when the dialog begins closing, whereasngDialog.closed
is fired after all animations are complete. Both will be fired even when animation end support is not detected.
Additionally we trigger following 2 events related to loading of template for dialog:
ngDialog.templateLoading
ngDialog.templateLoaded
In case you are loading your templates from an external location, you could use above events to show some kind of loader.
Finally, we trigger the following event when adding padding to or removing padding from the body tag to compensate for scrollbar toggling:
ngDialog.setPadding
ThengDialog.setPadding
event will communicate the pixel value being added to the body tag so you can add it to any other elements in your layout at the same time (often fixed-position elements will need this).
CurrentlyngDialog contains two default themes that show how easily you can create your own. Checkexample
folder for demonstration purposes.
ngDialog supports accessible keyboard navigation via thetrapFocus
andpreserveFocus
options.
Therole
,aria-labelledby
andaria-describedby
attributes are also supported, and are rendered as follows.
Dialogrole
attribute:
options.ariaRole
, if specified- "dialog" if
options.ariaAuto
istrue
and the dialog contains any focusable elements - "alertdialog" is
options.ariaAuto
istrue
and the dialog doesnot contain any focusable elements
Dialogaria-labelledby
attribute:
options.ariaLabelledById
, if specified- If
options.ariaLabelledBySelector
is specified, the first matching element will be found and assigned an id (if required) and that id will be used - If
options.ariaAuto
istrue
, the first heading element in the dialog (h1-6) will be found and processed as perariaLabelledBySelector
Dialogaria-describedby
attribute:
options.ariaDescribedById
, if specified- If
options.ariaDescribedBySelector
is specified, the first matching element will be found and assigned an id (if required) and that id will be used - If
options.ariaAuto
istrue
, the first content element in the dialog (article,section,p) will be found and processed as perariaDescribedBySelector
Dialog Contentrole
attribute:
- Always assigned a value of "document"
ngDialog is available for public oncdnjs. For example, please use following urls for version0.4.0
.
//cdnjs.cloudflare.com/ajax/libs/ng-dialog/0.4.0/css/ngDialog.min.css//cdnjs.cloudflare.com/ajax/libs/ng-dialog/0.4.0/css/ngDialog-theme-default.min.css//cdnjs.cloudflare.com/ajax/libs/ng-dialog/0.4.0/css/ngDialog-theme-plain.min.css//cdnjs.cloudflare.com/ajax/libs/ng-dialog/0.4.0/js/ngDialog.min.js
ngDialog default styles are heavily inspired by awesomeHubspot/Vex jQuery modals.
MIT Licensed
Copyright (c) 2013-2015, Likeastore.cominfo@likeastore.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
About
Modals and popups provider for Angular.js applications