【问题标题】:Angular ng-model expressionAngular ng-model 表达式
【发布时间】:2015-05-30 06:11:30
【问题描述】:

我想问如何使用 angularjs

将输入中的数字四舍五入
<input type="number" ng-model="value1"/>

我希望数字显示 2 位小数并四舍五入。

你能帮忙吗

【问题讨论】:

  • 如果你想显示它,试试角度过滤器: {{value1 |编号:2}}
  • @wZVanG 我认为这会在数字中添加逗号..

标签: html angularjs math rounding angularjs-ng-model


【解决方案1】:

在这种情况下使用$watch 会更合适,它也会倾向于在初始加载时格式化值。

标记

<input type="number" ng-model="value1"/>

代码

$scope.$watch('value1',function(newVal, oldVal){
    if((newVal != oldVal))
       $scope.value1 = newVal?  newVal.toFixed(2): 0;
});

【讨论】:

  • $watch 到底在看什么?
  • @softvar 那我的坏..谢谢提醒..它实际上在value1..我错过了string LOL:D
  • 在这种情况下,我需要为代码中需要舍入的每个字段添加 watch。对 ?我有太多的文本字段和太多的状态
  • 在某些情况下,我没有绑定,它是一个总计字段,所以它就像 我需要四舍五入总是有 2 个小数 (10.00)
【解决方案2】:

你可以使用 ng-change:

<input type="number" ng-model="value1" ng-change="roundNumber()" />

$scope.roundNumber = function(){
    $scope.value1 = Math.round($scope.value1 * 100) / 100;
};

//call function once at bottom of controller for initial run
$scope.roundNumber();

如果这将是您想要的通用功能,或者创建一个指令来执行此操作

【讨论】:

  • 工作并保存观察者。
  • 初次运行怎么样?它会被调用并四舍五入吗?
  • 您可以在您的控制器中调用该函数,它将在控制器初始化并初始更新编号时调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-02
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
相关资源
最近更新 更多