Yogi_Bear Yogi_Bear - 2 years ago 192
AngularJS Question

Clear input ng-model when ng-show is false AngularJS

Hi I have a small problem.
I have an input bar which sometimes need to be shown in a form and sometimes not.
I am afraid that if someone put data and then hide it and press send, the data will be sent. So I want to reset the input each time it is hidden.

ng-change isn't a good idea because it doesn't let my write 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()">

and this is the function

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

Answer Source

take out the show condition and use it to control visibility and model value.

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

call it in your div: <div class="form-group" ng-show="showHideField()">

this also provides the flexibility to pass a flag based on which you can decide whether to clear the field's value or not .. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download