如何使用 ng-click 在 ng-repeat 项目中切换活动状态 ng-class? [英] How do you toggle an active state ng-class in an ng-repeat item using ng-click?
问题描述
<ul>
<li data-ng-repeat="image in images" data-ng-click="toggle = !toggle" data-ng-init="toggle=false">
<img data-ng-class="{'active' : toggle}" src="" />
</li>
</ul>
'active' 类的 CSS 来自引导程序.
所以切换工作,这几乎是我想要的地方;我希望它类似于导航链接中的活动状态,除了在我的示例中它处理图像,因此需要担心 url 字符串等.
CSS for 'active' class is from bootstrap.
So toggling works, which is almost where I want it; I would like it similar to active states in navigation links, except in my example it's dealing with images so need to worry about url strings, etc.
我尝试模拟这里发现的这个例子无济于事(我尝试了相同的图像逻辑):ng-class 基于 ng-repeat 突出显示活动菜单项.AngularJS
I tried emulating this example found here to no avail (I tried the same logic for images): ng-class to highlight active menu item based on ng-repeat. AngularJS
如果有人能指出我正确的方向,我将不胜感激.:D
If someone could point me in the right direction, I would greatly appreciate it. :D
推荐答案
在你的情况下我会做的是在该 ng-repeat 的父作用域内定义一个对象,并将索引或任何你希望的属性分配给那个对象.那是因为对象在 javascript 中通过引用工作,这意味着 ng-click 将实际更新父作用域属性而不是重新定义它.plnkr 的示例:http://plnkr.co/edit/oA12yLIb3RnlSYe6JxhI?p=preview
What i would do in your situation is define an object inside the parent scope of that ng-repeat, and assign the index or whatever you wish to a propperty of that object. That is because objects work by reference in javascript, which means that the ng-click will actually update the parent scope attribute instead of redefine it. Example at plnkr: http://plnkr.co/edit/oA12yLIb3RnlSYe6JxhI?p=preview
<!DOCTYPE html>
<html ng-app>
<head>
<style>
.active{
background-color: red;
height: 500px;
width: 500px;
}
</style>
</head>
<body ng-controller="HolaCtrl">
<ul>
<li data-ng-repeat="image in images" data-ng-click="toggleObject.item = $index">a
<img data-ng-class="{'active' : toggleObject.item == $index}" src="" /><br>
</li>
</ul>
<script>
function HolaCtrl($scope){
$scope.images = [1,2,3];
$scope.toggleObject = {item: -1};
}
</script>
</body>
</html>
干杯
这篇关于如何使用 ng-click 在 ng-repeat 项目中切换活动状态 ng-class?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!