Using angularjs, how to perform math operations on

2019-05-12 18:31发布

问题:

I have an HTML file with 2 textboxes, one for value and the other for quantity. The result text at the bottom multiplies value with quantity and show the result.

The intention is to show the sum of all the rows of pairs of textboxes on the screen. To that end, I have an "add new" button which keeps adding additional pairs of textboxes.

The first set of textboxes that appear on the HTML, reflect the size of the "numbers" array of objects containing properties "val" and "qty". The same values are bound to the textboxes.

However, only the first set of values are added on screen. As I keep adding new textboxes and entering new values, the value of the result should change accordingly, but it simply doesn't.

HTML Code

    <div ng-app="adder" ng-controller="addcontrol">
        <table>
        <tr>
            <th>Value</th><th>Quantity</th>
        </tr>
        <tr ng-repeat="number in numbers">
            <td><input type="text" ng-model="number.val"></td>
            <td><input type="text" ng-model="number.qty"></td>
            <td><input type="button" ng-click="deleteNumber($index)" value= "Delete"></td>pp',[]);
        </tr>
        </table>
        <input type="button" ng-click="add()" value="Add new">Result : {{sum}}
    </div>
</body>
</html>

Javascript

var myapp = angular.module('adder', []);
myapp.controller('addcontrol',function($scope){
$scope.numbers = [
    {val:100,
     qty:200,
    }

];

$scope.add = function()
{
    $scope.numbers.push({val:0,qty:0});
};

$scope.deleteNumber = function(val)
{
    numbers.splice(val, 1);
};
var result=0;
angular.forEach($scope.numbers, function(num){
    result+=(num.val * num.qty);

});
$scope.sum = result;

});

What am I doing wrong here?

回答1:

In your code, the calculation of the sum would only be executed once.

You need to add a watch of the scope or bind a function to ng-change event in order to keep the sum updated while you change the numbers.

For example, you can do:

<div ng-app="adder" ng-controller="addcontrol">
    <table>
    <tr>
        <th>Value</th><th>Quantity</th>
    </tr>
    <tr ng-repeat="number in numbers">
        <td><input type="text" ng-change="update()" ng-model="number.val"></td>
        <td><input type="text" ng-change="update()" ng-model="number.qty"></td>
        <td><input type="button" ng-click="deleteNumber($index)" value= "Delete"></td>pp',[]);
    </tr>
    </table>
    <input type="button" ng-click="add()" value="Add new">Result : {{sum}}
</div>

And:

var myapp = angular.module('adder', []);
myapp.controller('addcontrol', function($scope) {
  $scope.numbers = [{
      val: 100,
      qty: 200,
    }

  ];

  $scope.add = function() {
    $scope.numbers.push({
      val: 0,
      qty: 0
    });
  };

  $scope.deleteNumber = function(val) {
    numbers.splice(val, 1);
    $scope.update();
  };

  $scope.update = function() {
    var result = 0;
    angular.forEach($scope.numbers, function(num) {
      result += (num.val * num.qty);
    });
    $scope.sum = result;
  };
});


回答2:

I know this a little bit besides the question but you can do arbitrary arithmetic operations inside a single input field:

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="">
  <input ng-model="expression"/>
  <p>{{$eval(expression)}}</p>
</body>



回答3:

Based on Pylinux's answer: it may seem obvious, however here it is. If you want to add 2 expressions, use the following:

{{$eval(expression1)+ $eval(expression2) }}



回答4:

The code in your controller is only activated once (when the view is rendered). Therefore, your sum is only computed once, before you even get a chance to add any rows. What you need to do is put your calculation into a function so that it can be called repeatedly as needed.

Tong's answer is basically correct, but I think this is a nicer way to do it:

 <div ng-controller="addcontrol">
    <table>
    <tr>
        <th>Value</th><th>Quantity</th>
    </tr>
    <tr ng-repeat="number in numbers">
        <td><input type="text" ng-model="number.val"></td>
        <td><input type="text" ng-model="number.qty"></td>
        <td><input type="button" ng-click="deleteNumber($index)" value= "Delete"></td>
    </tr>
    </table>
    <input type="button" ng-click="add()" value="Add new">Result : {{total()}}
  </div>

and

var app = angular.module('app', [])
.controller('addcontrol', function($scope) {
  $scope.numbers = [{
    val: 100,
    qty: 200,
  }];

  $scope.add = function() {
    $scope.numbers.push({
      val: 0,
      qty: 0
    });
  };

  $scope.deleteNumber = function(val) {
    $scope.numbers.splice(val, 1);        
  };


  $scope.total = function(){
    var total = 0;
    angular.forEach($scope.numbers, function(num) {
      total += (num.val * num.qty);
    });
    return total;
  }
})

Define a total function that loops through the array and returns the appropriate sum. Then you can bind that function to the result field in the view. The benefit of doing it this way is that you don't have to remember to call update() everywhere that might cause the total to change (like ng-change on the textboxes, and in the deleteNumber function). The total just updates automatically.

Here's a demo.