ANGULAR-CONFIRM

alerts, confirms and dialogs in one.

Welcome to angular-confirm!

The quickest way to build modals with angular
angular-confirm manages the scope, you don't need to worry about anything,
so that you can throw in a template and render stuff right away.
This project is a re-write of the jquery-confirm plugin

Please post your Suggestions here.

Features

These features can practically be used like so.

Elegant Alerts.

Stacked Confirmations

Success, error, warning

Need input?

Its also a Dialog.

Not so important modal

Loading from remote places

Some actions maybe critical

Responds to keystrokes

Automatically centered

Loading images

Youtube videos

Themes

angular-confirm comes loaded with 7 different themes, for all common use cases.

Whats new in v1.1.0

  • Performance fixes
  • Removed ngSanitize & ngAnimate dependencies

Getting started

Installation

Download
Download the Latest version and use files in the /dist/ folder.

via Bower:
$ bower install angular1-confirm

Dependencies:

  • Angular >= 1.5
  • Bootstrap by Twitter >= v3 (optional, if you want to use responsive layouts)
  • jQuery library >= v1.8
to use ngConfirm without bootstrap set useBootstrap: false

Basic Usage

Add the module dependency in your app

angular.module('myModule', ['cp.ngConfirm'])

$ngConfirm

A basic usage of ngConfirm,
This pretty much explains how it works, content is the template that will be shown inside the popup.

If $scope is not provided, ngConfirm will create a child scope from rootScope & the created scope will be destroyed when modal is closed.

.controller('myController', function ($scope, $ngConfirm) {
    $scope.test = function(){
        $scope.name = 'Sia: cheap thrills';
        $ngConfirm({
            title: 'Confirm!',
            content: '<strong>{{name}}</strong> is my favourite song',
            scope: $scope,
            buttons: {
                sayBoo: {
                    text: 'Say Booo',
                    btnClass: 'btn-blue',
                    action: function(scope, button){
                        scope.name = 'Booo!!';
                        return false; // prevent close;
                    }
                },
                somethingElse: {
                    text: 'Something else',
                    btnClass: 'btn-orange',
                    action: function(scope, button){
                        $ngConfirm('You clicked on something else');
                    }
                }
                close: function(scope, button){
                    // closes the modal
                },
            }
        });
    }
});

using templates (contentUrl)

contentUrl is basically templateUrl, which is fetched and compiled with scope.
if contentUrl is provided content property is ignored.

.controller('myController', function ($scope, $ngConfirm) {
    $scope.usingTemplates = function(){
        $ngConfirm({
            title: 'Confirm!',
            contentUrl: 'my_template.html',
            scope: $scope,
            ...
        });
    }
});

Shorthand usage

The shorthand thingy is made so that you don't need to define everything again.
There are 4 variants for passing the arguments.

$ngConfirm('Content here');
$ngConfirm('Content here', $scope);
$ngConfirm('Content here', 'Title here');
$ngConfirm('Content here', 'Title here', $scope);

Buttons

Its all what you need to know about buttons in ngConfirm.

Definition

Buttons can be defined in the following fashion, pretty self explanatory.

$ngConfirm({
    buttons: {
        hello: function(scope, button){
            // button action
        },
        hey: function(scope, button){
            button.setDisabled(true); // disable the current button.
            button.setText('heyyyy'); // change the current button text.
            this.triggerButton('hello'); // this triggers the other button named hello.
            this.buttons.heyThere.setDisabled(true); // disable the hello button.
        },
        heyThere: {
            text: 'Hey there!',
            btnClass: 'btn-blue',
            keys: ['enter', 'a'],
            action: function(scope, button){
                // button action
            }
        }
    }
});

Button text

$ngConfirm({
    buttons: {
        something: function(){
            // here the key 'something' will be used as the text.
            $ngConfirm('You clicked on something.');
        },
        somethingElse: {
            text: 'Something else &*', // Some Non-Alphanumeric characters
            action: function(){
                $ngConfirm('You clicked on something else');
            }
        }
    }
})

Button style

Simply applying classes to buttons.

ngConfirm comes bundled with btn-blue btn-green btn-red btn-orange btn-purple btn-default btn-dark

