Pass a controller to $ionicModal

Hello all!

I am wondering if you can pass a controller to the $ionicModal service. Something like.

$ionicModal.fromTemplateUrl('templates/login.html', {
  scope: $scope,
  controller: 'MyModalCotroller'
})

A little context: I would like to have a modal that is distributed across the app and I dont want to repeat all the methods (hide, show, buttons inside the modal) in every controller and I would like to remove the methods from the ‘Main Controller’ to keep things clean. This would encapsulate the functionality of the modal.

Is there a way to do this.?
Thanks

In angular there is the concept of services. You should place your modal code into a service or factory:

.factory('YourFactory', function($ionicModal) {
     return{
         openModal: function(){
                  //  do hacky things here
                  // open your modal here
         }
     }
});

Now you are able to call this code from every controller, where you´re injecting this new service:

.controller('YourController', function($scope, YourFactory) {
     YourFactory.openModal();
});
2 Likes