Angularjs Bind Multi-Checkbox

by manoj

HTML

<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
<div ng-app="checkbox" ng-controller="homeCtrl">
    <div ng-repeat="item in list">
        <input type="checkbox" checkbox-group />
        <label>{{item.value}}</label>
    </div>{{array}}
    <br>{{update()}}
</div>

JavaScript

var app = angular.module('checkbox', []);

app.controller('homeCtrl', function ($scope) {
    $scope.array = [1, 5];
    $scope.array_ = angular.copy($scope.array);
    $scope.list = [{
        "id": 1,
            "value": "apple",
    }, {
        "id": 3,
            "value": "orange",
    }, {
        "id": 5,
            "value": "pear"
    }];

    $scope.update = function () {
        if ($scope.array.toString() !== $scope.array_.toString()) {
            return "Changed";
        } else {
            return "Not Changed";
        }
    };

})
    .directive("checkboxGroup", function () {
    return {
        restrict: "A",
        link: function (scope, elem, attrs) {
            // Determine initial checked boxes
            if (scope.array.indexOf(scope.item.id) !== -1) {
                elem[0].checked = true;
            }

            // Update array on click
            elem.bind('click', function () {
                var index = scope.array.indexOf(scope.item.id);
                // Add if checked
                if (elem[0].checked) {
                    if (index === -1) scope.array.push(scope.item.id);
                }
                // Remove if unchecked
                else {
                    if (index !== -1) scope.array.splice(index, 1);
                }
                // Sort and update DOM display
                scope.$apply(scope.array.sort(function (a, b) {
                    return a - b
                }));
            });
        }
    }
});