Bind AngularJS Checkbox If Exists in Javascript Object

231 views Asked by At

I have the following users object loaded using a AngularJS factory:

{
    "user_id": "1",
    "groups": [
        {
            "name": "Object Group 10",
            "group_id": 10
        }
    ]
},
{
    "user_id": "2",
    "groups": [
        {
            "name": "Object Group 10",
            "group_id": 10
        },
        {
            "name": "Object Group 12",
            "group_id": 12
        }
    ]
}

I then have groups loaded using a separate factory.

[
    {
        "name": "Object Group 10",
        "group_id": 10
    },
    {
        "name": "Object Group 12",
        "group_id": 12
    }
]

I am trying to bind a checkbox on the user form so that it is checked when the group exists in user.groups array.

See code below:

<div ng-repeat="group in groups">
    <input type="checkbox" ng-model="user.groups">
</div>

Any help would be appreciated.

1

There are 1 answers

0
Fissio On BEST ANSWER
<div ng-repeat="group in groups">
    <input type="checkbox" ng-checked="groupExists(group.group_id, user.groups)">
</div>

In controller:

$scope.groupExists(id, groups) {
    var groupIds = [];
    for (var i=0; i < groups.length; i++) {
        groupIds.push(groups[i].group_id);
    }
    return groupIds.indexOf(id) > -1;
}