Search code examples
angularjsangular-ngmodelangularjs-ng-show

bind different value to ng-model on some condition


I have started using Angular and don't have much experience in it.
I am stuck with an issue. I am using ng-show and ng-model.

its like

<tr ng-show="responseValid">
  <td> <input id="nameId" ng-model="model.name"/> </td>
</tr>

I am pre-populating the value in model.name.

Now if response is valid the input tag is shown otherwise not.

but when I submit the form, nameId value is bind by ng-model="model.name"

Issue here is I want model.name should not contain any value if response is not Valid i.e when input tag is hidden. but its not happening.

How can I nullify/empty the value in model.name? Is there anything available that I can use in the tag itself?


Solution

  • When your send your model, check the state of the validResponse and set your model data based in this

    example:

    $scope.sendModel = function(){
      $scope.model.name = $scope.validResponse? $scope.model.name : '';
    }
    

    A more advanced example http://codepen.io/gpincheiraa/pen/mPzmxO