AngularJS Application

In this tutorial you will build your first AngularJS web-application. It is a simple calculator application, which demonstrates what you can do with your knowledge gained so far. The application we build here will be used in the advanced tutorials as well, so be sure to understand how the AngularJS calculator works.

Here’s a screenshot of what the calculator will look like
Screenshot of Calculator

For this tutorial I recommend you to have the example open aside

Play with example »

Before we begin with the implementation of the Model, View and Controller we’ll always think first what we need and go then through the implementation. The tutorial goes bottom-up, meaning we first implement the Model, then the Controller and at last the View.

Model

The model describes what needs to be stored and provides the (business-logic)methods in MVC-applications. In our example the model contains:

  • result (holds the actual result in memory)
  • operation (+ or -)
  • currentNumer (what the user entered last)
  • currentDisplay (displays the whole calculation, i.e. 5 + 12)
  • The methods for the calculation:
    • reset (resets the model itself to default)
    • setOperation (sets the operation, calculates and updates the currentDisplay
    • calculate

In this example our model will be a simple pojo (plain old javascript object), which implements fields and methods. The methods of the model in an MVC-application will then be called by the controller typically. Now we know what we need for the calculator-model, lets implement it!

Implementation of the object-fields
They’re pretty straight forward. Only thing to mention are the default values:

<script type="text/javascript">
// Declare the model
calculatorModel = {
	result: 0, // Holds the actual result in memory
	operation: "", // Holds the current operation
	currentNumber: "0", // Holds the current number as string
	currentDisplay: "", // Shows the input until the result is shown

Implementation of the methods
We begin with the reset-function, which does nothing else than to set the fields of the model back to their default-value. Here’s the implementation of the method:

reset: function() {
	this.result = 0;
	this.operation = "";
	this.currentNumber = "0";
	this.currentDisplay = "";
	},

Next we proceed with the setOperation-method. This method will be called, as soon as the user either hits + or -. The first if condition is true, if the user did not enter any value before entering an operator. In this case the currentDisplay must be updated with a 0 followed by the operator (like i.e. “0 + “). Then the calculation-method is called. Lastly the currentNumber can be emptied, as the calculation with it has been done. Here’s the implementation of the method:

setOperation: function(operationToSet) {
	this.operation = operationToSet;
	if(calculatorModel.currentNumber === "0") {
		this.currentDisplay += "0";
	}

	this.currentDisplay += " " + this.operation + " ";
	this.calculate();

	this.currentNumber = "";
},

Finally we’ll implement the calculation-method. It looks which current operator is set and calculates the result. Here’s the implementation of it:

calculate: function() {
	switch(this.operation) {
		case "+":
			this.result = this.result + parseFloat(this.currentNumber);
			break;

		case "-":
			this.result = this.result - parseFloat(this.currentNumber);
			break;
	}
}
}; // End of model-object

Controller

The controller executes the methods which are called by the calculator-buttons. In the case of our calculator we have different possibilities to respond to button-clicks. We could use one method and the $event-variable to find out what has been clicked or we could have different methods for the types of the buttons. I decided to use the later possibility of both, to make the code more readable. So what methods do we need to implement for the calculator?

  • Buttons 1-9: numberButtonClicked(clickedNumber)
  • Operations: operationButtonClicked(clickedOperation)
  • Enter: enterClicked()
  • Reset: resetClicked()

Module- and controller registratation
The first thing we need to do is to register the calculator-module and the calculator-controller, so that we can append the methods to the controller. Additionally we set the model in the controller with the line $scope.calculator = calculatorModel;. Here’s the implementation:

// declare the calculator-module
var calculatorApp = angular.module('calculatorApp', ['calculatorModule']);
var calculatorModule = angular.module('calculatorModule', []);

// Add the calculator-controller to module
calculatorModule.controller('calculatorController', ['$scope', function ($scope) {
$scope.calculator = calculatorModel;

Next we add the numberButtonClicked-method to the controller, which sets the number the users enter in the field currentNumber of our model. Additionally the number will be shown on the result-display, also via the model.

$scope.numberButtonClicked = function(clickedNumber) {
	if(calculatorModel.currentNumber === "0") {
		calculatorModel.currentNumber = "";
		calculatorModel.currentDisplay = "";
	}

	calculatorModel.currentNumber += clickedNumber;
	calculatorModel.currentDisplay += clickedNumber;
};

The next three methods (operationButtonClicked, enterClicked and resetClicked) do nothing more, then call their corresponding methods on the model.

$scope.operationButtonClicked = function(clickedOperation) {
	calculatorModel.setOperation(clickedOperation);
};

$scope.enterClicked = function() {
	calculatorModel.calculate();
	calculatorModel.currentDisplay = calculatorModel.result;
};

$scope.resetClicked = function() {
	calculatorModel.reset();
};
}]); // End of controller-block

View

This is the html of the calculator, with the attached AngularJS template. It shows the numbers and the operations of the calculator. Additionally it shows the calculation the user enters, respectively the result of the calculation. Have a look at the screenshot at the top of the page to see what we’ll need to build in html. You’d have two possibilities to create a layout – one is to use a table and the other is to use div. We’ll use the later of these! To do this, we’ll use a div-grid from http://www.responsivegridsystem.com/, which provides a perfect, dynamic grid for our calculator.

The html (without css) looks like in the following code-section:

<!-- Declare the View -->
<div ng-controller="calculatorController&quot>
	<div class="section group"> <!-- Display the result row -->
		<div class="col c3of4">{{ calculator.currentDisplay }}</div>
		<div ng-click="resetClicked()" class="col c1of4">C</div>
	</div>
	<div class="section group"> <!-- Display the 1st number row -->
		<div ng-click="numberButtonClicked(1)" class="col c1of4">1</div>
		<div ng-click="numberButtonClicked(2)" class="col c1of4">2</div>
		<div ng-click="numberButtonClicked(3)" class="col c1of4">3</div>
		<div ng-click="operationButtonClicked('+')" class="col c1of4">+</div>
	</div>
	<div class="section group"> <!-- Display the 2nd number row -->
		<div ng-click="numberButtonClicked(4)" class="col c1of4">4</div>
		<div ng-click="numberButtonClicked(5)" class="col c1of4">5</div>
		<div ng-click="numberButtonClicked(6)" class="col c1of4">6</div>
		<div ng-click="operationButtonClicked('-')" class="col c1of4">-</div>
	</div>
	<div class="section group"> <!-- Display the 3rd number row -->
		<div ng-click="numberButtonClicked(7)" class="col c1of4">7</div>
		<div ng-click="numberButtonClicked(8)" class="col c1of4">8</div>
		<div ng-click="numberButtonClicked(9)" class="col c1of4">9</div>
		<div ng-click="enterClicked()" class="col c1of4">Enter</div>
	</div>
</div>

The calculator layout
I think you can see pretty good, how the layout is done. Foreach row in our group, we have a div with a section group class, with the cells in them. We use the cells directly as our buttons. To make it more visible, that the divs are buttons, we use a css-hover effect, which changes the background, when the users hovers over them.

Binding to the AngularJS template
In the first div-element we have defined the controller in the ng-controller directive. The display-value is directly bound to our model with the expression {{ calculator.currentDisplay }}. Further we have many ng-click directives, which calls the corresponding methods in the calculatorController.

Conclusion

Congratulation, you can now build webapplications with AngularJS! As you can see, they feel very responsive, which will make your users happy. Wait – I could build such an application also with other frameworks! You’re absolutely right about it. The advantage of using AngularJS is the clean code you get behind your application. There’s no ugly spaghetti-code! The code is testable, as it has a clear separation of concerns. And it is quite easy to read the code.

Hope you liked this tutorial. Have any questions or suggestions? Drop me message below!