Skip to content

Instantly share code, notes, and snippets.

@Risto-Stevcev
Created November 27, 2014 09:16
Show Gist options
  • Save Risto-Stevcev/233a3fd70d2570e4e228 to your computer and use it in GitHub Desktop.
Save Risto-Stevcev/233a3fd70d2570e4e228 to your computer and use it in GitHub Desktop.
Checkbox list directive
var app = angular.module('app', []);
app.controller('TodoCtrl', function($scope) {
$scope.foo = true;
$scope.bar = false;
$scope.baz = true;
$scope.baa = true;
$scope.checkboxes = {
'foo': $scope.foo,
'bar': $scope.bar,
'baz': $scope.baz,
'baa': $scope.baa
};
// Non-encapsulated activity: updates parent scope values
$scope.checkboxInfo = function(name, value) {
console.log('Checkbox "' + name + '" clicked. It is now: ' + value + '.');
$scope[name] = value;
};
// This shouldn't do anything if we delete '$scope[name] = value', since we isolated the scope:
$scope.$watchCollection('[foo, bar, baz, baa]', function() {
console.log($scope.foo, $scope.bar, $scope.baz, $scope.baa);
});
})
// <checklist checkboxes="checkboxes" on-change="checkboxInfo(name, value)"
.directive('checklist', function($timeout) {
return {
restrict: 'E',
scope: {
checkboxes: '=', // create an isolate scope w/ 2-way binding
onChange: '&' // execute a function in the parent scope
},
template:
'<span ng-repeat="(checkboxName, checkboxValue) in checkboxes">' +
'{{ checkboxName }}' +
'<input type="checkbox" ng-model="checkboxValue" ng-change="onChange({name:checkboxName, value:checkboxValue})"/>' +
'</span>',
link: function(scope, element, attrs) {
// Add encapsulated activity as necessary
}
};
});
<div ng-app="app">
<div ng-controller="TodoCtrl">
<!--<span ng-repeat="(checkboxName, checkboxValue) in checkboxes">
{{ checkboxName }}
<input type="checkbox" ng-model="checkboxValue" ng-change="checkboxInfo(checkboxName, checkboxValue)"/>
</span>-->
<checklist checkboxes="checkboxes" on-change="checkboxInfo(name, value)"></checklist>
</div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment