Search code examples
angularjsng-class

Angularjs ng-class toggle between several classes


This might be a simple question to some of you.

<div class="component"
      ng-class="{'small': small, 'medium': medium, 'large': large, 'xlarge': xlarge}"
      ng-if="component.title == 'Heading'"
      ng-init="editing = false; small = false; medium = false; large = false; xlarge = false">

                  <input class="heading" ng-blur="editing = false" ng-hide="!editing" type="text" placeholder="Heading" ng-model="component.element" />
                  <h2 ng-click="editing = true" ng-hide="editing">{{component.element}}</h2>

                  <div ng-hide="!editing" class="textEditor">
                      <ul>
                          <li>
                              <a href="" ng-click="small = true">
                                  <span class="icon-size small"></span>
                              </a>
                          </li>
                          <li>
                              <a href="" ng-click="medium = true">
                                  <span class="icon-size medium"></span>
                              </a>
                          </li>
                          <li>
                              <a href="" ng-click="large = true">
                                  <span class="icon-size large"></span>
                              </a>
                          </li>
                          <li>
                              <a href="" ng-click="xlarge = true">
                                  <span class="icon-size xlarge"></span>
                              </a>
                          </li>
                      </ul>
                  </div>
               </div>

I need to add class to .component based on clicked a tag from Unordered list. I need to add class small to .component if first item is clicked, then if another item is clicked I need to remove small class and add respective class from that A tag.

Currently it adds them classes but not removing the ones that were added previously.

Basically I need to create a sort of toggle between them 4 classes


Solution

  • I'd say use separate variable for it customClass

    ng-class="customClass"
    

    Then markup

    <ul>
        <li>
            <a href="" ng-click="customClass = 'small'">
                <span class="icon-size small"></span>
            </a>
        </li>
        <li>
            <a href="" ng-click="customClass = 'medium'">
                <span class="icon-size medium"></span>
            </a>
        </li>
        <li>
            <a href="" ng-click="customClass = 'large'">
                <span class="icon-size large"></span>
            </a>
        </li>
        <li>
            <a href="" ng-click="customClass = 'xlarge'">
                <span class="icon-size xlarge"></span>
            </a>
        </li>
    </ul>