Angular directive for displaying cents as dollars in an input

时间:2016-04-21 21:48:35

标签: angularjs angularjs-directive

So, I have to make an input for currency that stores the value as an integer in cents. I have a directive that almost works, but not quite. The following directive successfully converts the data from the model to the view and after being changed, it successfully strips everything extraneous from what's going back to the model. The problem is that it does not update the view again when the model changes. So, if the input is showing $10.00 and I type in $10.00a, the model will correctly show 1000, but the a remains in the input field.

return {
  require: 'ngModel',
  link: function (elem, $scope, attrs, ngModel) {
    ngModel.$formatters.push(function (val) {
      return '$' + (val / 100).toFixed(2);
    });
    ngModel.$parsers.push(function (val) {
      var replaced = val.replace(/[^\d\.]/g, '');
      var split = replaced.split('.');
      var merged = split[0] + split[1].slice(0, 2)
      return Number(merged);
    });
  }
}

1 个答案:

答案 0 :(得分:1)

要更新viewValue,您需要在新推送的parser中调用这两个函数:

//update the $viewValue
ngModel.$setViewValue(displayedValue);
//reflect on the DOM element
ngModel.$render();

所以指令看起来像:

.directive('myFilter', [
    function() {
            return {
            require: 'ngModel',
                link: function (elem, $scope, attrs, ngModel) {
                    ngModel.$formatters.push(function (val) {
                        return '$' + (val / 100).toFixed(2);
                    });
                    ngModel.$parsers.push(function (val) {
                        //make sure the val is string
                        val = val.toString();
                        //filter the value for displaying, so keep the '$'
                        var displayedValue = val.replace(/[^\d\.\$]/g, '');
                        var replaced = val.replace(/[^\d\.]/g, '');
                        var split = replaced.split('.');
                        var merged = split[0] + split[1].slice(0, 2);
                        var typeConverted = Number(merged);
                        //update the $viewValue
          ngModel.$setViewValue(displayedValue);
          //reflect on the DOM element
          ngModel.$render();
                        return typeConverted;
                    });
                }
            }
        }
])

这里有一个工作小提琴:fiddle_link

另一个类似的超额补贴帖子更多地解释了为什么需要这两行:https://stackoverflow.com/a/36653378/1300334

希望这可以帮到你。