How to inject '$modalInstance' into a cont

2019-04-06 20:54发布

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)

3条回答
我想做一个坏孩纸
2楼-- · 2019-04-06 21:26

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().

查看更多
混吃等死
3楼-- · 2019-04-06 21:29

I have the same problem, and I found that the controller I registed run twice! thanks for @compguy ,I removed the controller name in the template . I Successd!

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-06 21:42

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.

查看更多
登录 后发表回答