gpt4 book ai didi

javascript - AngularJs - 在点击时添加事件类的最佳实践(ng-repeat)

转载 作者:IT王子 更新时间:2023-10-29 03:11:01 27 4
gpt4 key购买 nike

我想在列表中单击时添加一个事件类,我尝试了以下代码,但它在我的所有项目上添加了事件类:/:

HTML :

<div class="filters_ct" ng-controller="selectFilter">
<ul>
<li ng-repeat="filters in filter" ng-click="select(item)" ng-class="{sel: item == selected}">
<span class="filters_ct_status"></span>
{{filters.time}}
</li>
</ul>
</div>

Js:

  var filters = [
{
'filterId': 1,
'time': 'last 24 hours',
},
{
'filterId': 2,
'time': 'all',
},
{
'filterId': 3,
'time': 'last hour',
},
{
'filterId': 4,
'time': 'today',
},
{
'filterId': 5,
'time': 'yersteday',
}
];


function selectFilter($scope) {

$scope.items = ['filters'];
$scope.selected = $scope.items[0];

$scope.select= function(item) {
$scope.selected = item;
};

}

请给我一些帮助

谢谢

最佳答案

最好的解决方案是通过 Angular $index 定位它,这是数组中的对象索引/位置;

HTML

<div ng-app='app' class="filters_ct" ng-controller="selectFilter">
<ul>
<li ng-repeat="filter in filters" ng-click="select($index)" ng-class="{sel: $index == selected}">
<span class="filters_ct_status"></span>
{{filter.time}}
</li>
</ul>
</div>

JS/ Controller

var app = angular.module('app', []); 

app.controller('selectFilter', function($scope) {
var filters = [
{
'filterId': 1,
'time': 'last 24 hours',
},
{
'filterId': 2,
'time': 'all',
},
{
'filterId': 3,
'time': 'last hour',
},
{
'filterId': 4,
'time': 'today',
},
{
'filterId': 5,
'time': 'yersteday',
}
];

$scope.filters = filters;
$scope.selected = 0;

$scope.select= function(index) {
$scope.selected = index;
};
});

JSFIDDLE

关于javascript - AngularJs - 在点击时添加事件类的最佳实践(ng-repeat),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20902583/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com