Skip to content

Instantly share code, notes, and snippets.

@0x3333
Created April 27, 2016 22:30
Show Gist options
  • Save 0x3333/083dfda464f3b6e69eb9a14ab98cb8db to your computer and use it in GitHub Desktop.
Save 0x3333/083dfda464f3b6e69eb9a14ab98cb8db to your computer and use it in GitHub Desktop.
AngularJS 1.X Checkbox Directive

AngularJS 1.X Checkbox Directive

Will evaluate an expression when checked state is changed. A $checked parameter will be passed to expression with checked state.

<input type="checkbox" checkbox-change="changeMyValue($checked)">

var checkboxChangeDirective = function($parse) {
    return {
        restrict: 'A',
        compile: function($element, attr) {
            var fn = $parse(attr["checkboxChange"], null, true);

            return function ngEventHandler(scope, element) {
                element.change(function() {
                    var checked = this.checked,
                        callback = function() {
                        fn(scope, { $checked: checked });
                    };
                    scope.$apply(callback);
                });
            };
        }
    };
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment