0

I am trying to style an input type='checkbox' with an angular directive and my HTML layout looks like this

<div class="checkbox"><input type="checkbox" ng-model="checked1" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked2" /></div>
<div class="checkbox"><input type="checkbox" ng-model="checked3" /></div>

My directive so far looks like this:

myApp.directive('checkbox', function($parse) {
    return {
        restrict: "C",
        compile: function(elem, attr) {
            var model = $parse(attr.ngModel);

            return function(scope, elem, attr) {
                var toggleValue = function() {
                    scope.$apply(function(scope) {
                        model.assign(scope, !model(scope));
                    });
                };

                var updateComponent = function(value) {
                    if(value == true)
                        elem.addClass('checkbox-active');
                    else
                        elem.removeClass('checkbox-active');
                };

                elem.bind('click', toggleValue);

                scope.$watch(model, updateComponent);
            };
        }
    }
});

The problem with this directive is that it searched the ng-model from the not from the input inside the div so it would work if I had the layout like this

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

Can I change something into the compile of the directive so I make it read the ng-model from the input rather than from the div ?

1 Answer 1

3

You do not need to read the ng-model attribute directly like that, ngModel exposes an api via ngModelCtrl. Your directive can do this

require: "ngModel",

and then in the link function, the ngModelController will be available

link: function(scope, elem, attrs, ngModelCtrl) {

In the link function you could check the state of the model and add/remove classes accordingly. You might also be able to just use ngClass and not even use a custom directive.

The docs for ngModelController are here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

As for why it is being applied to the div and not the checkbox? You have class="checkbox" on the div. That is what is activating your directive. Move the class="checkbox" to the input.

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

Comments

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.