Skip to content

Instantly share code, notes, and snippets.

@LordJohn42
Created June 9, 2016 09:04
Show Gist options
  • Save LordJohn42/ecea84273c6ffd0f12eb920c7a10ac59 to your computer and use it in GitHub Desktop.
Save LordJohn42/ecea84273c6ffd0f12eb920c7a10ac59 to your computer and use it in GitHub Desktop.
Checkbox group AngularJS.
<input checkbox-group="true" type="checkbox" id="checkbox-toogle-all">
<div id="checkBoxContainer" ng-repeat="selectedItem in list">
<input type="checkbox" checkbox-group/>
<label class="">{{selectedItem.value}}</label>
</div>
$scope.array = [];
$scope.list = [
{
"id": 0,
"value": "Value 0"
},
{
"id": 1,
"value": "Value 1"
},
{
"id": 2,
"value": "Value 2"
},
{
"id": 3,
"value": "Value 3"
},
{
"id": 4,
"value": "Value 4"
},
{
"id": 5,
"value": "Value 5"
}
];
.directive("checkboxGroup", function () {
var elements = [];
return {
restrict: "A",
link: function (scope, elem, attrs) {
if (attrs.checkboxGroup !== 'true') {
elements.push(elem);
}
elem.bind('click', function () {
if (attrs.checkboxGroup !== 'true') {
var index = scope.array.indexOf(scope.selectedItem.id);
if (elem[0].checked) {
if (index === -1) {
scope.array.push(scope.selectedItem.id);
}
}
else {
if (index !== -1) scope.array.splice(index, 1);
}
scope.$apply(scope.array);
} else {
//Если кнопка выбрать все нажата
if (elem[0].checked) {
// Выделяем все элементы, checked = true;
angular.forEach(elements, function (key, value) {
if (key[0].checked !== true) {
key[0].checked = true;
}
});
// Добавляем в массив эти значения
angular.forEach(scope.list, function (key, value) {
index = scope.array.indexOf(key.id);
if (index === -1) {
scope.array.push(key.id);
}
});
} else {
angular.forEach(elements, function (key, value) {
key[0].checked = false;
});
angular.forEach(scope.list, function (key, value) {
scope.array.splice(key.id);
});
}
scope.$apply(scope.array);
}
});
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment