1. 程式人生 > >ng-repeat設定第一個元素為預設樣式,點選其餘元素切換樣式

ng-repeat設定第一個元素為預設樣式,點選其餘元素切換樣式

如何在ng-repeat時預設第一個元素background-color為紅色,點選對應元素背景變紅同時更換其他全為黑色

提供一個簡單思路:
JS:


$scope.isActive = 0;
$scope.arr = [
    {
        //code here
    },
    {
        //code here
    }
];
$scope.selectItem = function (index) {
    item.isActive = index;
}

HTML:

<ul>
    <li ng-repeat="item in arr track by $index"
ng-class="
{red:isActive === $index, black:!isActive === $index}" ng-click="selectItem($index)"></li> </ul>

CSS:

.red {
    background: red;
}
.black {
    background: black;
}

修改你的程式碼就是這樣:

HTML:



<div class="p10 c-white w50p fl mr1 tc" ng-repeat="e in item.images">
    <div
class="w50p h50 img_div" ng-class="
{b-red:isActive === $index,b-white:!isActive === $index}" ng-click="changeGood($index)"> <img src="{{e.path}}"> </div> <span class="ib w50p fs0-6 span-over">{{e.description}}</span> </div>

controller:


$scope.isActive=0
; $scope.changeGood=function(index){ $scope.isActive=index; }