2014-10-17 95 views
-1

我有我自己的無序列表:獨家選擇列表中的元素

<ul> 
    <li ng-class="{ 'active': selected }" ng-click="selected = !selcted">Stuff 1</li> 
    <li ng-class="{ 'active': selected }" ng-click="selected = !selcted">Stuff 2</li> 
    <li ng-class="{ 'active': selected }" ng-click="selected = !selcted">Stuff 3</li> 
</ul> 

我想要一類適用於用戶選擇列表項。一次只有一個項目可以擁有該課程。什麼是最好的方法來解決這個問題?大約有十幾個元素,所以我寧願不爲每個項目聲明一個新的變量。

+0

我會愛如果人們會解釋他們downvotes :) – 2014-10-17 14:52:38

回答

2

設置每個項目的屬性:

<ul> 
    <li ng-class="{ 'active': selected == 1 }" ng-click="selected = 1">Stuff 1</li> 
    <li ng-class="{ 'active': selected == 2 }" ng-click="selected = 2">Stuff 2</li> 
    <li ng-class="{ 'active': selected == 3 }" ng-click="selected = 3">Stuff 3</li> 
</ul> 
+0

完美。謝謝! – 2014-10-17 14:53:08

2

如果你想角上下的使用NG-repat

HTML

<ul ng-repeat="s in stuffs"> 
    <li ng-class="{active:$index==selected}" ng-click="selected=$index">{{s}}</li> 
</ul> 

JS

$scope.stuffs = ['Stuff 1', 'Stuff 2', 'Stuff 3'];