papakias papakias - 1 month ago 18
AngularJS Question

How to programmatically check checkbox with dynamic model name?

I have created a some checkboxes with dynamic model name like this:

<label ng-repeat="item in main.itemDetails">
<input type="checkbox" checklist-value="item.price"
ng-click="itemChanged(item)" ng-model="checkboxes[item.name]">
{{item.name}} - <b>{{item.price}} €</b>
<br>
</label>


In my controller, I want to check some checkboxes if their model's name exists in array $scope.selectedItems.

I'm trying to do something like this but it isn't working:

for (var i = 0, j = $scope.selectedItems.length; i<j; i++) {
$scope['selectedItems[i].name'].isChecked = true;
}


for example if item.name = 'Item1' I want the model to be named $scope.Item1 and later I want to call
$scope.Item1.isChecked = true;


What Am I doing wrong here?

Answer

Your are storing the model in the $scope.checkboxes, so you can set its value to true like the code below.

for (var i = 0, j = $scope.selectedItems.length; i<j; i++) {
    $scope.checkboxes[$scope.selectedItems[i].name] = true;
}
Comments