I am struggling with removing invalid fields from a form in AngularJS. I have reviewed the following threads:
AngularJS: How to clear input type='url' when setting model to = {}
Proper way to clean form with invalid input using AngularJS controller
Unfortunately, none of the suggested solutions seem to be working for me. I have attempted all proposed fixes without success.
This is the relevant HTML snippet within a larger directive template:
...
<form name="providerSearch">
<text-box type="text" ng-model="providerSearchModel.contains.Address" id="SettlementAgentSearch_ProviderSearch_StreetAddress"></input>
<text-box type="text" ng-model="providerSearchModel.contains.City" id="SettlementAgentSearch_ProviderSearch_City"></input>
<text-box type="text" ng-model="providerSearchModel.beginsWith.criteria.Zip" id="SettlementAgentSearch_ProviderSearch_Zip"></input>
</form>
...
<span class="btn btn-link" ng-click="clearSearchFilters()">Clear</span>
Definition of the text-box directive:
...
scope: {
model: '=ngModel',
...
},
...
And within the directive, I have implemented the following code:
...
link: function(scope,elem,attrs,ctrl) {
scope.providerSearchModel = {};
var setProviderModel = function() {
scope.providerSearchModel = {
contains: {},
beginsWith: { filter: 'beginsWith', criteria: {} }
};
};
setProviderModel();
scope.clearSearchFilters = function() {
setProviderModel();
}
}
...
Everything was functioning correctly until the requirement came to add a pattern to the City
field that disallows numbers. After adding a regex pattern to the input field, I encountered difficulties clearing the field if the value is not valid.
I have tried various suggestions from other resources but nothing seems to work. What am I missing?
I attempted modifying scope.clearSearchFilters
as follows, but it did not solve the issue:
scope.clearSearchFilters = function() {
scope.providerSearchModel = {
contains: null,
beginsWith: { filter: 'beginsWith', criteria: null }
};
}
I also tried using $setPristine(), but it did not yield any positive results:
scope.clearSearchFilters = function() {
scope.providerSearchModel = {
contains: null,
beginsWith: { filter: 'beginsWith', criteria: null }
};
scope.providerSearch.$setPristine();
}
Additionally, setting the field explicitly to null or "" did not work either:
scope.clearSearchFilters = function() {
scope.providerSearchModel.City = null; // or scope.providerSearchModel.City = "";
scope.providerSearchModel.City = {
contains: null,
beginsWith: { filter: 'beginsWith', criteria: null }
};
scope.providerSearch.$setPristine();
}
I have created a Plunker to demonstrate my issue, with a character-only validation on the City input field. Test cases can be: test for valid data, and test1 for invalid...