Other bootstrap options are btn-primary btn-inverse btn-warning btn-info btn-danger btn-success

$ngConfirm({
    buttons: {
        default: {
            btnClass: 'btn-default',
            ...
        },
        blue: {
            btnClass: 'btn-blue',
            ...
        },
        green: {
            btnClass: 'btn-green',
            ...
        },
    }
});

Button keys

Listen to keyup events for individual buttons. A button can listen for multiple keys at a time.

Available options are:
a to Z, tilde, enter, shift, tab, capslock, ctrl, win, alt, esc, space.
$ngConfirm({
    buttons: {
        specialKey: {
            text: 'On behalf of shift',
            keys: ['shift', 'alt'],
            action: function(){
                $ngConfirm('Shift or Alt was pressed');
            }
        },
        alphabet: {
            text: 'A, B',
            keys: ['a', 'b'],
            action: function(){
                $ngConfirm('A or B was pressed');
            }
        }
    }
});

In this example, the YES button is hidden using bootstrap's hide class, thus the user can only use keys to proceed.

$ngConfirm({
    title: false,
    content: 'A very very critical action here! <br> ' +
             'the proceed button is hidden.' +
             'The only way to proceed is to press the <strong>Y</strong> key.<br>' +
             'Press <span style="font-size: 20px;">Y</span> to proceed.',
    buttons: {
        yes: {
            show: false, // hides the button using display: none
            keys: ['y'],
            action: function (scope, button) {
                $ngConfirm('Critical action <strong>was performed</strong>.');
            }
        },
        no: {
            keys: ['N'],
            action: function (scope, button) {
                $ngConfirm('You clicked No.');
            }
        },
    }
});

Button properties

Button properties provide a nice and clean way to alter your buttons in run-time.

$ngConfirm({
    buttons: {
        buttonA: {
            text: 'button a',
            action: function (scope, button) {
                button.setText('Oh yeah'); // the current button
                this.buttons.buttonB.setText('Changed it!');
                return false;
            }
        },
        buttonB: {
            text: 'button b',
            action: function (scope, button) {
                this.buttons.buttonA.setDisabled(true);
                return false;
            }
        },
        reset: function (scope, button) {
            this.buttons.buttonA.setDisabled(false);
            this.buttons.buttonA.setText('button a');
            this.buttons.buttonB.setText('button b');
            return false;
        }
    },
});

A full list of functions for buttons.

Function Code Description
setText this.buttons.<buttonName>.setText('text') The text you want to set.
setBtnClass this.buttons.<buttonName>.setBtnClass('btn-info') Change the button's class.
setDisabled this.buttons.<buttonName>.setDisabled(Boolean) enable or disable a button
setShow this.buttons.<buttonName>.setShow(Boolean) Show or hide the button via CSS

Customizing

Dialog type

Dialog types helps give the user a hint as to what the dialog is about

$ngConfirm({
    title: 'Encountered an error!',
    content: 'Something went downhill, this may be serious',
    type: 'red',
    typeAnimated: true,
    buttons: {
        tryAgain: {
            text: 'Try again',
            btnClass: 'btn-red',
            action: function(){
            }
        },
        close: function () {
        }
    }
});

Icons

Give meaning to your dialog with custom icons.
Read about Font Awesome here .

$ngConfirm({
    icon: 'glyphicon glyphicon-heart',
    title: 'glyphicon'
});
$ngConfirm({
    icon: 'fa fa-warning',
    title: 'font-awesome'
});
$ngConfirm({
    icon: 'fa fa-spinner fa-spin',
    title: 'Working!',
    content: 'Sit back, we are processing your request!'
});

Close icon

ngConfirm confirm uses &times; html entity for this close symbol, however you can use Any icon of your choice (fa, glyphicon, zmdi)

By default closeIcon is set to null. That means, if buttons are not defined the closeIcon will be shown, else will not be shown.
To explicitly show closeIcon set it to a truthy value and vise versa.

Turn on closeIcon explicitly

$ngConfirm({
    closeIcon: true
});

Using other libraries for icons

$ngConfirm({
    closeIcon: true,
    closeIconClass: 'fa fa-close'
});

Handle closeIcon's callback

Control what happens when close icon is clicked.
closeIcon can take in function to handle the button click or you can return a button name.

