Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject '$modalInstance' into a controller?

In my application after I found out that a user is not logged in I want to open a modal dialog:

  .when('/showtask/:id', {templateUrl: 'Home/Template/showtask', resolve: ShowTaskCtrl.resolve, access: { allowAnonymous: false },
            resolve: {
        userAuthenticated: ["$http", "$q", function ($http, $q) {
            var deferred = $q.defer();
            $http.get('/api/Authentication/UserAuthenticated').then(function (data) {

                if (data.data != "null") {
                    deferred.resolve(data.data);
                }
                else {

                    var modalInstance = {
                        templateUrl: 'Home/Template/loginfailed',
                        controller: 'ModalInstanceCtrl',
                        modalpart: ['modalpart', function (modalpart) {
                            return modalInstance;
                            }]
                    };
                    $modal.open(modalInstance);

                    deferred.reject();

                }   
            });
            return deferred.promise;

        }]

    }

Since it is happening on route change I have to inject a modalpart inside an instance and retrieve it in the controller.

var ModalInstanceCtrl = WorkerApp.controller('ModalInstanceCtrl', ["$scope", "modalpart", function ($scope, modalpart) {

But I keep getting this error:

Unknown provider: modalpartProvider <- modalpart

How can I solve this problem?

P.S. Original code which I am looking at is here: http://angular-ui.github.io/bootstrap/ (under modal)

like image 409
Timsen Avatar asked Feb 26 '14 23:02

Timsen


2 Answers

Had this problem for awhile as well. Although you didn't post your HTML, that is where my problem was. Make sure you do not name the controller in your DOM, this has already been taken care of for you in $modal.open().

like image 91
compguy24 Avatar answered Nov 10 '22 13:11

compguy24


I've never had to use the $modal service inside a route change like what you are doing, so not sure how that will work. However just looking at your $modal code alone it looks wrong. The correct way should be:

var modalOptions = {
  templateUrl: 'Home/Template/loginfailed',
  controller: 'ModalInstanceCtrl'
};
$modal.open(modalOptions);

And then your controller definition:

WorkerApp.controller('ModalInstanceCtrl',
  ["$scope", "$modalInstance", function ($scope, $modalInstance) {
    // Do your stuff
  }]);

The $modal service will handle the injection of $modalInstance to your controller automatically, as per the documentation.

like image 43
Beyers Avatar answered Nov 10 '22 14:11

Beyers