AngularJs: Reusable $modal dialog for Yes/No scenario !!

Every project requires a standard popup where we display error messages, or alerts with yes/no options. Every time we cannot write $modal window for this purpose, how about a standard dialog which can be used across application. copy & paste below code snippets directly !!

Controller for modal window:

(function () {
    'use strict';

    angular.module('test').controller('MessageDialogCtrl',
        ['$scope', '$modalInstance', 'params', MessageDialog]);

    function MessageDialog($scope, $modalInstance, params) {

        $scope.title = params.title;
        $scope.message = params.message;

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');

        };

        $scope.ok = function () {
            $modalInstance.close();
        };

    }
})();

Create dialog:

function showYesNoDialog(title, message, yescallback, nocallback) {

    var modalInstance = $modal.open({
        templateUrl: 'yesno-dialog.html',
        controller: 'MessageDialogCtrl',
        resolve: {
            params: function () {
                return {
                    title: title,
                    message: message
                };
            }
        }
    });

    modalInstance.result.then(function (value) {
        if (yescallback) {
            yescallback(value);
        }
    }, function () {
        if (nocallback) {
            nocallback();
        }
    });
};

How to use ??

showYesNoDialog('title',message, function () {
        //yes callback - do when yes is pressed
    }, function () {
        //no callback - do when no is pressed
    }
);

Happy coding !!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s