Skip to content

Instantly share code, notes, and snippets.

@Luxiyalu
Last active August 29, 2015 14:07
Show Gist options
  • Save Luxiyalu/d1236b2e3a5b28eb24f7 to your computer and use it in GitHub Desktop.
Save Luxiyalu/d1236b2e3a5b28eb24f7 to your computer and use it in GitHub Desktop.
AngularJS Directive: Checkbox Set
app.directive 'checkbox', (Page) ->
# Page should be refreshed upon entering the page, within page controller
restrict: 'E'
scope:
hook: '@'
hookedTo: '@'
checkedStoredIn: '='
templateUrl: 'checkbox.html'
link: (scope, element, attr) ->
hookName = scope.hook || scope.hookedTo
Page.checkboxGroups ?= {}
hookObj = Page.checkboxGroups[hookName] ?= {}
childrenArr = Page.checkboxGroups[hookName].childrenArr ?= []
# store parent obj if there is one
if scope.hook then hookObj.parentObj = scope.checkedStoredIn
# else add children to the list
else childrenArr.push(scope.checkedStoredIn)
scope.toggleCheck = ->
scope.checkedStoredIn.checked = !scope.checkedStoredIn.checked
if scope.hook
if (childrenArr.every (e) -> e.checked is true)
childrenArr.forEach (e) -> e.checked = false
else
childrenArr.forEach (e) -> e.checked = true
else
# uncheck the parent checkbox if any of its children unchecked
if hookObj.parentObj? && !(childrenArr.every (e) -> e.checked is true)
hookObj.parentObj.checked = false
app.value 'Page', {}
app.controller 'pageX', (Page) -> Page = {}
<div class="checkbox-outer" ng-click="toggleCheck()">
<div class="checkbox-inner" ng-show="checkedStoredIn.checked"></div>
</div>
checkbox{
cursor: pointer;
.checkbox-outer{
width: 20px;
height: 20px;
border: 1px solid grey;
background-color: white;
}
.checkbox-inner{
width: 100%;
height: 100%;
background-color: black;
}
}
<!-- Have one or zero parent checkbox -->
<checkbox hook="A" checked-stored-in="setA"></checkbox>
<!-- Have multiple children checkbox -->
<checkbox hooked-to="A" checked-stored-in="obj1"></checkbox>
<checkbox hooked-to="A" checked-stored-in="obj2"></checkbox>
<checkbox hooked-to="A" checked-stored-in="obj3"></checkbox>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment