Reset erroneous input fields within nested directives

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...

Plunker Link

Answer №1

After addressing comments:

The issue arises from the discrepancy between displayed and model values, as well as the presence of "undefined". In the original plunker example, include

'<br/>"{{ providerSearchModel.contains.City }}"'
in your mainDirective template (immediately after the button), and enter your two test cases: In test1, you'll notice that the model value is empty (because Angular prevents invalid values from reaching the model).

Simply making the container empty will render all ng-model values undefined, which won't trigger view updates.

To rectify this with pure Angular, you must assign each field value to an empty string or null:

var setProviderModel = function() {
    scope.providerSearchModel = {
      contains: {City:null},
      beginsWith: { filter: 'beginsWith', criteria: null }
    };
  };

If you need to clear an entire form, place all ng-model fields within the same container so you can iterate over its properties and set them to null. For instance,

var clearForm = function() {
    // Set all properties in the ng-model container to null
    for (var prop in scope.providerSearchModel.contains) {
        if (scope.providerSearchModel.contains.hasOwnProperty(prop)) {
            scope.providerSearchModel.contains[prop] = null;
        }
    } 
    scope.providerSearchModel.beginsWith: { filter: 'beginsWith', criteria: null};
    };
  };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to load the parent window of a framed page from a separate domain results in a permission denial issue in Internet

Having an issue with a login page that is hosted within an iframe on a different domain. After a successful login, I am attempting to load the following page: <html> <head> </head> <body onload="parent.window.loca ...

Issue with Three.js Object3D.applyMatrix() causing inaccurate scaling

Exploring the wonders of Three.js version r.71! I have recently delved into Three.js and have come across an interesting challenge. I am working on streaming geometry and handling position/scale/rotation changes between clients using Socket.io and NodeJS. ...

Is it possible to have the Save Success Alert fade out only once?

After incorporating this code snippet, I implemented a fade effect on the success alert whenever it is triggered. However, I noticed that the fade effect only occurs the first time I click "save". Subsequent clicks do not trigger the fade effect, causing ...

How can we transfer parameters in JavaScript?

My vision may be a bit vague, but I'll try to explain it as best as I can. I want to implement multiple buttons that can toggle the visibility of a div (I have this functionality working already). Each button should carry two values (a number and a l ...

Adjusting iframe height dynamically across domains using Jquery

Can this task be accomplished using jQuery alone without using any bulky plugins? While I am aware of the numerous plugins and alternatives available, I am looking for the shortest, most robust, and cleanest solution (ideally utilizing jQuery). Feel free ...

Frequently refreshing a page to display the most recent information without needing to reload the entire

I am seeking a solution for updating the comments section on my website live or every 30 seconds. The comments are fetched from a MySQL database using PHP: <?php $link = mysql_connect('localhost', 'root', ''); ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Looking for Efficiency in Basic JavaScript Arithmetic Operations

I'm having trouble figuring out how to display a total price after a selection is made. My goal is to take the selected value, multiply it by 100, and then use the updateTotal function to show the total. // Gather Data & Prices for Updating Dynamic P ...

`Move the Hover effect to a different element upon mouseover``

In my setup, I have the following arrangement: <div class="menuHomeCategorias Accesoriosclass"> <div class="categoryName Accesorios" name="Accesorios"> <p>Accesorios</p> </div> <img class="categoriasHome" alt="Ca ...

Opacity effect on input text when it exceeds the input boundaries

I'm having an issue: I need to create inputs with different states, including when the text is longer than the input itself. In this case, the extra text should fade out with a gradient transparency effect: https://i.sstatic.net/r5qQu.jpg Here is my ...

What are the reasons behind loading failures and the subsequent failure to resolve promises?

Here is a snippet of code that is part of a larger directive: var imageArray = []; for (var i = 0; i < $scope.abbreviations.length; i++) { imageArray[i] = new Image(); imageArray[i].src = $scope.abbreviations[i].img ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Exploring JSON Data in Node-Red

Currently utilizing Node-Red for the purpose of counting individuals by implementing a flow that can successfully detect faces using visual recognition node. Presented below is the output from the Visual Recognition node taken directly from the Debug windo ...

Tips for sending a callback function in Angular following an HTTP request

Currently, I am leveraging an angular controller to make an http post request to my express route. Subsequently, data is dispatched to my Gmail client via nodemailer. Although the $http request functions properly and emails can be received in my Gmail acco ...

Rotating objects with Three.js on mobile devices

I came across a related question on Stack Overflow about stopping automatic rotation in Three.js while the mouse is clicked. I am now attempting to achieve the same functionality for rotating an object on smartphones and tablets. Given that I have curren ...

Angular and Three JS collaboration leads to misplacement of canvas rendering

Currently in the process of developing code for a website, I am attempting to integrate Three JS with Angular. After conducting some research, I have found that this combination is feasible and I have successfully merged these two libraries. However, I am ...

Angular 8 carousel featuring a dynamic bootstrap 4 design with multiple images and cards displayed on a single slide

I am currently working on a dynamic carousel that should display multiple cards or images in one row. Initially, I faced an issue with the next and previous buttons not functioning properly when trying to display multiple cards in one row. After some onlin ...

How can I define boundaries for objects in Three.js?

How can I customize the border width and color of a polygon/polyhedron created with three.js? The example code below shows a figure, but I'm unsure how to set borders. Are there alternative methods for creating polygons? <html> <head> ...

Navigating through information using Axios in React JS

Issue Currently, I am facing a challenge while trying to iterate through the data retrieved from an API call using Axios in a React.js application. The response is successfully received, but I am encountering difficulties when trying to display the inform ...

ng-click that triggers a dynamic string enclosed in double curly braces {{}}

In my HTML markup, I have a table element with an id attribute that is set dynamically within an ng-repeat loop. <div class="project" ng-repeat="project in data.projects"> <h2> {{projectState.name}} </h2> <table clas ...