Angular does not currently control change attributes; it only controls related values. There are a couple of Angular questions that discuss this further NgMinlength and NgMaxlength - sets the length value dynamically does not work and the input does not look ngPattern value for changes . Two key caitp comments:
The generic Angular template does not respond to actual changes in the attribute value, but rather respond to changes in the associated value.
and
The fact is that at present the template does not come from the analyzed variable expression / scope, it is just a string literal rotated into a regular expression, therefore, observing changes in this means essentially looking at the value of the DOM attribute for a change. I think I mentioned that on another issue regarding this a few weeks ago. Viewing changes to the actual DOM attribute is quite different from what Angular typically does.
Given these issues and considering how Angular implements ngPattern , one way to deal with this is to add a directive that monitors Angular eval() the ngPattern attribute for changes. If he sees a change, he can evaluate the regular expression ngPattern and setValidity .
This gives us dynamic monitoring of attribute values. Here's the directive:
.directive('updatePattern', function() { return { require: "^ngModel", link: function(scope,element,attrs,ctrl) { scope.$watch(function() { // Evaluate the ngPattern attribute against the current scope return scope.$eval(attrs.ngPattern); }, function(newval, oldval) { //Get the value from `ngModel` value = ctrl.$viewValue; // And set validity on the model to true if the element // is empty or passes the regex test if (ctrl.$isEmpty(value) || newval.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }); } } });
And we will add our new update-pattern directive in html:
<input name="postalCode" type="text" class="form-control" data-ng-model="editAddress.postalCode" data-ng-required="selectedCountry.requiresPostal" ng-pattern="selectedCountry | countryToPostalCodeRegex" maxlength="12" update-pattern />
working violin
source share