2016-12-28 139 views
3

在ng-repeat內部的HTML元素上應用CSS類我試圖根據active變量使HTML標題處於活動狀態或非活動狀態。但設置active標誌上點擊標題,我使用ng-repeat指令的$index變量:基於條件

<div ng-init="active = 1"> 
    <h4 ng-repeat="(key, val) in vm.headings" ng-click="active = $index" ng-class="{'active': active === $index}"> 
{{key}} 
</h4> 
</div> 

主導對象:

vm.headings = { 
    "HEADING_1": "CONTENT", 
    "HEADING_2": "CONTENT", 
    "HEADING_3": "CONTENT" 
}; 

第一次加載時,標題中的一個出現「active`如同設置。但在隨後的點擊中,它沒有提供期望的結果。所有標題在點擊它們時變得活躍。 Here is the fiddle.

回答

4

試試這個:

<h4 ng-repeat="(key, val) in vm.headings" ng-click="selectH($index)" ng-class="{'active': active === $index}"> 

在控制器:

$scope.selectH= function(index) { 
    $scope.active = index; 
}; 

希望這會工作。

+0

有關該問題的更多詳細信息,請訪問:http://stackoverflow.com/questions/17925355/how-can-i-use-the-index-inside-a-ng-repeat-to-enable-a-class-和秀-A-DIV – Dese