binarygiant binarygiant - 5 months ago 36
AngularJS Question

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,

Answer

Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):

$scope.close = function(result){
  dialog.close(result);
};

Update:

The directive has since been renamed Modal.