Zurb Foundation custom form and Angular JS ng-checked

When using the Zurb Foundation custom form checkbox, the angular js ng-checked directive will not mark/unmark the checkbox when there is change occurs in the angular model.

The reason being the “custom form check box” creates new span element for the check box to make the styling easy.

  <label for="checkbox1">
      <input type="checkbox" id="checkbox1" style="display: none;">
      <!-- the following span created by foundation checkbox -->
      <span class="custom checkbox"></span> Label for Checkbox
  </label>

Use the following directive instead of “ng-checked”. Just you need to change “ng-checked” to “ng-checked-foundation”, the params passed to it will be same. It may not be the idle way as it is closely coupled with foundation additional markups. but it solves the issue.

directive('ngCheckedFoundation',['$timeout', function($timeout) {
    function markCheckBox(value, scope, element, attr) {
        //timeout to avoid the foundation javascript action changed by this directive
        $timeout(function() {
                if(value) {
                    attr.$set("checked", true);
                    element.next().addClass('checked');
                }
                else {
                    attr.$set("checked", false);
                    element.next().removeClass('checked');
                }
        }, 200);
    }

    function link (scope, element, attr, ctrl) {
        scope.$watch(attr["ngCheckedFoundation"], function(n,o) {
          if(n != o) {
            markCheckBox(n, scope, element, attr);
          }
        });
        markCheckBox(scope.$eval(attr.ngCheckedFoundation), scope, element, attr);
    }

    return({
        link: link,
        restrict: "A",
    });
}])
This entry was posted in AngularJS. Bookmark the permalink.

One Response to Zurb Foundation custom form and Angular JS ng-checked

  1. Really neat trick. Thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *