我试图在控制器中检索输入[编号]。
我找到了一个解决方案,据说在输入上添加$ 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);
});
谢谢你的帮助!
答案 0 :(得分:3)
你不需要手表。这里的问题是输入在ng-if指令内,该指令定义了自己的范围。估计存储在ng-if
范围内,而不是存储在控制器范围中。
规则或拇指:你的ng模型中总是有一个点。
在您的控制器中,添加
$scope.data = {};
在html中,使用
ng-model="data.estimation"
和
ng-model="data.comments"
答案 1 :(得分:0)
测试新值是不是未定义的还是null或者是虚假的,这是因为角度循环通过监视器和模型几次,这个过程是调用脏检查
$scope.$watch('estimation', function (val, old) {
if (!val) {
return;
}
$scope.estimation = parseFloat(val);
});
答案 2 :(得分:0)
当您的值为""
或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;
}