Angular-ui modal, sending data into modal controller from $http

Joe picture Joe · Sep 18, 2013 · Viewed 58k times · Source

I'm using the angular-ui modal directive http://angular-ui.github.io/bootstrap/ .

I have followed the example from the link above.

This is my data I want to send from my controller:

ProductsFactory.getOneProduct().then(function(d){
  $scope.selectedProduct = d.data;
});

$scope.open = function () {
  var modalInstance = $modal.open({
    controller: 'ModalInstanceCtrl',
    templateUrl: 'productDetail.html',
    resolve: {
      items: function () {
        return $scope.selectedProduct;
      }
    }
  });
};

And this is my modal controller:

var ModalInstanceCtrl = function ($scope, $modalInstance, selectedProduct) {

  console.log(selectedProduct);

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

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

Problem is i can't access the "selected product" in my Modal controller. I know the reason is something to do width asyncrnous call and it can only be access from the GUI. But how do I solve this issue? How do i send the "$scope.selectedProduct" to my ModalInstanceCtrl?

Answer

Chandermani picture Chandermani · Sep 18, 2013

You can try something like

$scope.open = function () {
  var modalInstance = $modal.open({
    controller: 'ModalInstanceCtrl',
    templateUrl: 'productDetail.html',
    resolve: {
      items: function () {
        return ProductsFactory.getOneProduct();
      }
    }
  });
};

Basically your $modal can take a promise, so why not use it. Now the object should be available on the controller when the promise gets resolved. The ModalInstanceCtrl should be

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {

since you are resolving the items property not the selectedProduct property.