papakias papakias - 1 year ago 99
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[]">
{{}} - <b>{{item.price}} €</b>

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 = '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 Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download