0

I'm trying to make this ionic modal as flexible as possible, and I came up with this solution:

I have a service that has this code inside it to create a basic modal:

var showModal = function(type, $scope) {
  var buttons, deferred, settings;
  deferred = $q.defer();
  settings = _modalType(type);
  buttons = _dynamicAppendButtons(settings.buttons, deferred);
  $ionicPopup.show({
    title: settings.title,
    scope: $scope,
    cssClass: settings.class,
    templateUrl: settings.template,
    buttons: buttons
  });
  return deferred.promise;
};

this return a promise.

Then I setup some modal-specific settings in a different function that looks like this:

var _modalType = function(type) {
  var settings;
  settings = null;
  switch (type) {
    case 'new':
      settings = {
        title: "Add new",
        "class": "new",
        template: "./sections/modals/modal.new.tpl.html",
        buttons: [
          {
            text: "Cancel",
            "class": "pull-left",
            resolve: false
          }, {
            text: "Confirm",
            "class": "pull-right",
            resolve: true
          }
        ]
      };
  }
  return settings;
};

and another function generates the array of buttons to append to the modal based on the settings above:

var _dynamicAppendButtons = function(buttons, deferred) {
  var array, btn, button, i, len;
  array = [];
  for (i = 0, len = buttons.length; i < len; i++) {
    button = buttons[i];
    btn = {
      text: button.text,
      type: button["class"],
      onTap: function() {
        return deferred.resolve(button.resolve);
      }
    };
    array.push(btn);
  }
  return array;
};

everything works apart from the resolution of the promise from the array button.

I am trying to return deferred.resolve(button.resolve) where button.resolve is either true or false (to resolve or reject) but unfortunately I always get the latest button.resolve value for some reason.

Any help?

thanks

Nick
  • 13,493
  • 8
  • 51
  • 98
  • 1
    Switch `for()` loop to `forEach()` to create closure. Or use `map()` to create the array. By the time event occurs `button` will have last value in the loop – charlietfl Jul 19 '17 at 10:25
  • Hi, sorry I tried this only today. Yes, changing with for each solved the issue. Thanks again. If you wanna put this as an answer I can select it – Nick Jul 24 '17 at 09:06

0 Answers0