0

I am trying to style a checkbox with an angular directive and I came up with a simple solution. My idea is to have in HTML an input like this

<input type="checkbox" class="checkbox" ng-model="abc1"/>

and I want to create a directive that practically wraps this input inside a label with the class check and adds a div after the input so I can target that div after the input with + from CSS and design on it the states of the input.

So my directive should transform my HTML from what I should previous into this

<label class="check">
    <input type="checkbox" class="checkbox" ng-model="abc1"/>
    <div></div>
</label>

now I created this directive

.directive('checkbox', function() {
    return {
        restrict: 'C',
        transclude: true,
        template: '<label><ng-transclude></ng-transclude><div></div></label>',
        link: function(scope, elem, attrs) {
        }
    };
})

but it doesn't do the layout I want to achieve, I hope someone can help me showing the way to write the directive in order to transform it into that HTML output.

3

1 Answer 1

2

The following directive will wrap the input element to achieve the HTML structure that you want. If the wrapper div is strictly structural and does not contain any directives, then I think it is OK to do this.

  app.directive('checkbox', function() {
      return {
          restrict: 'C',
          link: function (scope, elem, attrs) {
              elem.wrap('<div class="check"></div>');
              elem.after('<div></div>');
          }
      };
  });

Here is a Plunk

Sign up to request clarification or add additional context in comments.

2 Comments

i used this and i get this into the html <!-- checkbox: undefined -->
thank you for this answer, i have used this, the only change is i moved the stuff from the link into the compile function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.