简体   繁体   中英

angular directive to style a checkbox

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM