Question

I have a selection of divs with a checkbox each. I'm trying to add a class to the label when each particular checkbox is checked.

I saw I could do it creating a specific model for each box (ng-model:"isChecked-1" and then ng-class="'active' : isChecked-1") and so on, but it doesn't seem very code-efficient.

Any thoughts?

Here's my code:

<div class="col-md-4">
<label class="checkbox-inline btn col-md-12" ng-class="{'active' : isChecked}">
  <input type="checkbox" id="inlineCheckbox1" value="option1" ng-model="isChecked"> Clothes
</label>
</div>
<div class="col-md-4">
<label class="checkbox-inline btn col-md-12" ng-class="{'active' : isChecked}">
  <input type="checkbox" id="inlineCheckbox1" value="option2"> Cars
</label>
</div>
<div class="col-md-4">
<label class="checkbox-inline btn col-md-12" ng-class="{'active' : isChecked}">
  <input type="checkbox" id="inlineCheckbox1" value="option3"> Music
</label>
</div>
Was it helpful?

Solution

Sounds like the job for a directive:

.directive('myCheckbox', function() {

    return{
        restrict: 'E',
        template: '<div class="col-md-4"> \
                      <label class="checkbox-inline btn col-md-12" ng-class="{active : isChecked}"> \
                         <input type="checkbox" id="inlineCheckbox1" value="option1" ng-model="isChecked" />{{text}} \
                      </label> \
                   </div>',
        replace: true,
        scope: {
            text: '@'
        }
    };
})

View:

<my-checkbox text='Clothes'></my-checkbox>
<my-checkbox text='Cars'></my-checkbox>
<my-checkbox text='Music'></my-checkbox>

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top