1

I have been trying to create a modal windows that are re-usable with angularJS. While I am googling I come to know that re-usable modals are created by using

  1. custom directives.
  2. services.

I'm in a confusion which method to follow. What is the most customized method for creating modal windows in angularJS? and any resources on how to create re-usable modal windows (design patterns for modal windows) in angularJS

Note: Please suggest solutions without angular-bootstrap-ui or bootstrap.

Update: I am trying to develop a similar kind of screen. enter image description here

  1. when the user clicks on "select Bus" link a modal window will be displayed.
  2. Title, Content of the modal window is based on the corresponding hyper link.
  3. I've already done this screen by using custom directives with the help of

How to Create a Simple Modal Dialog Directive in Angular.js

  1. But what I am going to rewrite it as a reusable module or directive.
  2. So suggest some design patterns to create re usable custom modal dialog windows using angularJS

3 Answers 3

1

Please check the following link for re-usable windows in angular. That may resolve your issues.

http://www.dwmkerr.com/the-only-angularjs-modal-service-youll-ever-need/

1

A fairly simple one is ng-modal (https://github.com/adamalbrecht/ngModal), it is a directive, meaning it is highly re-usable. Services are do-able as well, but they are meant to get/set/process data rather than display HTML; hence directives are the way to go.

I've used ng-modal and adding just a little code to it went a long way to make it super-reusable. You can place it in it's own controller and have it always injected so that you can open the modal and show a message or some html.

HTML:

<div ng-controller="modalCtrl">
    <modal-dialog show='dialogShown' dialog-title='titleToUse' height='400px' width='75%'>
        <p ng-bind="messageToShow"> </p>
        <div ng-bind-html="someHTML"></div>
    </modal-dialog>
</div>

JS:

myApp.controller('modalCtrl', function($scope){

    $scope.titleToUse = "Modal Title";
    $scope.messageToShow = "Testing Message"; // default message
    $scope.someHTML = "<div>Whoa! A Div!</div>";

    $scope.$on('changeMessageEvent', function($event, message){ // listens for change message event and sets new message
        $scope.messageToShow = message;
    });
});

   myApp.controller('someOtherController', function($scope, $rootScope){ // import rootScope

       var messageToSendToModal = "New Message!";
       $rootScope.$broadcast('changeMessageEvent', messageToSendToModal );

   });

Update:
If you want dynamic template and controllers, that is easily to do with ng-modal, you just have to use ng-include:

<div ng-controller="modalCtrl">
    <modal-dialog show='dialogShown' dialog-title='titleToUse' height='400px' width='75%'>
        <p ng-bind="messageToShow"> </p>
        <div ng-bind-html="someHTML"></div>
        <!-- some dynamic template -->
        <ng-include src="pathToTemplate"></ng-include>
    </modal-dialog>
</div>

where in modalCtrl you have

$scope.pathToTemplate = "/path/to/template.html";

that template can contain a controller and can be switched out dynamically via variables.

5
  • Hi Elite, thanks for you answer. Surprisingly I've tried the same example before asking this question and now I am trying how to develop the same example with re-usable modal behavior like adding dynamic template URL, passing data from controller to directive. So that anyone can create modal windows on the fly by and that too without any external dependencies like bootstrap. Sep 15, 2014 at 19:24
  • see my update above, this addresses the dynamic templates. but as for creating dynamic template urls, I don't think that's do-able very easily. Sep 15, 2014 at 19:40
  • 1
    for changing template urls see: stackoverflow.com/questions/14632260/… Sep 15, 2014 at 19:42
  • Thanks for your answer i've already seen the link you provided. I think there might be a problem with my design pattern. I think I need to change the way I designed the custom directive or to use service kinda structure. I've updated my question. Sep 15, 2014 at 20:56
  • I've seen dan wahlin creating reusable modal windows service and thinking whether to implement service or custom directive for creating re-usable modal overlays Sep 15, 2014 at 21:05
0

If anyone is looking for another example I just had a crack at creating a custom modal service and directive myself, with them you can add modals to views like this:

<button ng-click="vm.openModal('custom-modal-1')">Open Modal 1</button>

<modal id="custom-modal-1">
    <div class="modal">
        <div class="modal-body">
            <h1>A Custom Modal!</h1>
            <p>
                Home page text: <input type="text" ng-model="vm.bodyText" />
            </p>
            <button ng-click="vm.closeModal('custom-modal-1');">Close</button>
        </div>
    </div>
    <div class="modal-background"></div>
</modal>

Here's the controller that opens and closes the modal:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('Home.IndexController', Controller);

    function Controller(ModalService) {
        var vm = this;

        vm.openModal = openModal;
        vm.closeModal = closeModal;

        initController();

        function initController() {
            vm.bodyText = 'This text can be updated in modal 1';
        }

        function openModal(id){
            ModalService.Open(id);
        }

        function closeModal(id){
            ModalService.Close(id);
        }
    }

})();

This is the custom modal service:

(function () {
    'use strict';

    angular
        .module('app')
        .factory('ModalService', Service);

    function Service() {
        var modals = []; // array of modals on the page
        var service = {};

        service.Add = Add;
        service.Remove = Remove;
        service.Open = Open;
        service.Close = Close;

        return service;

        function Add(modal) {
            // add modal to array of active modals
            modals.push(modal);
        }

        function Remove(id) {
            // remove modal from array of active modals
            var modalToRemove = _.findWhere(modals, { id: id });
            modals = _.without(modals, modalToRemove);
        }

        function Open(id) {
            // open modal specified by id
            var modal = _.findWhere(modals, { id: id });
            modal.open();
        }

        function Close(id) {
            // close modal specified by id
            var modal = _.findWhere(modals, { id: id });
            modal.close();
        }
    }
})();

And this is the custom modal directive:

(function () {
    'use strict';

    angular
        .module('app')
        .directive('modal', Directive);

    function Directive(ModalService) {
        return {
            link: function (scope, element, attrs) {
                // ensure id attribute exists
                if (!attrs.id) {
                    console.error('modal must have an id');
                    return;
                }

                // move element to bottom of page (just before </body>) so it can be displayed above everything else
                element.appendTo('body');

                // close modal on background click
                element.on('click', function (e) {
                    var target = $(e.target);
                    if (!target.closest('.modal-body').length) {
                        scope.$evalAsync(Close);
                    }
                });

                // add self (this modal instance) to the modal service so it's accessible from controllers
                var modal = {
                    id: attrs.id,
                    open: Open,
                    close: Close
                };
                ModalService.Add(modal);

                // remove self from modal service when directive is destroyed
                scope.$on('$destroy', function() {
                    ModalService.Remove(attrs.id);
                    element.remove();
                });               

                // open modal
                function Open() {
                    element.show();
                    $('body').addClass('modal-open');
                }

                // close modal
                function Close() {
                    element.hide();
                    $('body').removeClass('modal-open');
                }
            }
        };
    }
})();

For more info you can check out this blog post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.