Stop Bootstrap alerts being removed from the DOM with AngularJS

So I was just working on a few updates to getTest (well actually a total re-write to be honest, introducing loads of great new features and functionality! Sign up to my mailing list if you’re interested in hearing when it’s available!) and I came across a rather silly thing with Bootstrap (version 3.2).

If you create a dismissible message box and dismiss it, Bootstrap removes it completely from the DOM! So if you want to be able to re-display that alert box with the same or different message (say you want to show a confirmation message every time someone updates their profile, but don’t want to have to reload the entire page between each edit, because that’s how we roll nowadays right?) you either have to dynamically create that alert message box each time you want to use it (urgh!), or you have to find another way to close (i.e. hide) it when it is dismissed by the user (much nicer!).

If you’ve reached this point and you’re wondering what I’m talking about, an alert message box looks like this:

dismissible-alert

and the HTML looks like this:

<div class=”alert alert-warning alert-dismissible” role=”alert”>
  <button type=”button” class=”close” data-dismiss=”alert” aria-label=”Close”><span aria-hidden=”true”>×</span></button>
  <strong>Warning!</strong> Better check yourself, you’re not looking too good.
</div>

So as I’m using Angular on getTestr I thought I would use Angular to hide the alert when the ‘close’ link is clicked.

My HTML now looks like this:

<div class=”alert alert-warning alert-dismissible” role=”alert” ng-show=”message”>
  <button type=”button” class=”close” aria-label=”Close” ng-click=”dismissAlert()”><span aria-hidden=”true”>×</span></button>
  <strong>Warning!</strong> Better check yourself, you’re not looking too good.
</div>

I’ve done a few things here – I’ve added an ng-show=”message” attribute to the alert box so it’s only showing when $scope.message is truthy (i.e. it contains a message). I’ve removed the ‘data-dismiss=”alert” attribute from the ‘close’ link so the alert box won’t be removed from the DOM and I’ve added an ng-click attribute instead: ng-click=”dismissAlert()”. In reality I’m also doing a few other things like binding the text within the alert box to a scope property, but I don’t want to over-complicate the example.

So now I just create the dismissAlert function in my Angular Controller (actually I’m doing this all within an Angular Directive, but for the sake of simplicity let’s pretend it’s in my Controller). This is really simple because I’m showing the alert when $scope.message is truthy, so to hide it, I just need to set $scope.message to false:

$scope.dismissAlert = function() {
  scope.responseData = false;
};

And that’s it – you can now re-use that alert box on the same page without a page reload!

Tagged with: , ,