Created a custom validation directive that invalidates an input when anything else than a number or space is input. When I change the value programmatically to something that should pass validation, the validation state is not changed.
Check this JSFIDDLE and see for yourself. Any ideas?
<div ng-app="test" ng-controller="Ctrl">
<form name="form">
<input custom-validation type="text" ng-model="box.text" name="text" />
</form>
<button ng-click="change()">Change to numbers only</button>
Why doesn't changing to numbers only pass the validation?
</div>
angular.module('test', []);
angular.module('test').directive('customValidation', function () {
'use strict';
return {
require: '?ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$parsers.push(function removeIllegalCharacters(viewValue) {
if(viewValue === undefined){
ngModelCtrl.$setValidity('numbersAndSpacesOnly', true); //empty value is always valid
} else {
var clean = viewValue.replace(/[^0-9 ]+/g, '');
if (viewValue === clean) {
ngModelCtrl.$setValidity('numbersAndSpacesOnly', true);
} else {
ngModelCtrl.$setValidity('numbersAndSpacesOnly', false);
}
}
return viewValue;
});
}
};
});
angular.module('test').controller('Ctrl', function ($scope, $timeout) {
$scope.change = function () {
$scope.box.text = '12345';
}
});
$formattersarray too.