0

I'm learing Angular JS and I'm currently in the process of understanding what it does and what it does not.

I'm trying to do a simple calculator that has two numbers and an operator as input.

I'm having a hard time to understand how to evaluate the operator on the binding. This is my code:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id='example' ng-app=''>
  <input ng-model='number1' type='number'>
  <select ng-model='operation' ng-options="op for op in ['+', '-', '/', '*']"></select>
  <input ng-model='number2' type='number'>
  <div id='output' ng-bind="number1 + number2"></div>
</div>

Instead of number1 + number2 I want it to be something like eval(number1 operator number2) but don't know how to do it.

2 Answers 2

2

You can use the if statement

<input ng-model='number1' type='number'>
<select ng-model='operation' ng-options="op for op in ['+', '-', '/', '*']"></select>
<input ng-model='number2' type='number'>
<div ng-if="operation == '+'"><div id='output' ng-bind="number1 + number2"></div></div>
<div ng-if="operation == '-'"><div id='output' ng-bind="number1 - number2"></div></div>
<div ng-if="operation == '/'"><div id='output' ng-bind="number1 / number2"></div></div>
<div ng-if="operation == '*'"><div id='output' ng-bind="number1 * number2"></div></div>

code

Sign up to request clarification or add additional context in comments.

1 Comment

But the id should be unique alongside the page. what $("#output") would return?
0

I would do the following

In controller:

$scope.operators = {
    '+': function(a, b) { return a + b },
    '-': function(a, b) { return a - b },
    //...rest of the operators
};

in view:

<div id='output' ng-bind="operators[operation](number1, number2)"></div>

This is will keep your view cleaner without any redundant divs.

Inspired by this SO answer: How to call and execute an operator from string?

1 Comment

seems like the best idea so far but my intention was to use only HTML and the ng properties.

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.