Use the same controller for modal and non-modal template in Angular UI Bootstrap


I am using “Angular UI-Bootstrap” modal directive ( to open my template in modal window. And my controller that handles modal template which takes $modalInstance as one of its dependency. But now the issue is that for desktop and tablet view I want my template to open as modal window. While for mobile view I don’t want modal window but the same template need to open as separate page. Here I’m trying to use same controller and same html template for the both mobile view as well as desktop view.

But in mobile view the controller wasn’t created via $ method and so Angular throws an error something like: Unknown provider: $modalInstanceProvider <- $modalInstance.

Then, I thought that let me manually inject $modalInstance later. So I tried something like:


but it doesn’t work :(. Also, after injecting $injector.has(‘$modalInstance’); still gives me false :(. It only works when directly inject via:

angular.module('mymodule').controller('MyModalCtrl', function($modalInstance) {
  // do something with $modalInstance

After struggling for a long while I found a easier trick on Stack Overflow for reusing my Controller for both modal and normal case.

We can pass caller’s scope to the modal controller, so pushed modalInstance into the scope and gave it to the modal controller. Now you don’t have the unknown provider problem because $scope is a well known one. Thanks He Zhang 🙂

Below is the example given as solution:

CallerController = function($rootScope, ...) {
   var modalScope = $rootScope.$new();
   modalScope.modalInstance = ${
        templateUrl: tempUrl,
        controller: ReuseableModalController ,
        scope: modalScope // <- This is it!

    modalScope.modalInstance.result.then(function (result) {
        // Closed
    }, function () {
        // Dismissed

ReuseableModalController = function($scope, ...){

        var dataToSendBack = 'Hello World';

This trick works for me. Please comment out if you have any better solution for this. 🙂


7 thoughts on “Use the same controller for modal and non-modal template in Angular UI Bootstrap

  1. Thx you. On a project i can inject $modalInstance and in another i can’t. I don’t Find the reason, but your trick is very helpfull.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s