generator-angular-fullstack icon indicating copy to clipboard operation
generator-angular-fullstack copied to clipboard

Modal Service

Open Hamatek opened this issue 12 years ago • 28 comments

I noticed there is a modal service in the latest version of the generator, but i couldn't find any example to see how to use it, I mean what should I I do once I call the modal service in my controller ?

Is there anyone kind enough to give me an explanation regarding this new service and how to use it ?

Cheers

Hamatek avatar Sep 22 '14 08:09 Hamatek

@Hamatek it goes like this:

client/app/admin/admin.controller.js

angular.module('accountstaffersApp')
  .controller('AdminCtrl', function ($scope, User, Modal, currentAdmin) {

    // Use the User $resource to fetch all users
    $scope.users = User.query({
      exclude: currentAdmin._id
    });

    // Modal.confirm.delete returns a function that will open a modal when ran
    // We use closure to define the callback for the modal's confirm action here in the controller
    $scope.delete = Modal.confirm.delete(function(user) { // callback when modal is confirmed
      User.remove({ id: user._id });
      angular.forEach($scope.users, function(u, i) {
        if (u === user) {
          $scope.users.splice(i, 1);
        }
      });
    });

  });

client/app/admin/admin.jade

div(ng-include='"components/navbar/navbar.html"')
.container
  p
    | The delete user and user index api routes are restricted to users with the 'admin' role.
  ul.list-group
    li.list-group-item(ng-repeat='user in users')
      strong {{user.name}}
      br
      span.text-muted {{user.email}}
      //- first argument is what will be displayed as name in delete modal
      //- additional args are passed to the callback defined in the controller
      a.trash(ng-click='delete(user.name, user)')
        span.glyphicon.glyphicon-trash.pull-right

kingcody avatar Sep 24 '14 07:09 kingcody

Please don't make fun of me, but to use the modal do I just replace the contents of the file with the text above? :+1:

xBlazeTECH avatar Sep 24 '14 12:09 xBlazeTECH

You can... If you would like to have a confirm delete modal opened when you attempt to delete a user from /admin.

kingcody avatar Sep 25 '14 08:09 kingcody

@Hamatek take a look at the comments in the code above, let me know if I should elaborate further on a particular section.

kingcody avatar Sep 25 '14 08:09 kingcody

@kingcody, Thanks you for your help, I wouldn't mind an easier example like "hello word" modal with a html page rather than jade, but i think I got it. Thank you.

Will this be in the default setup of the generator ?

Hamatek avatar Sep 25 '14 08:09 Hamatek

@Hamatek thank you for the feedback, I'll try to get some documentation together. I'll link it here for you when I do.

As far as it being included as default, I can not say.

kingcody avatar Sep 26 '14 06:09 kingcody

I'm looking for a way to launch the modal with a different functionality, a window to post to the database. I'm sure it's possible, but I'm I can't get it working. Any help would be appreciated!

camwhite avatar Nov 05 '14 18:11 camwhite

@camwhite could you be a little more specific on the details of your post action? Will the post occur while the modal is open or directly following the modal's dismissal?

kingcody avatar Nov 06 '14 07:11 kingcody

@kingcody I would be open to either solution, but preferably post on dismissal.

camwhite avatar Nov 06 '14 18:11 camwhite

I'm trying to implement the modal dialog but I'm struggling a bit as I'm fairly new to Angular.

I'd like to have a simple information modal dialog with a single button. I would like to pass in the title and body text from the controller that opens it. I've got this working but I can't work out how to use the callback or return a promise. I'd like to do something only after the user has clicked the button.

What would be the best way to achieve this?

TWKDreamState avatar Dec 05 '14 08:12 TWKDreamState

For all who are struggling, as a relative angular newbie this is how I got the service to work. I wanted a modal that would ask me to login if I tried to do a certain task. Inside my controller, I used the angular-fullstack modal service to construct a function that I can call at my pleasing.

      $scope.modal=Modal.confirm.askToLogin(function(message) { // callback when modal is confirmed
        $location.path("/login"); //will redirect to login page, make sure your controller is using $location
      });

Now, whenever I please, I can call this function as follows..

$scope.modal("follow");

But for this to work I have to add askToLogin to the "API" in the modal service. In modal.service.js I added

