Search code examples
angularjsradio-buttonangularjs-scopeangularjs-ng-repeat

how to disable radio button dynamically in angularjs using ng-repeat


I have developing some code in Angular JS and i need to disable radio button based on previous selection or change in text box

in JS controller:

PPCO.cusGender = [ {
id : '1',
key : 'Male',
value : 'Male',
disable:false

}, {
id : '2',
key : 'Female',
value : 'Female',
disable:false
}, {
id : '3',
key : 'TG',
value : 'TG',
disable:false
}];

PPCO.changeapplicant = function() {
switch (PPCO.p_SALUTATION.toLowerCase().trim()) {

case 'mrs.':
case 'miss.':angular.forEach(PPCO.cusGender, function(val, key) {
if(val.key != 'Male')
{
val.disable = false;
}
});
break;
}

};

in HTML:

   <input type="text" ng-model="PPCO.changeapplicant" class="color" ng-change="PPCO.changeapplicant()">

<label class="radio" ng-repeat="option in PPCO.cusGender">
    <input type="radio" name="gender"
           ng-model="PPCO.cusgendername" value="{{option.value}}" 
           ng-disabled="option.disable">
    <i></i>
    
</label>

My question is i able change the "ng-disabled =true" value but it is not enabling again. How to make that


Solution

  • I have created this plnkr for this case: https://plnkr.co/edit/F4JZcf6Nm5Csbxbg

    I think you have 2 errors happening at the same time:

    1. You're iterating over one array. So, you don't need to use angular.forEach, you can use array.forEach
    2. Also, most important, you're setting false when the element is mrs. or miss. and it's ok. BUT, you're not setting back to true. So, you will have to include one else clause like this:
    if (['mrs.', 'miss.'].includes($scope.applicant.toLowerCase().trim())) {
      $scope.cusGender.forEach(function(element) {
        element.disable = element.key == 'Male';
      });        
    } else {
      $scope.cusGender.forEach(function(element) {
        element.disable = false;
      });        
    }
    

    I think that would be all!