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.

Filipe Teixeira
  • 479
  • 1
  • 7
  • 26

2 Answers2

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

Abdennacer Lachiheb
  • 4,388
  • 7
  • 30
  • 61
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?

Community
  • 1
  • 1
avatsaev
  • 93
  • 1
  • 7