5

What is the best way to pass a function to an angular ui bootstrap modal dialog? I created a method in my modal controller that calls $scope.$parent.myMethod() like so:

$scope.isChosen = function(concept) {
    return $scope.$parent.isChosen(concept);
};

This works, but I would rather pass the function to the modal in a similar way to how functions are passed to directives. I've tried to use the modal "resolve" parameter to do this but without success. Is it possible to resolve a function for a modal, and if so, what is the syntax? If not possible, is there any other way to do this other than accessing the parent scope?

Edit: Here is a plunk attempting to pass a method to a modal, it is a little simplified but represents what I'm trying to do: http://plnkr.co/edit/eCjbZP

mer10z_tech
  • 697
  • 7
  • 12
  • It is certainly possible with the `resolve` attribute and I could show the code if you prepare a minimal plunker with what you've tried so far. having said this, your use-case sounds a bit odd. What are you trying to do, functionally speaking? – pkozlowski.opensource Jun 13 '14 at 12:20
  • I need to filter items in the modal based on other variables in my main controller. I just need to pass a function with 1 parameter that returns true or false. – mer10z_tech Jun 13 '14 at 12:32
  • Wouldn't it be better to pass filtering arguments in this case? This way or another a plunk would get you an answer in no time – pkozlowski.opensource Jun 13 '14 at 12:41
  • The filter method is rather complex and used in multiple places. I would rather keep it centrally located in my main controller. I have made a plunk with the solution from @xe4me but it is not yet working for me. – mer10z_tech Jun 13 '14 at 13:36

1 Answers1

8

When you are defining your modal , you must resolve like this :

  // here is the controller where you want to trigger the modal to open
 $scope.openModal = function () {
     // somewhere in your html , you may click on a button to envoke openModal()
   var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      size: size,
      resolve: {
        isChosen: function () {
          return $scope.isChosen;
        }
     }
   });
};

And later on , in your modalCtr you can inject isChosen like this :

  app.controller('modalCtrl',function($scope,isChosen){
     // now you can use your isChosen function however you want
  });
random_user_name
  • 25,694
  • 7
  • 76
  • 115
Milad
  • 27,506
  • 11
  • 76
  • 85
  • I think I have it working now by changing the resolve to isChosen: function () { return $scope.isChosen; } – mer10z_tech Jun 13 '14 at 13:41
  • Yup, that is the fix, if you update your answer I'll accept it. Here's an updated plunk with the correct code and a little cleaned up: http://plnkr.co/edit/tHCN4j – mer10z_tech Jun 13 '14 at 13:56
  • Yes , you're right , I was in a bit of hurry while answering your question:P – Milad Jun 13 '14 at 14:32