Skip to content

Instantly share code, notes, and snippets.

@muratcorlu
Created February 19, 2014 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muratcorlu/9083292 to your computer and use it in GitHub Desktop.
Save muratcorlu/9083292 to your computer and use it in GitHub Desktop.
A checkbox directive that selects/deselects all records that given for AngularJS
/**
* @ngdoc directive
* @name safe.directive:checkboxAll
*
* @element input
*
* @description
*
* Bir listedeki tüm elemanları seçen bir checkbox kutusu yapmak için pratik bir directive.
*
* @example
<example module="safe">
<file name="script.js">
function Ctrl($scope) {
$scope.items = [1,2,3,4,5];
}
</file>
<file name="index.html">
<div ng-controller="Ctrl">
<p><input type="checkbox" checkbox-all="items.isSelected"> Tümünü seç</p>
<ul>
<li ng-repeat="item in items"><input type="checkbox" ng-model="item.isSelected"> {{ $index }}. secenek</li>
</ul>
</div>
</file>
</example>
*
*/
angular.module('safe').directive('checkboxAll', function () {
'use strict';
return function (scope, iElement, iAttrs) {
var parts = iAttrs.checkboxAll.split('.');
iElement.bind('change', function () {
scope.$apply(function () {
var setValue = iElement.attr('checked');
angular.forEach(scope.$eval(parts[0]), function (v) {
v[parts[1]] = setValue;
});
});
});
scope.$watch(parts[0], function (newVal) {
var hasTrue, hasFalse;
angular.forEach(newVal, function (v) {
if (v[parts[1]]) {
hasTrue = true;
} else {
hasFalse = true;
}
});
if (hasTrue && hasFalse) {
iElement.attr('checked', false);
iElement.addClass('greyed');
} else {
iElement.attr('checked', hasTrue);
iElement.removeClass('greyed');
}
}, true);
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment