角JS两数相加的问题 [英] angular js adding two numbers issue

查看:159
本文介绍了角JS两数相加的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用了棱角分明的js有这个code:

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>

我能够做乘法,除法和减法但除此之外,code只是并置x和y的值(即如果x = 3和y = 4,一共是34个而不是被7)

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)

我在做什么错了?

推荐答案

如果的确是这样,那么正在发生的事情是,正在通过在x和y的值都被视为字符串,然后连接起来。你应该做的是将其转换为使用数字 parseInt函数

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);

或者如果你preFER简洁

or if you prefer brevity

return $scope.x*1 + $scope.y*1;

这篇关于角JS两数相加的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