使用Angular在列表中切换类 [英] Toggle classes in a list with Angular

查看:182
本文介绍了使用Angular在列表中切换类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用AngularJS单击元素时,我想切换一个类.我需要clicked元素来接收该类,并且需要列表中的其他任何项来松散该类.我已经在SO上研究了许多假定的解决方案,但是在实施它们时,它们无法正常工作,我也不知道为什么会这样做.

I'd like to toggle a class when an element is clicked using AngularJS. I need the clicked element to received the class, and any other items in the list to loose the class. I've researched a number of supposed solutions for this on SO, however in implementing them, they don't work appropriately and I don't understand why they would even.

建议的一般解决方案是将一个变量设置为 ng-repeat 列表中项目的索引.然后使用 ng-class 添加类.JSFiddle 此处.

The general solution proposed is to set a variable to the index of the item in the ng-repeat list. Then use ng-class to add the class. JSFiddle here.

<div ng-app>
<p ng-repeat="item in ['a', 'b', 'c']"
    ng-click="selectedIndex = $index"
    ng-class="{selected: $index === selectedIndex}"    
>{{item}}</p>
</div>

问题在于,'selected'类永远不会从之前的元素中删除.因此,单击元素会按预期将类添加到该元素,但是单击另一个元素并不会从先前单击的元素中删除该类.我猜想是因为Angular在每次单击时 not 都不会重新渲染整个列表,因此旧的被单击元素不会更改.但这引出了我的问题,为什么这是一个如此压倒性的解决方案?我只是在执行错误的事情吗?谢谢.

The problem is that the 'selected' class is never removed from the previous elements. So, clicking an element adds the class to the element as expected, but clicking another element doesn't remove the class from previously clicked elements. I would guess because Angular is not re-rendering the entire list on each click and thus the old clicked elements don't change. That begs my question though, why is this such an overwhelmingly proposed solution? Am I just implementing something wrong? Thanks.

推荐答案

这是因为 ng-repeat 创建了自己的子范围,因此您的其他每个元素都有自己的 selectedIndex -创建一个函数,以便所有重复的元素都可以看到 selectedIndex :

That's because ng-repeat creates its own child scope, so your other elements each have their own instance of selectedIndex - create a function so selectedIndex is seen by all repeated elements:

控制器:

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

<div ng-app>
    <p ng-repeat="item in ['a', 'b', 'c']"
        ng-click="setSelected($index)"
        ng-class="{selected: $index === selectedIndex}"    
    >{{item}}</p>
</div>

这篇关于使用Angular在列表中切换类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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