I have an ng-repeat for a table, I want to be able to add a class when <td>
is clicked, and remove the class when un-clicked. Multiple <td>
can be selected at the same time. Right now ALL of the cities are or are not getting the class applies.
For example: (lets say nodes has 100 items)
<tr ng-repeat node in nodes>
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="toggleMe( node.city )" ng-class"{clicked : isClicked()}" >{{node.city}}</td>
</tr>
in my JS
$scope.cityArr = [];
$scope.toggleMe = function(city) {
if ($scope.count > 0) {
angular.forEach($scope.cityArr, function(value) {
if (city === value) {
$scope.clicked = false;
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
});
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
$scope.count = 1;
};
$scope.isClicked = function() {
return $scope.clicked;
};
Right now there is a single
clicked
property on the scope that you're changing and everything refers to that. Try to putclicked
on the node instead...And in the
ngRepeat
...Alternately, the code can use a separate array and $index to set classes:
This approach is useful if you want to separate Model data from View data.
The DEMO
You don't need a special function or controller to accomplish this:
Full Plunker example: http://plnkr.co/edit/1hdcIOfz0nHb91uFWKrv
I could show you the controller I used by it's empty except for the test data. You don't need a function.