Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  51] [ 2]  / answers: 1 / hits: 79279  / 11 Years ago, fri, january 3, 2014, 12:00:00

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


More From » html

 Answers
33

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;
};
});


JSFIDDLE


[#73400] Thursday, January 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kareem

Total Points: 733
Total Questions: 110
Total Answers: 102

Location: Bermuda
Member since Thu, Apr 20, 2023
1 Year ago
;