PTN
PTN

Reputation: 1692

Clear input ng-model when ng-hide is true AngularJS

I am trying to set up this <input> in a way that when ng-hide is true, whatever in ng-model is reset.

<input type="text" class="form-control" ng-model="account.AccountName" ng-hide="account.AccountStatus == 'Terminated'">

So there will be a dropdown list containing Active and Terminated binded to ng-model="account.AccountStatus". When it's Active, the field Account Name would have text there. I want to make it that when I switch to Terminated, that input field is hidden and account.AccountName is set to "".

Upvotes: 4

Views: 1761

Answers (3)

Mike Jerred
Mike Jerred

Reputation: 10555

You could bind the AccountStatus variable to a function that clears the AccountName variable, e.g. in your controller:

$scope.$watch('AccountStatus', function(status) {
    if (status == 'Terminated')
        $scope.AccountName = null;
})

Upvotes: 2

You may use [ng-change] attribute and define function in the controller to handle change event and reset AccountName if AccountStatus equals to 'Terminated'. Example:

    <input type="text" class="form-control" ng-model="account.AccountName" ng-hide="account.AccountStatus == 'Terminated'">
    <select ng-change="selectChange()" name="selectState" ng-model="account.AccountStatus">
      <option value="Active">Active</option>
      <option value="Terminated">Terminated</option>
    </select>
    <script>
      angular.module('examleModule', []).controller('exampleController',['$scope', function($scope) {
         $scope.account = {
            AccountStatus: 'Active',
            AccountName: ''
         };

     $scope.selectChange= function() {
        // Reset AccountName if AccountStatus=='Terminated'
        if($scope.account.AccountStatus=='Terminated')
             $scope.account.AccountName = '';      
     };
   }]);
   </script>

Upvotes: 3

oseintow
oseintow

Reputation: 7391

Do

<select ng-model="account.AccountStatus" 
   ng-change="resetAccountName(account.AccountStatus == 'Terminated')">
     .......
     options goes here
     .......
</select>

then in your controller create the function resetAccountName like this

 $scope.resetAccountName = function(flag){
   if(flag == true){
      $scope.account.AccountName = "";
   }
 }

Upvotes: 2

Related Questions