ngModelController $parsers function not called consistently #12544
Comments
This is better illustrated with an example:
There are several "Angular" ways to properly handle this, e.g.: ngModel.$parsers.push(function (value) {
var numbers = value.replace(/\D/g, '');
if (numbers !== value) {
ngModel.$setViewValue(numbers); // Update the `$viewValue`
ngModel.$render(); // Update the element's displayed value
}
return numbers;
}); I am closing this, as everything seems to work as expected. |
This problem occurs with repeat keystrokes any time that new $viewValue is not committed. The suggested use of $setViewValue in the $parsers collection is sometimes avoided with a preference to directly setting $viewValue in some forums. The following would also work:
If you want to avoid any recursion pitfalls at all then $$lastCommittedViewValue could be updated directly if you don't mind violating encapsulation. Unfortunately when infinite recursion does occur in these functions I've seen cases where it isn't reported to the console even after max occurrences. Worth taking the few minutes to put a break point in during testing and verify any recursions. |
When enforcing input values to conform to certain rules using an ngModelController $parser function, the $parser function isn't called on repeated "invalid" keystrokes, which allows invalid characters to get added.
In the example below, the directive is meant to remove all non-digit characters. it mostly works, but if you type the same non-digit character twice in a row (e.g. 'xx'), a single 'x' will show up in the input. if you type 'x' a third time, it will remove the 'x'.
I've also included a failing test case.
all code is running at http://codepen.io/visnup/pen/YXgLVq?editors=101
directive usage
directive
failing test case
This has been brought up before in #10700.
The text was updated successfully, but these errors were encountered: