anonym anonym - 14 days ago 6
AngularJS Question

What's the error in this simple AngularJS calculator?

AngularJS newbie here. I'm trying to make a very simple calculator that adds two values in Angular 1.5. The value of

calc.result
doesn't update.

index.html

<body ng-app="Calculator">
<div class="container" ng-controller="calcCtrl as calc">
<input type="number" ng-model="calc.input1">
<span>+</span>
<input type="number" ng-model="calc.input2">
<span>=</span>
<input type="number" ng-model="calc.result">
</div>

<script src="js/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers/calc.js"></script>
</body>


js/app.js

(function() {
angular.module('Calculator', []);
})();


js/controllers/calc.js

(function() {
angular
.module('Calculator')
.controller('calcCtrl', CalculatorControl);

function CalculatorControl()
{
this.input1 = 0;
this.input2 = 0;

this.result = this.input1 + this.input2;
}
})();

Answer

You need to define a computed property to access a value that is dependent on other properties on the controller / scope.

To achieve it, javascript gives you the ability to have a getter on object, that you could use to compute the value, but still can access it as a property, in your case its result.

You could read more about Object.defineProperty on MDN.

Here is what you could do.

(function() {
  angular.module('Calculator', []);
})();

(function() {
  angular
    .module('Calculator')
    .controller('calcCtrl', CalculatorControl);

  function CalculatorControl() {
    this.input1 = 0;
    this.input2 = 0;

    Object.defineProperty(this, 'result', {
      get: function() {
        return this.input1 + this.input2;
      }
    });
  }
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="Calculator">
  <div class="container" ng-controller="calcCtrl as calc">
    <input type="number" ng-model="calc.input1">
    <span>+</span>
    <input type="number" ng-model="calc.input2">
    <span>=</span>
    <input type="number" ng-model="calc.result" ng-disabled="true" />
  </div>
</div>