$ngConfirm({
    closeIcon: function(){
        return false; // to prevent close the modal.
        // or
        return 'aRandomButton'; // set a button handler, 'aRandomButton' prevents close.
    },
    // or
    closeIcon: 'aRandomButton', // set a button handler
    buttons: {
        aRandomButton: function(){
            $.alert('A random button is called, and i prevent closing the modal');
            return false; // you shall not pass
        },
        close: function(){
        }
    }
});

Custom width

ngConfirm uses bootstrap's grid system for its layout by default. You can simply provide column classes to adjust the modal's width.

You can also set responsive layouts. Bootstrap grid docs

instead of typing the whole thing, provide keywords like
xlarge/xl equivalent to col-md-12
large/l equivalent to col-md-8 col-md-offset-2
medium/m equivalent to col-md-6 col-md-offset-3
small/s equivalent to col-md-4 col-md-offset-4
xsmall/xs equivalent to col-md-2 col-md-offset-5

$ngConfirm({
    columnClass: 'small'
});
$ngConfirm({
    columnClass: 'col-md-4'
});
$ngConfirm({
    columnClass: 'col-md-4 col-md-offset-8 col-xs-4 col-xs-offset-8'
});
$ngConfirm({
    columnClass: 'col-md-4 col-md-offset-8 col-xs-4 col-xs-offset-8',
    containerFluid: true, // this will add 'container-fluid' instead of 'container'
});

Custom width without Bootstrap

Many have a different taste, who wont be using bootstrap in their projects.
You can simply provide the width of the modal, in px or any metric you want.

useBootstrap must be set to false to use this feature
$ngConfirm({
    boxWidth: '30%',
    useBootstrap: false,
});
$ngConfirm({
    boxWidth: '500px',
    useBootstrap: false,
});

Namespaced bootstrap

Namespacing is basically isolating the bootstrap classes names, like turning '.row' to '.custom-row'
If you're using a namespaced bootstrap library, this option is for you.

it is ideal to set this in defaults

$ngConfirm({
    bootstrapClasses: {
        container: 'container',
        containerFluid: 'container-fluid',
        row: 'row',
    },
});

Animations

The animations section is moved to the animations.html page.

see Animations

Themes

The themes section is moved to the themes.html page

see Themes

Auto close

Do a action if the user does not respond within the specified time.
This comes in handly when the user is about to do something critical.
The autoClose option takes in a string, like 'confirm|4000' where confirm is the action to trigger after 4000 milliseconds.
Practical examples of autoClose

$ngConfirm({
    title: 'Delete user?',
    content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
    autoClose: 'cancel|8000',
    buttons: {
        deleteUser: {
            text: 'delete user',
            btnClass: 'btn-red',
            action: function () {
               $ngConfirm('Deleted the user!');
            }
        },
        cancel: function () {
           $ngConfirm('action is canceled');
        }
    }
});
$ngConfirm({
   title: 'Logout?',
    content: 'Your time is out, you will be automatically logged out in 10 seconds.',
    autoClose: 'logoutUser|10000',
    buttons: {
        logoutUser: {
            text: 'logout myself',
            btnClass: 'btn-green',
            action: function () {
               $ngConfirm('The user was logged out');
            }
        },
        cancel: function () {
           $ngConfirm('canceled');
        }
    }
});

Background dismiss

Control what happens if the user clicks outside the modal.

backgroundDismiss is set to false by default.
$ngConfirm({
    backgroundDismiss: true, // this will just close the modal
});
$ngConfirm({
    backgroundDismiss: function(){
        return false; // modal wont close.
    },
});
$ngConfirm({
    backgroundDismiss: function(){
        return 'buttonName'; // the button will handle it
    },
});
$ngConfirm({
    backgroundDismiss: 'buttonName',
    content: 'Click outside the box to close the modal',
    buttons: {
        buttonName: function () {
            $ngConfirm('Button name was clicked');
        },
        close: function () {
        }
    }
});

Background dismiss animation

Fancy animations to grab users attention. Click outside the modal to see the animation.

$ngConfirm({
    backgroundDismiss: false,
    backgroundDismissAnimation: 'shake',
});
$ngConfirm({
    backgroundDismiss: false,
    backgroundDismissAnimation: 'glow',
});

