AngularJS- Example- Add values of the two text fields and show the sum

After writing my previous AngularJS html web page, I am continue to learn the AngularJS. Today I have found a on line editor Plunker for creating, collaborating and sharing my web development programs and examples.

My next example adds the values of two fields and show the result in an label. This is very common task but is helpful to make familiar with the AngularJS expression.

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div ng-app="">
    <p>Add the Numbers</p>
    <p>
      <input type="text" ng-model="val1">+
      <input type="text" ng-model="val2">= {{ val1 *1 + val2 *1}}</p>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

Result will be like this:

Add to text fields in angularjs

You can also edit this example on the plunker: Edit this example

In the above example, I am multipling both text fields with 1 to cast into the numbers.

But in HTML5, If you use the type=”number” then you don’t need to do this. In HTML 5 the above example written as:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div ng-app="">
    <p>Add the Numbers</p>
    <p>
      <input type="number" ng-model="val1">+
      <input type="number" ng-model="val2">= {{ val1 + val2}}</p>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>

2 thoughts on “AngularJS- Example- Add values of the two text fields and show the sum”

Comments are closed.