Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...