添加错误结果的文本框数量

时间:2016-12-10 11:56:47

标签: javascript angularjs

我正在创建一个网络应用,其中我的$scope变量

中有一个数字
$scope.total=20;

我有一个文本框

<input type="text" ng-model="amount1" ng-change="amountchange(amount1)" />

当用户在文本框中输入500时,它应该是700,但答案是755,当我从文本框中删除500时,它变为null

我只是想在我的文本框中添加或删除我在这里做错了什么

以下是我为了更好地理解而创建的fiddle

3 个答案:

答案 0 :(得分:1)

这个问题就在这一行:

$scope.total = parseInt($scope.amount1) + parseInt($scope.total);

当您输入更多输入而不是仅播放结果时,您会聚合该值。

你可以做的很简单,添加这个方法:

 $scope.getTotal=function(){
    return parseInt($scope.amount1) + parseInt($scope.total);
}

并将{{total}}替换为:{{getTotal()}}

答案 1 :(得分:0)

每次添加值时都会因为ng-change而发生这种情况 进入500时,

Step1 5 + 200 Step2 50 + 205 Step3 500 + 255

因此它变为755.使用 ng-blur 代替ng-change

 <body data-ng-controller="myController">
  <input type="text" ng-model="amount1" ng-blur="amountchange()" />
 {{total}}
  </body>

<强> DEMO

答案 2 :(得分:0)

您的应用实际上会发生什么,因为您在每次输入更改时都会添加当前数字。

在更新值之前更改为ng-blur或设置超时,使用内置的ng-model-options,现在可以从Angular 1.6(昨天发布)开始,这可能是不错的选择。

<input type="text" ng-model="amount1" ng-change="amountchange()" ng-model-options="{'debounce':{'default':300}}" />

或:

<input type="text" ng-model="amount1" ng-blur="amountchange()" />

但是,我不推荐其中任何一个,这就是原因:

通过不让用户决定他们输入的数据何时提交(例如:按enter或提交按钮),您会使用户不友好并引入不需要的行为,例如当用户点击时在第二个例子中,该号码将一次又一次地添加......

考虑使用表单和ng-submit,因为它更干净,更具语义性,并且还为用户提供了更友好的方式来提交数据。

此外,这是您的其他问题的解决方案:

$scope.amountchange = function () {
        var amount = ($scope.amount1 != '') ? $scope.amount1 : 0;
        console.log(amount)
        if (amount != NaN) {
            $scope.total = parseInt(amount) + parseInt($scope.total);
        }
        else {
            alert("Please enter a number.");
            $scope.amount1 = $scope.total;
        }
 }

要解释:首先,您没有使用任何参数,因此您无需将amount1模型的值传递给指令中的函数。但那不是问题。它将其设置为null的原因是空字段不会解析为0,因此您必须自己设置它。我将值保存到函数的变量amount中,如果它恰好是空的,则分配$scope.amount0的值。