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

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

问题描述

角是否有一个内置的指令圆输入值?

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

因为我要轮NG-模型中的实际 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=$p$ PVIEW

这真的取决于你想要的工作。它应该限制用户输入?你介意模型和视图的价值有什么不同?如果无效的数字输入是在模型空?这些都是决定你做。该指令将上述无效数字转换成空。

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天全站免登陆