Escape key

Control what happens when the escape key is pressed. This is enabled by default.
backgroundDismiss is called when escape key is pressed. if backgroundDismiss is false, it will make the backgroundDismissAnimation

$ngConfirm({
    content: 'background dismiss is not allowed on this modal, thus the modal will make a backgroundDismissAnimation',
    escapeKey: true,
    backgroundDismiss: false,
});
$ngConfirm({
    escapeKey: 'buttonName',
    buttons: {
        buttonName: function(){
            $.alert('Button name was called');
        },
        close: function(){

        }
    }
});

RTL support

If you need to show the confirm box in rtl then you should set the rtl option to true.

$ngConfirm({
    title: 'پیغام',
    content: 'این یک متن به زبان شیرین فارسی است',
    rtl: true,
    closeIcon: true,
    buttons: {
        confirm: {
            text: 'تایید',
            btnClass: 'btn-blue',
            action: function () {
                $ngConfirm('تایید شد.');
            }
        },
        cancel: {
            text: 'انصراف',
            action: function () {

            }
        }
    }
});

Callbacks

Get more control over the modal, mainly important for binding events for the modal elements.

$ngConfirm({
    title: false,
    contentUrl: 'callback.html',
    onScopeReady: function(scope){
        // when the scope is ready/created
        alert('Scope is ready');
        var self = this;
        this.buttons.ok.disabled = true;
        scope.fnClick = function () {
            scope.name = 'Chuck norris';
            self.buttons.ok.disabled = false;
        };
    },
    onReady: function (scope) {
        // when content is fetched & the modal is open
        alert('onReady');
    },
    onOpenBefore: function (scope) {
        // before the modal is displayed.
        alert('onOpenBefore');
    },
    onOpen: function () {
        // after the modal is displayed.
        alert('onOpen');
    },
    onClose: function () {
        // before the modal is hidden.
        alert('onClose');
    },
    onDestroy: function () {
        // when the modal is removed from DOM
        alert('onDestroy');
    },
    onAction: function (scope, btnName) {
        // when a button is clicked, with the button name
        alert('onAction: ' + btnName);
    },
    buttons: {
        ok: function () {

        }
    }
});

Global defaults

You can setup global settings for your ngConfirm.

angular.module('myApp', ['cp.ngConfirm'])
    .run([
        '$ngConfirmDefaults',
        function($ngConfirmDefaults){
            $ngConfirmDefaults.useBootstrap = false; // this is globally set.
        }
    ]);

Options

Options, their defaults, possibilities and explanations.

Name Type Default Description
title String 'Hello' Title of the dialog.
type String 'default' Colors the modal to give the user a hint of success/failure/warning,
available options are: 'blue, green, red, orange, purple & dark'
scope Angular scope false If a scope is provided, the content will be compiled with that scope, if not, a new child scope will be created from rootScope.
typeAnimated Boolean true Adds a little animation to the colors.
content String 'Are you sure to continue?' Template/Content for the dialog,
contentUrl String false Template/Content url form where the template will be fetched.
This template is cached in $templateCache
icon String '' Icon class prepended before the title. ex: 'fa fa-icon'
bgOpacity Float null if null, the theme's default bg opacity is applied.
theme String 'light' Color theme for the dialog.
possible options are 'light', 'dark', 'material' & 'bootstrap'
animation String 'zoom' The Open animation for the dialog.
possible options are right, left, bottom, top, rotate, none, opacity, scale, zoom, scaleY, scaleX, rotateY, rotateYR (reverse), rotateX, rotateXR (reverse)
The 'blur' animation was removed in v1.1.2
closeAnimation String 'scale' The close animation for the dialog. Same options as animation.
animationSpeed Number 400 Animation duration in milliseconds.
animationBounce Float 1.2 Adds a Bounce open animation,
1 = No bounce
escapeKey Boolean, String false if false, escapeKey wont work,
if true, will work, but no callbacks,
if string, will be assigned to button.
rtl Boolean false Use the Right to left text layout.
container String 'body' Specify where the generated HTML content for jconfirm should append.
By default it appends in the document's <body>.
containerFluid Boolean false If true, will use the container-fluid layout, to use the full browser width.
Only applicable if useBootstrap is true
backgroundDismiss Boolean, String, Function false If false, user wont be able to exit by clicking out.
If true, user will be able to click out, no callback.
If string, will be assigned to button.
If function, will be used as callback.
backgroundDismissAnimation String 'shake' Animation to perform to grab the user's attention when user clicks out of the box.
autoClose String false Auto-close the dialog within a specified time, if the user doesn't respond.
possible option 'buttonName|400'

