简体   繁体   中英

AngularJS ng-click change color within ng-repeat

I have some code that lists out items in a table from a database. The click function toggles the cells between green and red

 <div class="row">
    <div class="logs-table col-xs-12">
        <table class="table table-bordered table-hover" style="width:100%">

            <tr>              
                <th>Name</th>
                <th>Seed</th>
                <th>Division</th>                
            </tr>

            <tr ng-repeat="team in Pool">
                <td ng-class="{'btn-danger': started, 'btn-success': !started}" ng-click="inc()">{{ team.chrTeamName }}</td>
                <td>{{ team.intSeed }}</td>
                <td>{{ team.chrDivision }}</td>
            </tr> 

        </table>
    </div>
</div>

My click function is below

 $scope.inc = function () { $scope.started = !$scope.started }

The only problem is that this is changing all of the cells in the first column. I'm thinking i need to pass a parameter in my click function, but I'm not sure what.

If you don't use the started value in your controller, you don't really need to define a function.

You could use ng-init to initialize an array keeping track of the started value for each team.

Something like this:

        <tr ng-repeat="team in Pool" ng-init="started = []">
            <td ng-class="{'btn-danger': started[$index], 'btn-success': !started[$index]}" ng-click="started[$index] = !started[$index]">{{ team.chrTeamName }}</td>
            <td>{{ team.intSeed }}</td>
            <td>{{ team.chrDivision }}</td>
        </tr> 

Somehow cleaner would be if there was a started property on every team instance:

        <tr ng-repeat="team in Pool">
            <td ng-class="{'btn-danger': team.started, 'btn-success': !team.started}" ng-click="team.started = !team.started">{{ team.chrTeamName }}</td>
            <td>{{ team.intSeed }}</td>
            <td>{{ team.chrDivision }}</td>
        </tr> 

Yes, passing a parameter into your function will help. Currently you have a $scope level variable ( $scope.started ) which selects your css ng-class. You probably want a team-by-team property. To do this, you should refer to the actual team object from within your ng-repeat.

<tr ng-repeat="team in Pool">
    <td ng-class="{'btn-danger': started, 'btn-success': !team.started}" ng-click="inc(team)">{{ team.chrTeamName }}</td>
    <td>{{ team.intSeed }}</td>
    <td>{{ team.chrDivision }}</td>
</tr> 

And in your javascript:

$scope.inc = function (team) { team.started = !team.started; }

Now that your are using the actual individual object ( team ) from your ng-repeat, everything should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM