Reputation: 111
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?
Upvotes: 0
Views: 674
Reputation: 1690
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>
Upvotes: 1
Reputation: 41
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>
Upvotes: 0