Aug 17, 2015

Addition of Two Numbers in AngularJS

Recently, I have started learning AngularJS. AngularJS is a JavaScript Framework, which helps you to declare more HTML Tag Attributes with very powerful functionality.
Let’s Code Something

The first thing, which I tried to do, is to add two numbers and show the result in a TextBox. I coded like below…


<div ng-app="">
    <p>First Number:
        <input type="text" ng-model="a" />
    </p>
    <p>Second Number:
        <input type="text" ng-model="b" />
    </p>
    <p>Sum: {{ a + b }}</p>
</div>




    The ng-model directive binds the value of the input field to the application variable name. So, the variable "a" will contain first TextBox Value and "b" will contain second TextBox value.
    {{ expression }} is used to dynamically bind the result of the expression. Thus, while typing on the TextBoxes, this place will populate with the result of the expression, which is our expected summation.

Alright, Let’s See What Happened Next

The following screenshot would tell you what happened after that.

Looking for Solutions !!!

Now, I researched and found two solutions.
Solution 1 – Using Double Negation

Very beautiful hack. Code as…


<div ng-app="">
    <h3>Using Double Negation</h3>

    <p>First Number:
        <input type="text" ng-model="a" />
    </p>
    <p>Second Number:
        <input type="text" ng-model="b" />
    </p>
    <p>Sum: {{ a -- b }}</p>
</div>

Solution 2 – Using HTML5 Input Type Number

This is the most preferable way of achieving this task as it uses HTML5 Input Type Number. So, when we use this Number Type, then “+” operator will work because the values are numbers by default.


<div ng-app="">
    <h3>Using Input Type Number</h3>

    <p>First Number:
        <input type="number" ng-model="c" />
    </p>
    <p>Second Number:
        <input type="number" ng-model="d" />
    </p>
    <p>Sum: {{ c + d }}</p>
</div>




No comments:

Post a Comment