Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular js adding two numbers issue

I have this code using angular js:

<!DOCTYPE html >
<html>
<head>
    <title>Untitled Page</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script type="text/javascript">
        function TodoCtrl($scope) {
            $scope.total = function () {
                return $scope.x + $scope.y;
            };

        }
    </script>
</head>
<body>
   <div ng-app>
  <h2>Calculate</h2>

  <div ng-controller="TodoCtrl">
    <form>
        <li>Number 1: <input type="text" ng-model="x" /> </li>
        <li>Number 2: <input type="text" ng-model="y" /> </li>
        <li>Total <input type="text" value="{{total()}}"/></li>       
    </form>
  </div>
</div>

</body>
</html>

I am able to do multiplication, division and subtraction but for addition, the code just concatenates the x and y values (i.e. if x = 3 and y = 4, the total is 34 instead of being 7)

What am I doing wrong?

like image 839
mpora Avatar asked Mar 26 '13 22:03

mpora


3 Answers

If that is indeed the case then what is happening is the values that are being passed in for x and y are being treated as strings and concatenated. What you should do is convert them to numbers using parseInt

return parseInt($scope.x) + parseInt($scope.y);

or if you prefer brevity

return $scope.x*1 + $scope.y*1;
like image 84
Travis J Avatar answered Oct 10 '22 15:10

Travis J


You want this:

   return parseFloat($scope.x) + parseFloat($scope.y);

+ overrides string concatenation when you have 2 strings. You'll need to cast them to integers or floats explicitly. -,*,/ will all cast to numbers if possible.

like image 45
Ben McCormick Avatar answered Oct 10 '22 17:10

Ben McCormick


That is because the concatenation has higher precedence over addition operation or the Plus (+) Operator. Since, Minus Operator (-) works just fine , here is a Simple Hack!

<script type="text/javascript">
    function TodoCtrl($scope) {
        $scope.total = function () {
            //Subtracting a Zero converts the input to an integer number
            return (($scope.x - 0) + ($scope.y - 0));
        };

    }
</script>

You could as well do this:

<form>
    <li>Number 1: <input type="text" ng-model="x" /> </li>
    <li>Number 2: <input type="text" ng-model="y" /> </li>
    <li>Total <input type="text" value="{{(x-0) + (y-0)}}"/></li>       
</form>
like image 2
indieNik Avatar answered Oct 10 '22 17:10

indieNik