Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-ng-clickangularjs-ng-class

How to fix this ng-class toggle comparison?


http://plnkr.co/edit/7v63GXSIDon1QKm1GXCE?p=preview

I have an array which stores the name of each button that is clicked. Once clicked the object is placed into array, I use ng-class to check if the name of the object in the array is the same as the model used to create the button. Then if so toggle the btn-info class on or off.

ng-class="{'btn-info': toggleArray[k].name == m.name}"

Not sure what is wrong with my code but, but it works if you click the buttons in an exact order, from 1 to 3. However once you start randomly clicking buttons it breaks quickly.

plnkr example

The Controller

.controller('ArrayCtrl', ['$scope', function($scope) {

        // Init ArrayCtrl scope:
        // ---------------------
        var vs         = $scope;
        vs.message     = "Add and remove objects from array:";
        vs.toggleArray = [];
        vs.apiArray    = [{name: 'AAA'}, {name: 'BBB'}, {name: 'CCC'}];

        vs.selectBtn = function(btnObj) {
            var index = vs.toggleArray.indexOf(btnObj);
            if (index !== -1) {
                vs.toggleArray.splice(index, 1);
            } 
            else {
                vs.toggleArray.push(btnObj);
            }
        };

    }
]);

The Markup

<div class="model-btns">
    <ul>
      <li ng-repeat="(k, m) in apiArray"
          ng-click="selectBtn(m)"
          class="tag-li">
              <button class="btn"
                      ng-class="{'btn-info': toggleArray[k].name == m.name}">
                  {{m.name}}
              </button>
        </li>
    </ul>
  </div>

  <div class="well list-delete">
      <p>List to delete:</p>
      <ul>
          <li ng-repeat="item in toggleArray">
              {{item}}
          </li>
      </ul>
  </div>

Solution

  • The problem is right here: ng-class="{'btn-info': toggleArray[k].name == m.name}"

    Let's say that all the buttons are "off", so the toggleArray is []. You click the second button, so toggleArray will be [ { "name": "BBB" } ]. But in the ng-class expression for that button, k will be 1. So toggleArray[1] is undefined and the expression is never true, unless you click first the first item so toggleArray has 2 elements.

    You can simply change:

    ng-class="{'btn-info': toggleArray[k].name == m.name}"
    

    to:

    ng-class="{'btn-info': toggleArray.indexOf(m) > -1}"
    

    As illustrated in this plnkr.