Reset ng-model when ng-show is not active in AngularJS

Hey there, I'm facing a little issue. I have an input field that sometimes needs to be displayed in a form and sometimes not. I'm worried that if someone enters data, hides it, and then hits send, the data will still be sent. That's why I want to clear the input every time it's hidden.

Using ng-change isn't ideal because it restricts my ability to type anything.

<div class="form-group" ng-show="isItOne=='1' || isItTwo=='2'">
  <label class="col-md-1">someName</label>
  <div class="col-md-4">
    <input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
  </div>
</div>

And here's the corresponding function:

$scope.clearWhenChanged = function() {
  $scope.nameModel = "";
};

Answer №1

Remove the display condition and utilize it for managing visibility and model data.

$scope.toggleVisibility = function(){
    if(isItOne=='1' || isItTwo=='2'){
        return true;
    }
    $scope.nameModel= "";
}

Include it in your div:

<div class="input-group" ng-show="toggleVisibility()">

This approach also allows for passing a flag to determine whether to clear the field's value or not .. :)

Answer №2

Instead of directly manipulating the isItOne variable, consider creating a function to handle it. This function can set the variable to either 1 or 2 and also clear the model value.

HTML

<div class="form-group" ng-show="show()">
    <label class="col-md-1">someName</label>
    <div class="col-md-4">
        <input class="form-control" type="text" name="someOtherName" ng-model="nameModel" ng-change="clearWhenChanged()">
    </div>
</div>

Controller

$scope.show = function() {
    if ($scope.isItOne == '1' || $scope.isItOne == '2');
        return true;
    $scope.nameModel = '';
}

Alternatively, it may be more advisable to simply reset the model value upon submission if you do not wish to include it in the data being sent.

Answer №3

To display a tag based on a condition, utilize the tag attribute ng-if="your condition". If the condition is true, the tag will be rendered. If false, the entire input will be removed from the DOM.

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

I'm looking for a way to use AngularJS to automatically populate options in a second select list based on the value selected in the first select list

My current HTML and javascript code is used to fill a select box dynamically using AngularJS: <select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts"> <option value="">Select Account ...

Uncovering the Android tablet browser: A guide

I have implemented the code below to detect mobile/tablet browsers. function isMobile() { var index = navigator.appVersion.indexOf("Mobile"); return (index > -1); } Although it works well for desktop browsers and iOS devices (iPhon ...

Replace character within a table using jQuery

Below is the table content: <table> <tr> <td>"James"</td> <td>"do"</td> <td>"you</td> <td>"like</td> <td>"your life"</td> </tr> </table> <butt ...

Tips for retaining JWT token in local storage even after a page refresh

I am currently working on implementing a login/logout feature and utilizing the context API to manage functions such as storing tokens in local storage and removing them upon logging out. However, I have encountered an issue where the token stored in local ...

A guide to setting up checkbox input in Vue 3 so that it toggles between checked and unchecked states when an

I'm in the process of creating a div container that will contain both an image and a checkbox input element. The checkbox input has a click handler that passes a value to a function, as well as a :value binding which sends the value to an array named ...

Analyzing a problem with a table directive

Here is the custom directive code I have written: currentApp.directive('testList', ['$compile', function ($compile) { return{ restrict: 'E', template: '<table></table>', ...

Troubleshooting a JavaScript Error in AngularJS Module

I created a Module called "app" with some helper functions in the file "scripts/apps.js": angular.module('app', ['ngResource']).run(function($scope){ $scope.UTIL = { setup_pod_variables: function (pods){...} ... }); Now, I want to ...

Utilizing GTM to Implement Dynamic Content Deployment

Can you provide guidance on the entire process from creating a Custom HTML Tag in GTM to executing JavaScript for firing dynamic HTML code, such as displaying a div with text or image based on a specific rule like the referral or cookie variable? For exam ...

Having trouble with my getJSON function, can't pinpoint the error in my code

After collaborating with some fellow stack users, I have developed the following: http://jsfiddle.net/9ywLq/ I am looking to integrate an external json file in order to achieve something similar to this: http://jsfiddle.net/RCB9M/ Currently, I am linki ...

Troubleshooting jQuery.ajax - Why won't it function properly?

I've been struggling to get the ajax service functioning properly. I tried a simple $.get("http://google.com"), but it didn't work. Additionally, this code snippet failed as well: <html> <head> <script src="https://aja ...

Using AJAX to create an interactive dropdown menu with changing options

I have been working on creating a dropdown menu using Ajax. When hovering over the navigation bar, the menu successfully triggers the Ajax function to display the dropdown options. The issue arises when attempting to navigate to another page (show_activi ...

When using Nuxt JS and Jest, a warning message may appear stating "[Vue warn]: Invalid Component definition" when importing an SVG file

I am facing a unique issue only in my Jest unit test where an error occurs when I import an SVG into the component being tested: console.error node_modules/vue/dist/vue.common.dev.js:630 [Vue warn]: Invalid Component definition: found in -- ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

step-by-step guide on implementing autocomplete using google.maps.places.autocomplete in ExtJS

Just to clarify... I initially wrote a code that was error-free before editing this post. However, after reading a comment on creating a Minimal, Complete, and Verifiable example, I became confused. My minimal script did not work properly, I couldn't ...

The script fails to work correctly when displaying the data

Last night, I finally cracked the code on how to transfer data from my form on the index page to the content page, and then display the results inside the content div back on the index page. However, a new challenge has emerged. My Javascript function (re ...

Achieving a transparent background in WebGLRender: A guide

I've been experimenting with placing objects in front of CSS3DObjects using the THREE.NoBlending hack. However, in the latest revisions (tested on r65 and r66), I only see the black plane without the CSS3DObject. Here is a small example I created: in ...

Leverage all the documents obtained from a collection to reference in a Vue component

I am attempting to display all documents from a Firestore collection in a table using refs, but I am unsure about accessing each field for template ref. getDocs(collection(db, "usr")) .then((querySnapshot) => { querySnapshot.forEach((doc ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Is it possible to incorporate jQuery into an AngularJS project?

When it comes to testing, AngularJS is a framework that supports test-driven development. However, jQuery does not follow this approach. Is it acceptable to use jQuery within Angular directives or anywhere in AngularJS for manipulating the DOM? This dilemm ...

Unexpected behavior in Angular service's value exposure

I'm encountering an issue accessing values in my service from the controller. The structure of my service is as follows: angular.module('someApp').factory('someSvc', SomeSvc); function SomeSvc($http) { var colors = []; fu ...