the string is divided in two halves with pipe '|', the first part specifies the button name to trigger. The other half specifies the wait time in milliseconds.

closeIcon Boolean null By default closeIcon is visible if both buttons are false. (dialog mode).
closeIcon can be shown by setting this value to true.
closeIconClass String false By default jQuery confirm uses × html entity for this close symbol. You can provide icon class here to change it.
columnClass String 'col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1' Provides a better way to set Custom width and is responsive.
You can also set custom widths for different display sizes using the Bootstraps grid.
useBootstrap Boolean true if true, bootstrap classes will be set on the modal. columnClass wil be set on the box. if false, bootstrap classes will not be set, instead boxWidth will be set on the box.
boxWidth String '50%' This options sets the width of the box, when you're not planning to use bootstrap in your project
Will only work if useBootstrap is set to false,
bootstrapClasses object { container: 'container', containerFluid: 'container-fluid', row: 'row', } These are the default classes that are set when bootstrap is used, this option is available to folks who use namespaced bootstrap classes.
onScopeReady Function function(){} is called when the scope is ready or is created. Assigning properties to scope is to be done here.
onContentReady Function function(){} is called when the content is put in DOM and the modal is open. (When the modal is completed ready.)
onOpenBefore Function function(){} is called when the modal is going to be opened.
onOpen Function function(){} is called when the modal has finished opening.
onClose Function function(){} is called when the modal is going to be closed.
onDestroy Function function(){} is called after the modal element is removed from the DOM.
onAction Function function(buttonName){} is called when any of the button is clicked. buttonName is provided as argument.

Api

These are a few stuff, that will let you interact and make changes in your modal on run time.
The function $ngConfirm() returns an object on execution.

var jc = $ngConfirm({
    title: 'awesome',
    onScopeReady: function(){
        // this === jc
    }
});
All of the properties in jc are two-way binded, all you have to do is asign a new value to the property.

jc.scope

Angular scope object Read only

The content is compiled with this scope

jc.buttons.<buttonName>.setText(String|Function)

Function

Set text for a button

jc.buttons.<buttonName>.setBtnClass(String)

Function

Set class to the button

jc.buttons.<buttonName>.setDisabled(Boolean)

Function

Disables the button with attribute disabled='disabled'

jc.buttons.<buttonName>.setShow(Boolean)

Function

Show or hide the button using ng-hide

jc.close()

Function

The close method closes/destroys the dialog.

jc.isClosed()

Function

returns true if the modal is closed, else false.

jc.isOpen()

Function

returns true if the modal is open, else false.

jc.setDialogCenter()

Function

Centers the dialog on screen. This is done for you by the watch timer when the content changes.

jc.$el

DOM element

is the modal body that includes buttons content title and stuff.

jc.$confirmBox

DOM element

The box element

jc.setTheme(String)

Function

Set the theme of the modal.

jc.setType(String)

Function

Set the type for the modal

jc.setTypeAnimated(String)

Function

Set if the type decoration should animate.

jc.setTitleClass(String)

Function

Set the class for the title div.

jc.setBoxWidth(String)

Function

Set the box width for the modal, Will only work for useBootstrap: false.

jc.setContainerFluid(Boolean)

Function

Set if the container class should be fluid or not

jc.setColumnClass(String)

Function

Set the column class for the modal will only work if useBoostrap: true

jc.setIcon(String)

Function

Set the icon

jc.setTitle(String)

Function

Set the title of the modal.

jc.setCloseIcon(String)

Function

Set the close icon for the modal.

jc.setCloseIconClass(String)

Function

Choose weather to set a class name or use × as the close icon.

jc.triggerButton(String)

Function

Pass in the button key that you want to trigger.

jc.setRtl(Boolean)

Function

Set the modal for RTL or not.