19

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?

1 Answer 1

41

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you help explain this change? The problem with original post was that the member would be "items" and not "selectedProduct". The original example would put product data in that items member. This answer changes that to put the promise in that items member. Why change this? You say "it can be done" but since this wasn't the problem, I don't understand the reason for this change. I am assuming that code (not in the picture) would have to be changed because now you have a promise instead of the data -- or is there some other hidden magic that makes both examples the same?
You can work without this change. The only think that needs to be made sure is that $scope.selectedProduct is set before modal dialog is called. Considering that the getOneProduct call is async. Using getOneProduct in the resolve saves us from the timing issue.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.