Alex
Alex

Reputation: 11

AngularJS how to use promise and defer

I have this service:

angular.module('taskModule').service('myService', ['$modal', '$q', myService]);

function myService($modal, $q) {
  this.displayModal = function(data) {
    return $q(function(resolve, reject) {
      $modal.open({
        templateUrl: 'taskModule/taskModule/modal.tpl.html',
        controller: function() {
          this.datas = data;
          this.buttonAction = function(id) {
            console.log(id);
          };
        },
        controllerAs: 'myCtrl'
      });
    });
  };
}

What should I add to this code to see in console

You clicked the button ok

OR

You clicked the button Cancel 

When I call this modal with this code:

myService.displayModal({
  title: "This is a modal window",
  message: "Please click a button.",
  buttons: [{
    id: 'ok',
    label: 'OK'
  }, {
    id: 'cancel',
    label: 'Cancel'
  }, ]
}).then(function(buttonId) {
  console.log('You clicked the button', buttonId);
});

Maybe I should use $q.defer(); but I'm novice in AngularJS.

Upvotes: 1

Views: 114

Answers (1)

Brad Barber
Brad Barber

Reputation: 2963

The $modal.open function returns a modal instance which already has a promise that resolves/rejects when the modal is closed/dismissed, so you can just return that promise instead of creating a new one.

To return a value with a promise, you can call close/dismiss with that value - updated below.

function myService($modal, $q) {
  this.displayModal = function(data) {
    var modalInstance = $modal.open({
      templateUrl: 'taskModule/taskModule/modal.tpl.html',
      controller: function() {
        this.datas = data;
        this.buttonAction = function(id) {
          console.log(id);
          modalInstance.close(id);
        };
      },
      controllerAs: 'myCtrl'
    });
    return modalInstance.result;
  };
}

Upvotes: 2

Related Questions