有选择地向ng-repeat AngularJS添加一个类

use*_*246 6 angularjs ng-class angularjs-ng-class

我有一个表的ng-repeat,我希望能够在<td>单击时添加一个类,并在单击时删除该类.<td>可以同时选择多个.现在所有的城市都适用或不适用.

例如:(假设节点有100个项目)

<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>
Run Code Online (Sandbox Code Playgroud)

在我的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;
};
Run Code Online (Sandbox Code Playgroud)

Ant*_*Chu 4

clicked现在,您正在更改的范围内只有一个属性,并且所有内容都引用该属性。尝试放在clicked节点上......

$scope.toggleMe = function(node) {
  if ($scope.count > 0) {
    angular.forEach($scope.cityArr, function(value) {
      if (node.city === value) {
        node.clicked = false;
      } else {
        $scope.cityArr.push(node.city);
        node.clicked = true;
      }
    });
  } else {
    $scope.cityArr.push(node.city);
    node.clicked = true;
  }
  $scope.count = 1;
};
Run Code Online (Sandbox Code Playgroud)

而在ngRepeat...

<tr ng-repeat node in nodes>
  <td>{{node.name}}</td>
  <td>{{node.date}}</td>
  <td ng-click="toggleMe( node )" ng-class"{clicked : node.clicked}" >{{node.city}}</td>
</tr>
Run Code Online (Sandbox Code Playgroud)