Karan Singh Kochar Karan Singh Kochar - 1 year ago 140
Javascript Question

how to use ng-checked and ng-disabled with ng-repeat

i was facing problems with ng-repeat while using ng-checked and ng-disable with it

<div ng-repeat="module in modulelist>
<input id="switch{{$index}}" ng-init="setState($index);" type="checkbox" ng-checked="switch.checked" ng-disabled="switch.disable" ng-click="toggle($index,light.name)" />


i am using ng-init to load the state of the checkbox
module.status
from the modulelist ,status can be ON ,OFF or unknown ,for unknown i want to disable the cb ,for ON/OFF i want to check/uncheck the cb. i tried using

$scope.switch={checked:true};


but it is applying the property to all the checkbox
i know that 'switch.checked'/'switch.disable' should be unique for each CB to make a unique change,but i am not able to do so.

please help

Answer Source

This looks like what you need. Each module is the model for the input, so you can use ternaries for those attributes.

<div ng-repeat="module in modulelist>
<input id="switch{{$index}}" 
    ng-init="setState($index);" type="checkbox"
    ng-checked="module.status==='ON'"
    ng-disabled="module.status==='unknown'"
    ng-click="toggle($index,light.name)" />

Using the below code is using the same scope variable for all the checkboxes, which is why changing one will change them all.

$scope.switch={checked:true};

Edit

In response to the OP's comment, something like this:

ng-checked="handleCheckStatus(module.status)"

and then on $scope:

$scope.handleCheckStatus = function(status) {
   switch (status) {
       case 'ON':
           return true;
       break;
       case 'OFF':
           return false;
       break;
       // and so on
   }
}