My approach to solving this problem involves creating a controller variable to hold the current validation pattern.
Controller:
$scope.validationPattern = 'number';
Update the validation pattern when the selected radio button changes:
HTML:
<input type="radio" value="number" ng-model="validationPattern">
<input type="radio" value="percent" ng-model="validationPattern">
Create a custom directive to add validators to ngModel
. This directive should watch for changes in the validationPattern
and update the validator accordingly.
app.directive('regexValidator', function (){
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel) {
$scope.$watch('validationPattern', function() {
// remove previous regex pattern
ngModel.$validators.splice()
// add new regex pattern
ngModel.$validators.push()
});