AngularJs:单击后用颜色突出显示整个div卡,选择另一张卡后取消选择

问题描述

<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';
    }

注意:选择卡后,我可以获得卡ID。但是当我单击卡片时,颜色不会改变。

解决方法

您应该使用ng-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;
}