AngularJS - ngRepeat & checkboxes

by Sajeetharan Sinnathurai

HTML

<div ng-controller="MyCtrl">
    <table>
    <tr ng-repeat="appObj in myAppObjects">
        <td>{{appObj.id}}
            <input type="checkbox" ng-model="appObj.cb1"></td>
        <td><input type="checkbox" ng-model="appObj.cb2"></td>
        <td><input type="checkbox" ng-model="appObj.cb3"></td>
        <td><input type="checkbox" ng-model="appObj.cb4"></td>
        <td><input type="checkbox" ng-model="appObj.cb5"></td>
    </tr>
    </table>
    {{myAppObjects}}
    <br>list of checked items: {{checkedItems()}}
</div>

JavaScript

function MyCtrl($scope) {
    $scope.myAppObjects = [
        {
        id: 1,
        cb1: true,
        cb2: false,
        cb3: true,
        cb4: true,
        cb5: false
        },
        {
        id: 2,
        cb1: false,
        cb2: false,
        cb3: true,
        cb4: false,
        cb5: true
        }];
    $scope.checkedItems = function() {
        var checkedItems = [];
        angular.forEach($scope.myAppObjects, function(appObj, arrayIndex){
            angular.forEach(appObj, function(cb, key) {
                if(key.substring(0, 2) == "cb" && cb) {
                    checkedItems.push(appObj.id + '-' + key)
                }
            })
        })
        return checkedItems
    }
}