有选择地向 ng-repeat AngularJS 添加一个类 [英] Add a class selectively to an ng-repeat AngularJS

查看:18
本文介绍了有选择地向 ng-repeat AngularJS 添加一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表的 ng-repeat,我希望能够在单击 时添加一个类,并在未单击时删除该类.可以同时选择多个.目前,所有城市都在申请或未申请该课程.

I have an ng-repeat for a table, I want to be able to add a class when <td> is clicked, and remove the class when un-clicked. Multiple <td> can be selected at the same time. Right now ALL of the cities are or are not getting the class applies.

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

For example: (lets say nodes has 100 items)

<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>

在我的 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;
};

推荐答案

现在,您要更改的范围上只有一个 clicked 属性,并且所有内容都指向该属性.尝试将 clicked 放在节点上...

Right now there is a single clicked property on the scope that you're changing and everything refers to that. Try to put clicked on the node instead...

$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;
};

并且在 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>

这篇关于有选择地向 ng-repeat AngularJS 添加一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