Angularjs 带数字输入的 ng 模型

Angularjs ng-model with number input

我正在尝试在我的控制器中检索输入[数字]。

我找到了一个解决方案,说要在输入上添加一个 $scope.$watch。

我试过了,但现在我的号码是 "NaN"。

<div class="offerText">
    <label class="form-inline" ng-if="!admin">What will it cost ? <input type="number" class="form-control" ng-model="estimation"/></label>      
    <label class="form-inline">Comments <textarea rows="3" cols="50" class="form-control" ng-model="comments"></textarea></label>
</div>

在我的控制器中

    $scope.$watch('estimation', function (val, old) {
        $scope.estimation = parseFloat(val);
    });

感谢您的帮助!

测试新值是否未定义或 null 或其他虚假值,发生这种情况是因为 angular 在手表和模型中循环了几次,这个过程称为脏检查

$scope.$watch('estimation', function (val, old) {
        if (!val) {
          return;
        }
        $scope.estimation = parseFloat(val);
    });

当您的值为 ""null 时,您将始终获得 parseFloat 结果为 NaN

$scope.$watch('estimation', function (val, old) {
    return !isNaN(val) ? parseFloat(val): 0; //considering default value is 0 
});

其他可能的方法是使用 ng-change 指令获得变化的价值。

<div class="offerText">
    <label class="form-inline" ng-if="!admin">What will it cost ? <input type="number" class="form-control" ng-model="estimation" ng-change="changedEstimation(estimation)"/></label>      
    <label class="form-inline">Comments <textarea rows="3" cols="50" class="form-control" ng-model="comments"></textarea></label>
</div>

控制器

$scope.changedEstimation =  function(val){
   return !isNaN(val) ? parseFloat(val): 0;
}

你不需要手表。这里的问题是输入在 ng-if 指令中,它定义了自己的范围。估计存储在 ng-if 范围内,而不是存储在控制器范围内。

规则或经验:在你的 ng-model 中总是有一个点。

在您的控制器中,添加

$scope.data = {};

并在 html 中使用

ng-model="data.estimation"

ng-model="data.comments"