// Public API here
return {
  /* Confirmation modals */
  confirm: {
    delete: function(del) {
      //this is the example provided
    },
    askToLogin: function(cb) { //my new modal
      cb = cb || angular.noop;
      return function() {
        var args = Array.prototype.slice.call(arguments),
            name = args.shift(),
            theModal;
        theModal = openModal({ //openModal is a function the modal service defines.  It is just a wrapper for $Modal
          modal: {
            dismissable: true,
            title: 'Login',
            html: '<p>In order to complete the <strong>' + name + '</strong> action you must login.</p>', //set the modal message here, name is the parameter we passed in
            buttons: [ {//this is where you define you buttons and their appearances
              classes: 'btn-warning',
              text: 'Cancel',
              click: function(event) {
                theModal.dismiss(event);
              }
            },{
              classes: 'btn-primary',
              text: 'Login',
              click: function(event) {
                theModal.close(event);
              }
            },]
          }
        }, 'modal-primary');
        theModal.result.then(function(event) {
          cb.apply(event, args); //this is where all callback is actually called
        });
      };
    }

honkskillet avatar Feb 08 '15 19:02 honkskillet

Hello!

I've followed honkskillet example and have mutated it into my own means. I pass an obj to the modal which is then edited in the modal body via form fields (nothing out the usual as im just binding the obj via traditional ng-model="modal.obj.key" .)

But where I'm struggling is getting that object back from the modal to the controller to then manipulate it in my controller's scope.

I hope someone can help.

Thanks.

Code below for anyone interested: Controller:

        $scope.modal = Modal.confirm.newMailer(function (message) { 
            // callback when modal is confirmed
            console.log(message); 
            //Change this code to restangular insert mailer (needs made) 
        }, {hello:"world"});

Modal function:

newMailer: function (cb, newMailerObj ) { //my new modal
                    cb = cb || angular.noop;
                    return function () {
                        var args = Array.prototype.slice.call(arguments),
                            name = args.shift(),
                            theModal;
                        theModal = openModal({ 
                            //openModal is a function the modal service defines.  It is just a wrapper for $Modal
                            modal: {
                                dismissable: true,
                                title: 'Login',
                                text: 'Login',
                                newMailerObj: newMailerObj,
                                buttons: [{ 
                                    //this is where you define you buttons and their appearances
                                    classes: 'btn-warning',
                                    text: 'Cancel',
                                    click: function (event) {
                                        theModal.dismiss(event);
                                    }
            }, {
                                    classes: 'btn-primary',
                                    text: 'Create',
                                    click: function (event) {
                                        theModal.close(event);
                                    }
            }, ]
                            }
                        }, 'modal-danger', 'components/modal/newMailerModal.html');
                        theModal.result.then(function (event) {
                            cb.apply(event, args); //this is where all callback is actually called
                        });
                    };
                }

LunarDevelopment avatar Apr 29 '15 09:04 LunarDevelopment

Never mind, I've sorted it, I found where I could pass the scope object back from modal to controller.

Modal html:

<input ng-model="modal.newMailerObj.hello" /> // just to manipulate the obj in modal scope 

modal factory

newMailer: function (cb, newMailerObj ) { //my new modal
                    cb = cb || angular.noop;
                    return function () {
                        var args = Array.prototype.slice.call(arguments),
                            name = args.shift(),
                            theModal;
                        theModal = openModal({ 
                            //openModal is a function the modal service defines.  It is just a wrapper for $Modal
                            modal: {
                                dismissable: true,
                                title: 'Login',
                                text: 'Login',
                                newMailerObj: newMailerObj,
                                buttons: [{ 
                                    //this is where you define you buttons and their appearances
                                    classes: 'btn-warning',
                                    text: 'Cancel',
                                    click: function (event) {
                                        theModal.dismiss(event);
                                    }
            }, {
                                    classes: 'btn-primary',
                                    text: 'Create',
                                    click: function (event) {
                                        theModal.close(event);
                                    }
            }, ]
                            }
                        }, 'modal-danger', 'components/modal/newMailerModal.html');
                        theModal.result.then(function (event) {
                            //cb.apply(event, args); //this is where all callback is actually called
// this was the issue as I just needed to pass my declared object back to the callback <cb> 
                            cb(newMailerObj);
                        });
                    };
                }

controller

$scope.modal = Modal.confirm.newMailer(function (message) { 
            // callback when modal is confirmed
            console.log(message); 
            //Change this code to restangular insert mailer (needs made) 
        }, {hello:"world"});

LunarDevelopment avatar Apr 29 '15 09:04 LunarDevelopment

In case anyone has followed this thread, I have a new issue.

From an ng-repeat for object in objectsArray I need to call a modal on button click and pass that object into the modal for editing. Heres the simplified code (which doesnt work) View:

<button ng-click="Modal(viewObject)" class="btn btn-default">Edit</button >

Controler

$scope.Modal= Modal.confirm.openthemodal(function (objectReturnedFromModal) {
            console.log(objectReturnedFromModal); 
        }, viewObject);

modal factory

openthemodal: function (cb, viewObject) {
                    cb = cb || angular.noop;
                    return function () {
                        var theModal;
                        theModal = openModal({
                            modal: {
                                dismissable: true,
                                title: title || '',
                                viewObject: viewObject || {},
                                buttons: [{
                                    classes: 'btn-warning',
                                    text: 'Cancel',
                                    click: function (event) {
                                        theModal.dismiss(event);
                                    }
            }, {
                                    classes: 'btn-primary',
                                    text: 'Create',
                                    ngDisabled: 'mailer_form.$invalid',
                                    click: function (event) {
                                        theModal.close(event);
                                    }
            }, ]
                            }
                        }, 'modal-danger', 'components/modal/mailerModal.html', 'lg');
                        theModal.result.then(function (event) {
                            //cb.apply(event, args); //this is where all callback is actually called
                            cb(MailerObj);
                        });
                    };
                }

LunarDevelopment avatar Apr 29 '15 15:04 LunarDevelopment

Can someone help me create a modal form using this service? The modal form when submitted saves data to the database. I'm trying to follow the above code but did not understand how can I send the form input back to the controller where modal is invoked. Also, do I always have to use modal.html or can I have another html template for modal form? I'm Angular newbie so I'm finding it hard to understand the code in above examples.

msjoshi avatar Jun 11 '15 01:06 msjoshi

@Awk34 we went from 2.1.1 to 3.0.0.rc... Is the milestone 2.3.0 still valid or should be changed to 3.0.0?

amejiarosario avatar Aug 18 '15 04:08 amejiarosario

The GitHub history still shows this:

screenshot 2015-08-18 11 31 10

but I have renamed the milestone to 3.1.0, which you can see here:

screenshot 2015-08-18 11 31 01

Awk34 avatar Aug 18 '15 15:08 Awk34

@msjoshi: I struggled with using the modal service for a form as well. The trick is to use the args parameter that you see when the modal is opened. If you have data input into the modal, you just stuff it into the args array on the click event. Since the array essentially gets emptied at the beginning of the function, anything you put into the array will go in at index 0. This is late but I hope it helps.

haverchuck avatar Jan 04 '16 03:01 haverchuck

I built a contact-list app using this tutorial: http://fullstacktutorials.net/mean-stack-tutorial-for-beginners-part-1-configuration-setup/ I would like to use the built-in modal service to allow users to input new contact information via a modal and save to DB. Can someone point me in the right direction? The above delete example is not similar enough. Thanks! @kingcody

rmindigo avatar Jan 05 '16 16:01 rmindigo

Hi, The steps below will allow you to collect data in a form on the modal and then pass the form-data back to the controller:

  1. Add a form to the modal template (/client/components/modal/modal.jade)

    .modal-header
      button.close(ng-if='modal.dismissable', type='button', ng-click='$dismiss()') &times;
      h4.modal-title(ng-if='modal.title', ng-bind='modal.title')
    .modal-body
    
      form.form(name="formData")
        .form-group
          label Place
          input.form-control(type="text", ng-model="modal.formData.place")
        .form-group
          label Rating
          rating(max="5", ng-model="modal.formData.rating")
        .form-group
          label Review
          textarea.form-control(type="text", rows="3", ng-model="modal.formData.review")
    
    .modal-footer
      button.btn(ng-repeat='button in modal.buttons', ng-class='button.classes', ng-click='button.click($event)', ng-bind='button.text')
    
  2. Add an object to the modal's scope in the model service (/client/components/modal/modal.service.js)

    1. Create an object for the form data: var formData = {}
    2. Add formData to the 'modal' object: formData: formData
    3. Pass the formData into the callback: del.apply(event, [formData]);
          /**
           * Create a function to open a delete confirmation modal (ex. ng-click='myModalFn(name, arg1, arg2...)')
           * @param  {Function} del - callback, ran when delete is confirmed
           * @return {Function}     - the function to open the modal (ex. myModalFn)
           */
          delete(del = angular.noop) {
            /**
             * Open a delete confirmation modal
             * @param  {String} name   - name or info to show on modal
             * @param  {All}           - any additional args are passed straight to del callback
             */
            return function() {
              var args = Array.prototype.slice.call(arguments),
                  name = args.shift(),
                  deleteModal;
    
              var formData = {}
    
              deleteModal = openModal({
                modal: {
                  formData: formData
                  dismissable: true,
                  title: 'Confirm Delete',
                  html: '<p>Are you sure you want to delete <strong>' + name + '</strong> ?</p>',
                  buttons: [{
                    classes: 'btn-danger',
                    text: 'Delete',
                    click: function(e) {
                      deleteModal.close(e);
                    }
                  }, {
                    classes: 'btn-default',
                    text: 'Cancel',
                    click: function(e) {
                      deleteModal.dismiss(e);
                    }
                  }]
                }
              }, 'modal-danger');
    
              deleteModal.result.then(function(event) {
                del.apply(event, [formData]);
              });
            };
          }
    
  3. Launch the modal from your controller, and handle the formData in the callback passed to the modal service

    'use strict';
    angular.module('exampleApp')
    .controller('exampleCtrl', function ($scope, Modal) {
    
      $scope.openModal = Modal.confirm.delete(function (formData) {
    
        // formData contains the data collected in the modal 
        console.log(formData.place)
    
      });
    });
    
    

MagRelo avatar Jan 16 '16 22:01 MagRelo