Search code examples
angularjsangularjs-ng-repeatangularjs-ng-click

Change class of just one element in an ngRepeat


I have an ng-repeat. And I would like to change the class of just that element vs the entire group.

<button ng-class="defaultClass" ng-repeat="tube in node.Tubes" ng-click="toggleBtn(tube)">{{"Tube " + ($index + 1)}}</button>

with the above HTML on my ng-click I can pass the tube, which really only gives me the data passed from the API, if I console.log(this) I see the class name in an element called $$watchers but that seems odd 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 that with the function it changes every element.

How can I only change the class of the element clicked?


Solution

  • Continuing from the comments. Than you can't use $scope variable for that, because, as you said, it will be the same. TO solve this you need to use ng-class properly. Docs: https://docs.angularjs.org/api/ng/directive/ngClass (see an 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>
    

    http://plnkr.co/edit/WKLJ45yRYu1583C2ZnfT?p=preview