Created
June 29, 2015 17:32
-
-
Save brandonhesse/d10c51f3cbdea0734652 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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