AngularJs tutorial – create a loan calculator

Hubert Huynh   August 22, 2015   Comments Off on AngularJs tutorial – create a loan calculator

Google Add

This tutorial is meant for AngularJs newbies. AngularJs is a framework and we need to follow its structure. It is structured in a MVC pattern.

We assume that you have read AngularJS on w3school.com. The demo page is not styled with CSS so that AngularJS can be viewed easily.

0- The application

You can view the application at http://www.huberthuynh.com/demos/angularjs-payment/index.html

1- Create a module

This will allow us to create an app. We need only 1 line of code, and the app name is pmtApp

var app = angular.module('pmtApp', []);

2- Initialize the view

<div ng-app="pmtApp">

In this example the view will be within a ‘div’ tag.

3- Create the controller

In the example, we create a controller named pmtCtrl

app.controller('pmtCtrl', function($scope) {
....
}

4- define the scope of the model

app.controller('pmtCtrl', function($scope) {
    $scope.loan = 15000;
    $scope.duration = 4;
    $scope.interest= 2;
    $scope.payment= function() {
	return (($scope.interest/1200.0*$scope.loan)/
           (1.0-Math.pow(1.0+$scope.interest/1200.00, -1.0*$scope.duration*12.0))).toFixed(2);	
    };					
});

5- Inform the view about the controller

<div ng-app="pmtApp" ng-controller="pmtCtrl">

6-Bind the data to view

<div ng-app="pmtApp" ng-controller="pmtCtrl">
Loan___: <input type="number" ng-model="loan"> <br>
Duration: <input type="number" ng-model="duration"><br>
Interest_: <input type="number" ng-model="interest"> <br>
<br>
Monthly Payment: {{"USD " + payment()}}
<div>

8- Source

View source