Monday, March 13, 2017

How I built a simple calculator using AngularJS in less than 15mins

Hi there! Yeah you read that right!
I'm starting to love AngularJS framework. I should have used this framework for my previous academic projects since this feature called data binding eliminates much of the code.

Before we start there are three components of AngularJS that you should know to understand how this simple calculator works. 😏 
  1. ng-app - This directive defines and links an AngularJS application to HTML.
  2. ng-model - Binds the values of AngularJS application data to HTML input controls.
  3. ng-bind - Binds the AngularJS application to HTML tags
  4. ng-controller - It defines the application controller.Controller is a JavaScript Object created by                           a standard JavaScript Constructor.

Now that we know these main components lets get started!!!

If you have read my previous articles on JavaScript then you'll see that I have separated the HTML part and JavaScript part in separate files and I did the same here.


HTML part!




As you can see this HTML code is fairly simple! The ng-app and ng-controller is declared in a single div element rather than declaring them in an extra level.

And also we have 2 input boxes and select element which has ng-model to bind the values entered into the input boxes to the AngularJS application data. 

The last part we have a function call {{ result() }} in the directive which is interesting! 

JavaScript part!




An AngularJS module (angular.module() ) defines an application and it is a container for the different parts of an application,
In the JavaScript part we create a angular module and controller and we declare the result as an attribute of the current scope. 
And when you make a controller in AngularJS, you pass the $scope object as an argument.

.controller( "      " , function($scope) {

 $scope.result = function() {}

}

And the last part of the JavaScript code calculating the math operations are simple which is familiar hence not worth going in detail.

Happy coding!!! ✌👍

--Ashen Jayasinghe--