Search code examples
javascriptangularjsangularjs-directiveangular-ui-router

AngularJs: Highlight the whole div card with color after clicking and deselect after another card is selected


<div class="col-xs-12">
    <ul class="list-group">
         <li ng-repeat="item in shoppingItems" class="list-group-item text-center clearfix">
          <div class="card-body text-dark" ng-click="highlight(item.id)">
            <span style="font-weight:bold">{{item.itemName}}</span>
            <img ng-src="{{ item.imgUrl }}" width="40" height="40"/>
            </div>
         </li>
    </ul>
</div>


 $scope.highlight = function(id){
        console.log("Card id"+id);
        document.getElementById('selectedRow').style.backgroundColor = 'blue';
    }

Note: I can get the card id after I select on the card. But when I click on the card the color doesnt change.


Solution

  • You should use the ng-class to dynamically adding the class:

    https://stackblitz.com/edit/angularjs-bxpwnw?file=home%2Fhome.controller.js

    JS:

    $scope.highlight = function(itm) {
      itm.highlighted = true;
    }
    

    HTML:

    <div class="col-xs-12">
        <ul class="list-group">
            <li ng-repeat="item in shoppingItems" class="list-group-item text-center clearfix">
              <div class="card-body text-dark" ng-click="highlight(item)" ng-class="{'color--highlighted': item.highlighted}">
                <span style="font-weight:bold">{{item.itemName}}</span>
                <img ng-src="{{ item.imgUrl }}" width="40" height="40"/>
                </div>
            </li>
        </ul>
    </div>
    

    CSS:

    .color--highlighted {
      background-color: blue;
    }