Skip to content

Instantly share code, notes, and snippets.

@brandonhesse
Created June 29, 2015 17:32
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 brandonhesse/d10c51f3cbdea0734652 to your computer and use it in GitHub Desktop.
Save brandonhesse/d10c51f3cbdea0734652 to your computer and use it in GitHub Desktop.
ng.directive('smGroup', ['$cacheFactory', '$log', function ($cacheFactory, $log) {
var cache = $cacheFactory('smGroupModelCache');
function searchAndDestroy(array, target) {
var index, found;
if (!Array.isArray(array)) {
return false;
}
// Search for the element
index = array.indexOf(target);
found = Boolean(~index);
if (found) {
array.splice(index, 1);
}
return found;
}
function postLink(scope, elm, attrs, ngModelCtrl) {
if (elm.attr('type').toLowerCase() !== 'checkbox') {
$log.warn('$element is not of a [type="checkbox"]! @', elm[0]);
}
var groupName, groupies, model, destroyers = [];
groupName = attrs.smGroup;
if (!groupName) {
$log.error('Group name is not defined! @', elm[0]);
}
groupies = cache.get(groupName) || cache.put(groupName, []);
model = {model: ngModelCtrl, name: elm.attr('name')};
groupies.push(model);
ngModelCtrl.$validators.groupRequired = function($modelValue) {
var some = groupies.some(function(groupie) {
if (groupie === model) {
return Boolean($modelValue);
}
return Boolean(groupie.model.$modelValue);
});
return some;
};
destroyers.push(
scope.$on('$destroy', function () {
destroyers.forEach(function (destroyer) {
destroyer();
});
searchAndDestroy(groupies, model);
groupies.forEach(function (groupie) {
groupie.model.$validate();
});
})
);
}
return {
restrict: 'A',
require: 'ngModel',
link: postLink
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment