[twitter-bootstrap] Closing Twitter Bootstrap Modal From Angular Controller

I have a modal window that I use to present a form to users. They enter the information and then press a button the has an ng-click. The server processes the request and sends back a response. When the response is success I want to close the modal window from the controller. How can this be achieved?

The modal is a partial included in another page

Main page:

<!-- main content -->
<p>Foo</p>
<!-- angular directive -->
<foo-directive></foo-directive>

Content of that directive:

<div ng-controller="FooCtrl">
    <ul class="thumbnails">
        <li class="span3 tile tile-white" ng-repeat="foo in model.foo">
            <div>
                {{foo.bar}}
            </div>
            <div>
                ({{foo.bam}})
            </div>
            <div>
                <a data-toggle="modal" href="#myModal"><img src="{{foo.imgPath}}"></a>
            </div>
        </li>
    </ul>
    <!-- foo modal partial included by ejs -->
    <% include foo_modal.ejs %>
</div>

Modal markup:

<div id="fooModal" class="modal hide fade in" style="display: none; ">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3>New Device</h3>
    </div>
    <div class="modal-body">
        <h4>Foo Modal</h4>
        <div ng-controller="FooCtrl">
            <form name="fooFrm">
                <input id="email" type="email" class="input-medium" ng-model="fooEmail"
                       placeholder="Email">
                <button class="btn btn-primary btn-small"
                        ng-click="doFoo({email:fooEmail})">Email Link</button>
            </form>
        </div>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Close</a>
    </div>
</div>

Controller code:

functionFooCtrl($scope, FooService) {


    $scope.doFoo= function (email) {
       FooService.save({email:email.fooEmail}) {
            alert('Request successful');
            //TODO close Twitter bootstrap modal named fooModal here
        },
            function (err) {
                alert('Your request bonked, sorry');
                //TODO close twitter bootstrap modal named fooModal here
            });
        }
    };

What is the right way to close the modal from the controller in the success and error functions?

Thanks in advance,

This question is related to twitter-bootstrap angularjs angularjs-directive

The answer is


You can add data-dismiss="modal" to your button attributes which call angularjs funtion.

Such as;

<button type="button" class="btn btn-default" data-dismiss="modal">Send Form</button>

You can do it like this:

angular.element('#modal').modal('hide');

I have remixed the answer by @isubuz and this answer by @Umur Kontaci on attribute directives into a version where your controller doesn't call a DOM-like operation like "dismiss", but instead tries to be more MVVM style, setting a boolean property isInEditMode. The view in turn links this bit of info to the attribute directive that opens/closes the bootstrap modal.

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.directive('myModal', function() {_x000D_
   return {_x000D_
     restrict: 'A',_x000D_
     scope: { myModalIsOpen: '=' },_x000D_
     link: function(scope, element, attr) {_x000D_
       scope.$watch(_x000D_
         function() { return scope.myModalIsOpen; },_x000D_
         function() { element.modal(scope.myModalIsOpen ? 'show' : 'hide'); }_x000D_
       );_x000D_
     }_x000D_
   } _x000D_
});_x000D_
_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
  $scope.isInEditMode = false;_x000D_
  $scope.toggleEditMode = function() { _x000D_
    $scope.isInEditMode = !$scope.isInEditMode;_x000D_
  };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MyCtrl as vm">_x000D_
_x000D_
<div class="modal fade" my-modal my-modal-is-open="isInEditMode">_x000D_
  <div class="modal-dialog">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-body">_x000D_
        Modal body! IsInEditMode == {{isInEditMode}}_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button class="btn" ng-click="toggleEditMode()">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<p><button class="btn" ng-click="toggleEditMode()">Toggle Edit Mode</button></p> _x000D_
<pre>isInEditMode == {{isInEditMode}}</pre>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's a reusable Angular directive that will hide and show a Bootstrap modal.

app.directive("modalShow", function () {
    return {
        restrict: "A",
        scope: {
            modalVisible: "="
        },
        link: function (scope, element, attrs) {

            //Hide or show the modal
            scope.showModal = function (visible) {
                if (visible)
                {
                    element.modal("show");
                }
                else
                {
                    element.modal("hide");
                }
            }

            //Check to see if the modal-visible attribute exists
            if (!attrs.modalVisible)
            {

                //The attribute isn't defined, show the modal by default
                scope.showModal(true);

            }
            else
            {

                //Watch for changes to the modal-visible attribute
                scope.$watch("modalVisible", function (newValue, oldValue) {
                    scope.showModal(newValue);
                });

                //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                element.bind("hide.bs.modal", function () {
                    scope.modalVisible = false;
                    if (!scope.$$phase && !scope.$root.$$phase)
                        scope.$apply();
                });

            }

        }
    };

});

Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition

<div modal-show class="modal fade"> ...bootstrap modal... </div>

Usage Example #2 - this uses an Angular expression in the modal-visible attribute

<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>

Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.

$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)

I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal

Hope this helps.


You can do it with a simple jquery code.

$('#Mymodal').modal('hide');

We can achieve the same without using angular-ui. This can be done using angular directives.

First add the directive to the modal.

<div class="modal fade" my-modal ....>...</div>

Create a new angular directive:

app.directive('myModal', function() {
   return {
     restrict: 'A',
     link: function(scope, element, attr) {
       scope.dismiss = function() {
           element.modal('hide');
       };
     }
   } 
});

Now call the dismiss() method from your controller.

app.controller('MyCtrl', function($scope, $http) {
    // You can call dismiss() here
    $scope.dismiss();
});

I am still in my early days with angular js. I know that we should not manipulate the DOM inside the controllers. So I have the DOM manipulation in the directive. I am not sure if this is equally bad. If I have a better alternative, I shall post it here.

The important thing to note is that we cannot simply use ng-hide or ng-show in the view to hide or show the modal. That simply hides the modal and not the modal backdrop. We have to call the modal() instance method to completely remove the modal.


**just fire bootstrap modal close button click event**
var app = angular.module('myApp', []);
app.controller('myCtrl',function($scope,$http){
  $('#btnClose').click();// this is bootstrap modal close button id that fire click event
})

--------------------------------------------------------------------------------

<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" id="btnClose" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

just set modal 'close button' id as i set btnClose, for closing modal in angular you have to just fire that close button click event as i did $('#btnClose').click()


Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angularjs-directive

Angular2 - Input Field To Accept Only Numbers Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS ng-change not working on a text input Controller not a function, got undefined, while defining controllers globally Find child element in AngularJS directive Angular directives - when and how to use compile, controller, pre-link and post-link How to validate email id in angularJs using ng-pattern Enable/Disable Anchor Tags using AngularJS get original element from ng-click How to detect browser using angularjs?