简体   繁体   中英

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()">
  </div>
</div>

and this is the function

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

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

You could call a function instead where you set the isItOne variable. In that function you could set the variable to 1 or 2 and 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 = '';
}

Having said all that it might be a better option to just simply unset the model's value on submit in cases when you don't want it to be sent.

use the tag attribute ng-if="your condition" , This will render the tag only when the condition is true. Otherwise it will remove the whole input from DOM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM