四舍五入十进制数的角度指令 [英] Angular Directive to round a decimal number

查看:27
本文介绍了四舍五入十进制数的角度指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 是否有内置指令来舍入输入值?

Does Angular have a built-in directive to round the input value?

数字过滤器在这种情况下不合适,因为我也想对 ng-model 中的实际 val 进行四舍五入.如果我必须写一个,它会是什么样子?

The number filter is not appropriate in this case because I want to round the actual val in ng-model as well. If I have to write one, what would it be like?

推荐答案

您可以使用指令创建双向绑定转换.这是一个简单的例子:

You can create two way binding conversion using directives. Here's a quick example:

app.directive('roundConverter', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elem, attrs, ngModelCtrl) {
      function roundNumber(val) {
        var parsed = parseFloat(val, 10);
        if(parsed !== parsed) { return null; } // check for NaN
        var rounded = Math.round(parsed);
        return rounded;
      }
      // Parsers take the view value and convert it to a model value.
      ngModelCtrl.$parsers.push(roundNumber);
   }
 };
});

http://plnkr.co/edit/kz5QWIloxnd89RKtfkuE?p=preview

这实际上取决于您希望它如何工作.它应该限制用户输入吗?你介意模型和视图值不同吗?模型上的无效数字输入是否应该为空?这些都是你要做出的决定.上面的指令会将无效数字转换为 null.

It really depends on how you want it to work. Should it restrict user input? Do you mind having the model and view value differ? Should invalid number inputs be null on the model? These are all decisions for you to make. The directive above will convert invalid numbers to null.

这篇关于四舍五入十进制数的角度指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