Angular.js如何在单击时更改元素CSS类并删除所有其他元素 [英] Angular.js How to change an elements css class on click and to remove all others

查看:143
本文介绍了Angular.js如何在单击时更改元素CSS类并删除所有其他元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试切换两个元素,因此如果单击一个元素,它将删除my-class的所有引用并将其应用于自身.有什么想法吗?

i'm trying to make my two elements toggle, so if one element is clicked it will remove all references of my-class and apply it to its self. Any ideas?

<span id="1" ng-style="my-class" ng-click="tog=my-class"></span>

<span id="2" ng-style="my-class" ng-click="tog=my-class"></span>

干杯!

推荐答案

创建一个名为selectedIndex的范围属性和一个itemClicked函数:

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

然后我的模板如下所示:

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

仅供参考,$ index是ng-repeat指令中可用的不可思议的变量.

Just for reference $index is a magic variable available within ng-repeat directives.

您也可以在指令和模板中使用相同的示例.

You can use this same sample within a directive and template as well.

这是工作中的plnkr:

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

这篇关于Angular.js如何在单击时更改元素CSS类并删除所有其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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