Neha Sohail
Neha Sohail

Reputation: 239

Apply ng-class to parent element if any checkbox is clicked using Angular?

I have a parent list with a dropdown of checkboxes that you can see if you click on the list. What I want to do is give the parent list class "active" if any of the checkboxes are checked. What's happening now is that I have multiple lists so if the checkbox is checked all lists will get that class when I only want the list the checkboxes are in to get the "active" class. How can I refactor this so only the "active" class is given to the parent list, not all lists?

HTML:

<ul ng-repeat="type in filterTypes">
    <li ng-repeat="filter in type.filters" ng-class="{active:checked}">{{filter.value | uppercase}}
        <ul>
            <li ng-repeat="option in filter.options">
                <label>
                    //if any checkbox is checked, the active class should be given to the parentd list at the way top.
                    <input type="checkbox" ng-model="checked"/>
                    {{option}}
                </label>
            </li>
        </ul>
    </li>
</ul>

Directive:

return {
    restrict: "E",
    templateUrl: 'scripts/directives/all-filters.html',
    link: function(scope, el, attr) {
        scope.filterTypes = dummyData.filters;
    }
}

Upvotes: 0

Views: 1419

Answers (2)

James Buck
James Buck

Reputation: 1640

Apply the checked property to each option by changing the model to ng-model="option.checked"

Then on the li element change the ng-class directive to call a function to check if any option within the filter is checked

$scope.isAnyChecked = function(filter) {
    for (var i = 0; i < filter.options.length; i++) {
        if (filter.options[i].checked) {
            return true;
        }
    }
    return false;
}

Then apply the active class if it returns true

ng-class="isAnyChecked(filter) ? 'active' : ''"

Upvotes: 1

indigo
indigo

Reputation: 1

<input ng-model='checked' ng-change='filter.checked=checked'/>

Upvotes: 0

Related Questions