Angular is a nice JavaScript framework for creating more structured web solutions and presenting data. As shown in previous post, jQuery works just as good, but some advantages of Angular are that your code is easier to read, you can piggy-back on the functionality of Angular meaning less development time, and it is meant for separating the view (i.e. your HTML) from the data handling – i.e. Model-View-Controller based (MVC).

Things you need to have a fair understanding of to follow this post

  • A fair knowledge of HTML, CSS, and JavaScript
  • The basics of Angular suchs ”ng directives” and ”controller”
  • It’s good to check this previous post since we will go from a jQuery based solution to Angular

Breaking our web app into html, css, and JavaScript

In the end we will have an identical user interface with the same frontend functionality as we did with jQuery.

front-end_design

However one of the main end benefits of using Angular will be a cleaner structure when it comes to separating the presentation layer (i.e the html view) and the data handling (i.e. the Angular part). We will start by breaking our web app into three files:

  • index.html – this is the clean html frontend
  • sensorApp.js – this is where we implement the controller logic to update the data in the html view
  • sensorApp.css – this is simply the css styles we used previously, unchanged but broken out in a separate file

Updating our index.html with adequate ng directives

We start by ”Angular-ify” our html view by adding necessary ng directives and bindings. This will allow us to use these spaces from our Angular controller to populate the html view with sensor data. We add the ”ng-app” and ”ng-controller” directives in the <html> tag, and link our css file, the Angular framework and our sensorController.js file in the <head>.

<!DOCTYPE html>
<html ng-app="mySensorApp" ng-controller="sensorCtrl">
  <head>
    <title>Home Security Frontend</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="http://code.jquery.com/jquery.js"></script>

    <!-- Bootstrap -->
    <script src="js/bootstrap.min.js"></script>
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

    <!-- Angular -->
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="sensorController.js"></script>

    <link href="sensorApp.css" rel="stylesheet" media="screen">
  </head>
  <body>


<div class="container">
...

Next we structure the ”container” part of our html file in three sections corresponding to the Bootstrap rows: the top row, the home security status row, and the sensor boxes row.

<div class="container">
   <!-- The top row for the logo and the time -->
   <div class="row">
      <div class="col-sm-12" id="top-bar">
         <img id="yellington_logo" src="http://www.yellington.com/yellington_logo.png">
         <div id="clock">{{clock | date: 'HH:mm:ss'}}</div>
      </div>
   </div>
   
   <!-- The home security status row -->
   <div class="row">
      <div class="col-sm-6 v-align" style="text-align: right;">       
         <span class="glyphicon glyphicon-home" id="house-image"></span>
      </div>
      <div class="col-sm-6 v-align" id="house-status-text"><!-- keep the opening and closing div tags together to avoid white space causing line breaks in the user interface-->
         <h5>Home Security Status</h5>
         <h2>{{homeSecurityStatus}}</h2>
      </div>
   </div>

   <!-- The row for the sensor boxes -->
   <div class="row" id="sensor-container">
      <div ng-repeat="sensor in sensorData" class="col-sm-6 col-md-4 col-lg-3 sensor-outer-box">
         <div class="sensor-box">
            <img class="sensor-icon" ng-src={{getSensorImage(sensor.Type)}}>
            <div class="sensor-data">
               <h4>{{ sensor.Name }}</h4>
               <h5>Status: {{ sensor.Data }}</h5>
               Updated: {{ sensor.LastUpdate }}
            </div>
          </div>
        </div>
      </div>

    </div><!-- Container -->
  </body>
</html>

In the top row, we have added an Angular expression for binding clock data to our html, likewise in the home security status row, and in the sensor data row for sensor data. The ng-repeat directive is a neat thing that will assist us going through the retrieved sensor data from the server. The html view has no clue where this data comes from or how or when it should be updated. This logic is handled by the controller.

Adding an Angular controller for updating the data

Angular uses a ”controller” to take care of the logic for updating the data in the presentation view i.e. the html. We create a controller that looks like this and is linked together with our html file.

var app = angular.module('mySensorApp', []);
app.controller('sensorCtrl', function($scope, $http, $timeout) {
	var domoticzURL = "http://192.168.1.99:8080/"; //use this format if you want to place this file on another computer on your home network.
	//var domoticzURL = "../"; //use this format if you place this file in a folder in the www folder on your Domoticz server. 

	updateSensorData(); //Start the polling of sensor data

	function updateSensorData() {
		//Publish the time in our user interface
		$scope.clock = new Date();  

		//We request a list of all sensor data and loop through it to publish on our web page
		$http.get(domoticzURL + "json.htm?type=devices&filter=all&used=true&order=Name")
		 .then(function(response) {
		   
		  	$scope.sensorData = response.data.result;      

			//We retrieve the status of the security system, basically Disarmed, Armed Away, or Armed Home
			$http.get(domoticzURL + "json.htm?type=command&param=getsecstatus")
			.then(function(response) {    

			    if (response.data.secstatus==0) $scope.homeSecurityStatus = "Disarmed";
			    	else if (response.data.secstatus==1) $scope.homeSecurityStatus = "Armed Home";
			    	else if (response.data.secstatus==2) $scope.homeSecurityStatus = "Armed Away";
			        else $scope.homeSecurityStatus = "Unknown";

			    $timeout(updateSensorData(), 1000); //Poll the sensor data every second
	  		});
	  	});
	}

	$scope.getSensorImage = function(sensorType){
		//This function returns the image of the sensor that is stored in the image folder on your Domoticz server
		//The list of sensor types can be expanded dependant on what type of sensors you have
		switch(sensorType) {
		case "Light/Switch":
		      return domoticzURL + "images/Light48_On.png";
		    break;
		case "Temp + Humidity":
		    return domoticzURL + "images/temp-20-25.png";
		    break;
		default:
		  return domoticzURL + "images/Light48on.png";
		}
	};
});

What’s inside the curly brackets of the app.controller is the constructor of the controller class and will execute at the time of launching the web app. You will probably recognize most of the code from the jQuery version. We have an updateSensorData() function that retrieves the sensor data through http requests along with a timer to poll the server every second. The getSensorImage() is used by the html view to retrieve the corresponding url for the src attribute.

Final conclusion

Using Angular might require some time to get a feeling for how it works and how to utilize the built-in functionality. Once over that learning curve, it’s a nice framework to use. Counting the lines of code from the jQuery version and the Angular version gives us that  jQuery required 142 lines of code whereas Angular required 117 – an 18% improvement. However, the biggest improvement is an increase in readability and structure and thus maintainability.

Creating an MVC structured UI using Angular

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *