AngularJS在ng重复中选择单个表单元格

AngularJS select a single table cell in ng-repeat

本文关键字:选择 单个表 单元格 ng AngularJS      更新时间:2023-09-26

我希望能够在ng-repeat中单击一个表单元格来选择它(或者用CSS切换"打开/关闭"),但我遇到了麻烦,需要一些帮助。

HTML

<tr ng-repeat="row in game.rows">
    <td ng-repeat="word in row.words">{{word}}</td>
</tr>

td的种子是由API为游戏添加文字。

控制器

'use strict';
angular.module('MyApp')
    .controller('CardCtrl', function($scope, $http) {
        $scope.game = {};
       $http.get('/api/games/new').success(function(game) {
           $scope.game = game;
        });
    });

我想做的是能够像jQuery中的toggleClass一样单击td,能够在单个td上切换CSS类。有什么想法吗?

您可以通过以下方式轻松切换带有ng class指令的类:

<td ng-repeat="word in row.words" ng-class={yourClassName:toggle} ng-click="toggle = !toggle">{{word}}</td>

它会在每次点击时切换你的类名。将为每个td自动生成"toggle"属性(由于angular使用ng repeat创建的范围)。因此,它不会影响其他td.

您的问题还不清楚,您可以使用ng-click="toggle($event)"$event用于获取事件被触发的位置。并在控制器中使用以下功能。

$scope.toggle = function(event){
 $(event.currentTarget).toggleClass("myClass");
}

可以实现。