问题
I have a list of things that I display with ngrepeat
that when they are clicked, produce an additional list of things pertaining to the element selected. My intent is to have the clicked element's background change color so as to show it selected. My issue is when I select another element, they both show as selected. Here is my code:
<div class="breakdownRow pointer" ng-class="{bSelection: selection}" ng-click="selection=true" ng-repeat="m in masterList">
<span class="areaTag">{{m.area}}</span>
<span class="storeNumTag" ng-repeat="v in m.valueList track by $index">{{v.toLocaleString()}} </span>
</div>
As noted before, the first click event works great. bSelection is my css class that has the changing of the background color. Again my issue is that once another element is clicked, the previous doesn't "unselect" per se.
Question: How do I un-give a class to an element when another element has been selected so that only one shows as highlighted at a time?
回答1:
Set and check selection in concrete element:
<div class="breakdownRow pointer" ng-class="{bSelection: m.selection}" ng-click="m.selection=true" ng-repeat="m in masterList">
UPDATE
for selected just one - save not bool, but index selected element. ng-repeat
create own scope, so on click selection created for each item. you can use $parent to create one selection in parent scope.
<div class="breakdownRow pointer" ng-class="{bSelection: $parent.selection==$index}" ng-click="$parent.selection=$index" ng-repeat="m in masterList">
angular.module('app', [])
.controller('controller', function($scope) {
$scope.masterList = [1, 2, 3, 4, 5, 6, 7, 8];
});
.breakdownRow {
border: 1px solid black;
width: 100px;
height: 100px;
}
.bSelection {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-app="app" ng-controller="controller">
<div class="breakdownRow pointer" ng-class="{bSelection: $parent.selection==$index}" ng-click="$parent.selection=$index" ng-repeat="m in masterList">
{{m}}
</div>
</div>
来源:https://stackoverflow.com/questions/33962645/angularjs-how-to-unselect-a-span-when-selecting-another