Change the class of only one element in ngRepeat
I have ng-repeat. And I would like to change the class of just this element vs the whole group.
<button ng-class="defaultClass" ng-repeat="tube in node.Tubes" ng-click="toggleBtn(tube)">{{"Tube " + ($index + 1)}}</button>
with the above HTML on mine, ng-click
I can pipe a tube that really only gives me the data passed from the API if I console.log(this)
can see the class name in the element called $$watchers
, but it seems weird to change it from there.
$scope.toggleBtn = function (element) {
console.log(element);
console.log(this);
}
In my controller I have $scope.defaultClass = "btn btn-off";
, but if I change it using a function, it changes every item.
How do I change the class of the selected item?
source to share
Continuing comments. Than you can't use the $ scope variable for this, because as you said it would be the same. To solve this problem, you need to use the ng class correctly. Docs: https://docs.angularjs.org/api/ng/directive/ngClass (see example at the bottom of the page)
<button ng-class="{'btn-on' : tube.toggled, 'btn-off' : !tube.toggled}" ng-repeat="tube in node.Tubes" ng-click="toggleBtn(tube)">{{"Tube " + ($index + 1)}}</button>
source to share
These other answers are excellent. However, I would like to point to a different method. Let's say you are iterating over an array of receipts. For example, in the controller, you have receipts in the area:
$scope.receipts = [ ... ];
And at the front end, you punched these receipts:
<div ng-repeat="receipt in receipts">{{ receipt.[attribute] }}</div>
One way to keep track of unique classes is to add the class key to the receipt objects. For example, a receipt will look like this:
receipt { 'id': '1', 'class' : ' ... ' }
In the interface, you have to define the class using the ng class:
<div ng-repeat="receipt in receipts">
<div ng-class="receipt.class"></div>
</div>
And then you can pass the receipt and its ID to the toggleButton () method like this:
<div ng-repeat="receipt in receipts">
<div class="btn" ng-click="toggleClass(receipt.id)"></div>
<div ng-class="receipt.class"></div>
</div>
And then in the controller, you can simply update the class for that particular receipt (assuming there is a getReceipt () method here that gets the receipt from the $ scope.receipts array):
$scope.toggleClass = function(id) {
getReceipt(id).class = { ... }
}
This will dynamically change the class for that single receipt based on the logic in the toggleClass () function.
source to share