【问题标题】:AngularJS: apply class to multiple elements in array on clickAngularJS:单击时将类应用于数组中的多个元素
【发布时间】:2015-10-12 16:17:45
【问题描述】:

我正在自学 Angular 并通过 O'Reilly AngularJS 书工作。有一个电子邮件应用示例,我想添加一个“标记为已读”按钮,当单击该按钮时,该按钮会将一个类应用于该行。

在做了一些研究后,我找到了应用条件类的解决方案,该解决方案基于使用 $index 来选择一行,但这是在我单击按钮时从其他元素切换类。你可以在这里看到我在说什么in this Plunker

这是我认为的 HTML:

    <table>
  <tr>
    <td><strong>Sender</strong></td>
    <td><strong>Subject</strong></td>
    <td><strong>Date</strong></td>
  </tr>
  <tr ng-repeat='message in messages' ng-click='readMessage($index)'
          ng-class='{markRead: $index==selectedRow}'>
    <td>{{message.sender}}</td>
    <td><a ng-href='#/view/{{message.id}}'>{{message.subject}}</a></td>
    <td>{{message.date}}</td>
    <td><button  ng-click="remove(message)">Delete</button></td>
    <td><button  ng-click="markRead()">Mark as Read</button></td>
  </tr>
</table>

这是我添加到控制器中以在单击时应用类的内容:

  $scope.readMessage = function(row) {
    $scope.selectedRow = row;
  };

我的目标是能够根据用户的需要(而不是一次一个)将类应用于数组中的任何和所有元素。

有人可以帮我理解为什么这不起作用以及如何实现我的目标吗?我可以在 SO 上找到的所有问题/答案都是关于切换课程或设置活动课程,这与我想要完成的相反。

谢谢!

【问题讨论】:

    标签: angularjs ng-class


    【解决方案1】:

    函数readMessage可以将消息标记为read,如果设置了标记,ng-class会设置css类:

    控制器:

    $scope.readMessage = function(message) {
        message.read = true;
    };
    

    模板:

    ng-class='{markRead: message.read}'
    

    plunker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2021-12-08
      • 2014-06-28
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多