0

I am trying to dyanmically display checkbox with labels based on conditional flag. The label values are as follows:

$scope.listA = [
   {
     name : "Sample 1"
   },
   {
     name : "Sample 2"
   }
];
$scope.listB = [
   {
     name : "Result 1"
   },
   {
     name : "Result 2"
   },
   {
     name : "Result 3"
   }
];

This is the html I am using.

<input type="checkbox" ng-repeat="item in listA"/>{{item.name}}

I have a variable based on which i need to display either $scope.listA or $scope.listB.

var mode = "A";

If mode = A then i need to show listA as checkbox labels. If anything else then i need to show listB as checkbox labels.

How can i go about doing this? And how can i make the checkboxes to be checked by default?

2 Answers 2

1

Try using a function to return the values to display rather than the list directly. Like this

<input type="checkbox" ng-repeat="item in whichItems()"/>


$scope.whichItems = function() {
    var ret = listA;
    if($scope.mode != 'A') {
       ret = listB;
    }
    return ret;
};

EDIT: To bind to an array You'll have to have a common value in your data structure and bind to that. For example:

  var mydata = [{itemLabel:'item1',selected:false},  {itemLabel:'item2', selected:false}]

and then in the checkbox you have

   <div ng-repeat="item in whichItems()">
      <input type="checkbox" ng-model="item.selected">{{item.itemLabel}}
   </div>
Sign up to request clarification or add additional context in comments.

2 Comments

And in addition: add a surrounding div (or span or label) around your checkbox and label and set the ngRepeat on this div. Otherwise only the checkboxes will be repeated and not the label.
How can i attach an ng-model for each input as true (for checked) and false(for unchecked)??
0

Scott's answer is correct regarding the array selection. To make your checkbox checked by default, use ng-checked if the checkbox is checked with an expression

<input type="checkbox" ng-checked="expression">

or the checked property if you want it to always be checked by default

<input type="checkbox" checked>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.