AngularJs - 单击时添加活动类的最佳实践(ng-repeat) [英] AngularJs - Best-Practices on adding an active class on click (ng-repeat)
本文介绍了AngularJs - 单击时添加活动类的最佳实践(ng-repeat)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在列表中单击时添加一个活动类,我尝试了以下代码,但它在我的所有项目上添加了活动类:/:
HTML:
<ul><li ng-repeat="过滤器中的过滤器" ng-click="select(item)" ng-class="{sel: item == selected}"><span class="filters_ct_status"></span>{{filters.time}}
JS:
var 过滤器 = [{'过滤器ID':1,'time': '过去 24 小时',},{'过滤器ID':2,'时间':'所有',},{'过滤器ID':3,'time': '最后一小时',},{'过滤器ID':4,'时间': '今天',},{'过滤器ID':5,'time': '昨天',}];功能选择过滤器($范围){$scope.items = ['过滤器'];$scope.selected = $scope.items[0];$scope.select= function(item) {$scope.selected = 项目;};}
请给我一些帮助.
谢谢
解决方案
最好的解决方案是通过 angulars $index
这是对象在数组中的索引/位置;
HTML
<ul><li ng-repeat="filter in filters" ng-click="select($index)" ng-class="{sel: $index == selected}"><span class="filters_ct_status"></span>{{filter.time}}
JS/控制器
var app = angular.module('app', []);app.controller('selectFilter', function($scope) {无功过滤器 = [{'过滤器ID':1,'time': '过去 24 小时',},{'过滤器ID':2,'时间':'所有',},{'过滤器ID':3,'time': '最后一小时',},{'过滤器ID':4,'时间': '今天',},{'过滤器ID':5,'time': '昨天',}];$scope.filters = 过滤器;$scope.selected = 0;$scope.select= 函数(索引){$scope.selected = 索引;};});
I want to add an active class on click in a list, i tried the following code, but it adds the active class on all my items :/ :
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;
};
}
Please, give me some help.
Thanks
解决方案
The best solution would be to target it via angulars $index
which is the objects index/position in the array;
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;
};
});
这篇关于AngularJs - 单击时添加活动类的最佳实践(ng-repeat)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文