Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  186] [ 7]  / answers: 1 / hits: 48054  / 11 Years ago, tue, march 26, 2013, 12:00:00

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?


More From » angularjs

 Answers
9

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;

[#79330] Tuesday, March 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mari

Total Points: 305
Total Questions: 100
Total Answers: 98

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
mari questions
Mon, Feb 18, 19, 00:00, 5 Years ago
Wed, Jan 2, 19, 00:00, 6 Years ago
Tue, Dec 25, 18, 00:00, 6 Years ago
;