Search code examples
javascriptangularjsangular-strap

How to close angular-strap modal from controller when calling from factory


Well, so I have seen a lot of people struggling to close the angular-strap modal from controller. I got some of the answers, but actually they do it differently (I do not want to change the code style). I open modal using my modalFactory, and so I do not have modalInstance with me. So I am compeltely not sure, how I can close this.

With angular-bootstrap, I know I can inject uibModalInstance and call uibModalInstance.dismiss() to close the function. But how I can do similar with the angular-strap modal.

Here is my factory:

(function (app) {
'use strict'

app.factory('modalFactory', ['$modal', function ($modal) {

    var local = this;
    local.modalInstance = ['$scope',
        function ($scope) {
               $scope.myVar = "Some variable input ";
               $scope.closeModal = function(){
                 console.log("CLose function has been called..")
                 // How I can close this.
               }
        }];

    return {
        openMyModal: function (ip) {
            $modal({
                templateUrl: 'myModal.html',
                controller: local.modalInstance,
                size: 'lg',
                resolve: {
                    ip: function () {
                        return ip;
                    }
                }
            })
        }
    }
}])

})(app);

Complete plunkr is available here.


Solution

  • Call $scope.$hide() inside you clodeModal method.

    (function (app) {
        'use strict'
    
        app.factory('modalFactory', ['$modal', function ($modal) {
    
            var local = this;
            local.modalInstance = ['$scope',
                function ($scope) {
                       $scope.myVar = "Some variable input ";
                       $scope.closeModal = function(){
                         console.log("CLose function has been called..")
                         $scope.$hide();
                       }
                }];
    
            return {
                openMyModal: function (ip) {
                    $modal({
                        templateUrl: 'myModal.html',
                        controller: local.modalInstance,
                        size: 'lg',
                        resolve: {
                            ip: function () {
                                return ip;
                            }
                        }
                    })
                }
            }
        }])
    })(app);
    

    Update plunker: http://plnkr.co/edit/2FxoBzY0vQqdrxqptm6F?p=preview