AngularJS how to force an input to be re-rendered on blur

前端 未结 5 1635
攒了一身酷
攒了一身酷 2020-12-24 14:17

I have some custom validation code, which includes a $formatter. (I store currency in pence for correctness, but display in pounds.pence.)

If the user types \'10\'

5条回答
  •  情书的邮戳
    2020-12-24 14:51

    A little improved: Do not reformat if the value is not valid (in my case invalid text just got cleared on blur, which is bad for usability, I think).

    Also, like Dark Falcon said: Formatters should be iterated backwards.

    Finally do not iterate over arrays with for-in, at least not without checking hasOwnProperty() (for me the code crashed because it treated Array.find() as a formatter).

    // Reformat text on blur
    elements.bind('blur', function() {
        if(!ngModel.$valid) {
            return;
        }
        var viewValue = ngModel.$modelValue;
        var formatters = ngModel.$formatters;
        for (var i = formatters.length - 1; i >= 0; --i) {
            viewValue = formatters[i](viewValue);
        }
        ngModel.$viewValue = viewValue;
        ngModel.$render();
    });
    

提交回复
热议问题