angular js 添加两个数字的问题 [英] angular js adding two numbers issue

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

问题描述

我有这个使用 angular js 的代码:

<头><title>无标题页</title><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script><script type="text/javascript">功能 TodoCtrl($scope) {$scope.total = 函数 () {返回 $scope.x + $scope.y;};}<身体><div ng-app><h2>计算</h2><div ng-controller="TodoCtrl"><表格><li>数字 1:<input type="text" ng-model="x"/><li>数字 2:<input type="text" ng-model="y"/><li>Total <input type="text" value="{{total()}}"/></li></表单>

</html>

我可以做乘法、除法和减法,但是对于加法,代码只是连接 x 和 y 值(即如果 x = 3 和 y = 4,总数是 34 而不是 7)

我做错了什么?

解决方案

如果情况确实如此,那么所发生的就是为 x 和 y 传入的值被视为字符串并进行连接.您应该做的是使用 parseInt

将它们转换为数字

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

或者如果你喜欢简洁

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

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?

解决方案

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;

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

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