Adding classes with AngularJS

So I’ve just added a nice bit of functionality to getTestr, where you can test a website from the homepage without being registered or logged in. When the website url is entered, getTestr goes off and tests the website, displaying the result in a modal window.

getTestr - quick website test

This is all managed by AngularJS making an Ajax call back to the server, which then does the testing bit and sends the result back to the AngularJS code. This means the user experience is nice and slick, complete with Ajax spinners (of course) while the user is waiting to see the result of the test.

I wanted to change the look of the response message based on the result of the test. I wanted a failed test to show a red header, like this:

gettestr test fail

and a successful test to show a green header, like this:

gettestr test success

Making this happen with AngularJS was actually pretty simple using the ng-class attribute. Here’s how I did it in 3 easy steps:

1. Add the ng-class attribute to your HTML template:

<div ng-app ng-controller=”ColourChangeController”>
  <div ng-class=”class”>
    This background turns red with an error, or green when everything works…
  </div>
</div>

2. Add some css to your stylesheet for the colours you want to switch between

.green { background: #00ff00; }
.red { background: #ff0000; }

3. Add the logic to your AngularJS controller

function ColourChangeController ($scope) {
  // add your code in here and test if it passes or fails
  if (success) {
    $scope.class = “green”;
  } else {
    $scope.class = “red”;
  }
});

And that’s all there is to it!

getTestr is a website monitoring platform for developers and freelancers. It’s simple to set up and use, so you can focus on writing code rather than babysitting your websites! Register for your 14 day free trial today and see if you can improve your customer’s satisfaction!

Tagged with: ,