Alexandr
Alexandr

Reputation: 1031

AngularJS Expression of multiple inputs

I really didnt know how to title this question:

Is it possible to do this only with AngularJS?:

<input ng-model="number1">
<input ng-model="number2">
<input ng-model="sum" value='{{number1 + number2}}'>

<h1>Multiply sum by 2 NOT WORKING: {{sum * 2}}</h1>

https://jsfiddle.net/fthnvv5s/

I hope you got the point, and will be very grateful not to downgrade me, and yes, I know i can use jQuery.

Upvotes: 2

Views: 73

Answers (1)

alphapilgrim
alphapilgrim

Reputation: 3975

There are many ways to do this, here's one way. Hope it helps.

function exampleController($scope) {
  $scope.number1 = 0;
  $scope.number2 = 0;
  $scope.$watchGroup(['number1','number2'], function(newval){
    if(!newval) return;
    $scope.sum = parseInt(newval[0]) + parseInt(newval[1]);
  });
}

angular
  .module('example', [])
  .controller('exampleController', exampleController);
.row {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div class="container-fluid" ng-app="example">
  <div class="container" ng-controller="exampleController">
    <input class="row" ng-model="number1">
    <input class="row" ng-model="number2">
    <input class="row" ng-model="sum">

    <h1>Multiply sum by 2: {{sum * 2}}</h1>
  </div>
</div>

Upvotes: 3

Related Questions