Recently I started exploring Angular js and came across the concept of controllers. So I decided to write a small application two calculate the sum of two numbers.
To start with, what I have understood is that the controllers are used to manage the data flow between the view and data model. It uses $scope for this purpose. So let's create a sample application, to understand it. For this, we create an angular module and add the controller to it:
- var angApp = angular.module('angApp', []);
-
- angApp.controller('sumController', function ($scope) {
-
- }
- });
Further, we will have two properties named firstNumber and secondNumber and a function to calculate their sum, named addNumbers. Controller will receive the data through the $scope function.So the controller will look like:
- var angApp = angular.module('angApp', []);
- angApp.controller('sumController', function ($scope) {
-
- $scope.firstNumber = 1;
- $scope.secondNumber = 2;
-
- $scope.addNumbers = function () {
- return $scope.firstNumber * $scope.secondNumber;
- }
- });
Now it's time to bind the controller to the view. Add an html page and refer to the angular js using external references.
https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js
Add a div with textboxes to get input for 2 numbers, from user. Bind the controller to the div using the ng-controller directive,
- <div ng-app=" angApp " ng-controller='sumController'>
- </div>
Bind the textboxes with model properties using ng-model directive. So our textboxes will look like the following:
- <input type="text" ng-model="firstNumber">
- <input type="text" ng-model="secondNumber">
Finally we display the sum by binding the addNumbers method with a span tag, using angular expressions.
- <span>{{ addNumbers() }}</span>
Complete html code will look like the following:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head>
- <title></title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
- <script type="text/javascript" src="sumController.js"></script>
- </head>
-
- <body>
- <div ng-app="angApp" ng-controller="sumController">
- <fieldset>
- <legend>Calculate sum using Controllers</legend>
- <p>
- Enter the first number:
- <input type="text" ng-model="firstNumber">
- </p>
- <p>
- Enter the second number:
- <input type="text" ng-model="secondNumber">
- </p>
- <p>
- Sum is:
- <span>{{ addNumbers() }}</span>
- </p>
- </fieldset>
- </div>
- </body>
-
- </html>
Run the application and change the values and see the results.
![app]()
Hope you liked my first article on angularjs. Since this is my first one on this topic, any feedback and suggestions are welcome.