0

I was learning AngularJS. To practically fiddle with it, I was trying to create a basic calculator which read values from input box, does basic calculation and give output.

Here it is:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app=''>
    
    <p>Enter first number: <input type="number" ng-model="input1"></p>
        <p>The number you entered is <mark ng-bind="input1"></mark></p>
    <p>Enter second number: <input type="number" ng-model="input2"></p>
        <p>The number you entered is <mark ng-bind="input2"></mark></p>

        <p>
            Subtraction: {{ (Property.input1|number) + (Property.input2|number) }}
        </p>

        <p>
            Sum: {{ (Property.input1|number) + (Property.input2|number) }}
        </p>
    
        <p>
            Product: {{ (Property.input1|number) * (Property.input2|number) }}
        </p>
        
        <p>
            Division: {{ (Property.input1|number) / (Property.input2|number) }}
        </p>
        
</div>

The values doesn't seem to be automatically getting calculated. Can someone guide?

1 Answer 1

1

You misused the angular ng-model variables evaluation.

For example for the Sum you just need to write

{{ input1 + input2 }}

This is the new working code:

<div data-ng-app=''>

    <p>Enter first number: <input type="number" ng-model="input1"></p>
        <p>The number you entered is <mark ng-bind="input1"></mark></p>
    <p>Enter second number: <input type="number" ng-model="input2"></p>
        <p>The number you entered is <mark ng-bind="input2"></mark></p>

        <p>
            Subtraction: {{ input1 - input2 }}
        </p>

        <p>
            Sum: {{ input1 + input2 }}
        </p>

        <p>
            Product: {{ input1 * input2 }}
        </p>

        <p>
            Division: {{ input1 / input2 }}
        </p>

</div>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @fbid - now it's working perfect. Btw, what does (Property.input1|number) mean? I saw that syntax somewhere but don't know the use.
The " | number " is an angular filter used to format the value. You can find more info here: docs.angularjs.org/api/ng/filter/number
As for the Property.input1, you are referring to a input1 property on a Property Object. In order to use that notation you have to assign ng-model="Property.input1" instead of ng-model="input1" and then something like: {{ (Property.input1 / Property.input2) | number:2 }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.