AngularJs - лучшие практики по добавлению активного класса при нажатии (ng-repeat)
Я хочу добавить активный класс в клик в списке, я попробовал следующий код, но он добавляет активный класс ко всем моим элементам:/:
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;
};
}
Пожалуйста, помогите мне.
Спасибо
Ответы
Ответ 1
Лучшим решением было бы нацелить его на углы $index
, которые являются объектом index/position в массиве;
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/контроллер
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
Ответ 2
Медленно, чтобы ответить, вот что я получил (может добавить немного больше)
РАБОЧИЙ ДЕМО: http://jsfiddle.net/WVY7L/
TEMPLATE
<ul>
<li ng-repeat="filter in filters"
ng-click="select($index)" ng-class="{active: $index===selectedIndex}">
<span class="filters_ct_status"></span>
{{filter.time}}
</li>
</ul>
CONTROLLER
$scope.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.selectedIndex = 0; /* first one set active by default */
$scope.select= function(i) {
$scope.selectedIndex=i;
};
-
стоит упомянуть, что в данных у вас есть запятая, которая не должна быть там.
{ filterId: 1, time: 'last 24 hours'**,**}
Остальное было обеспечение того, что ваш контроллер был передан номер массива
ng-click="select($index)" ng-class="{active: $index===selectedIndex}"
и возможность сохранить этот номер массива selectedIndex
для использования в вашем шаблоне
$scope.selectedIndex
синтаксис ng-класса
{active: $index===selectedIndex}
Переводит для добавления класса с именем "active", когда "$ index" равен "selectedIndex"
Ответ 3
Я очень опаздываю на вечеринку, но это самый многоразовый шаблон, и он спасет вас от повторной записи одной и той же функции каждый раз.
HTML:
<ul>
<li ng-repeat="item in list" ng-click="setActive(item, list)" ng-class="{active: item.active}"></li>
</ul>
JS:
$scope.list = [{}, {}];
$scope.setActive = function(item, list){
list.some(function(item){
if(item.active){
return item.active = false;
}
});
item.active = true;
};
Ответ 4
Проверить идентификатор выбранного элемента:
<div class="filters_ct" ng-controller="selectFilter">
<ul>
<li ng-repeat="item in filters" ng-click="select(item)" ng-class="{sel: item.filterId == selected.filterId}">
<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.filters = filters;
$scope.selected = $scope.items[0];
$scope.select= function(item) {
$scope.selected = item;
};
}