MDN
拥有默认选择也需要初始化。
根据你的小提琴,这里是html
<div ng-app ng-controller="ContinentController">
<ul>
<li ng-repeat="continent in continents">
<h2>{{continent.name}}</h2>
<ul>
<li ng-repeat="country in continent.countries">
<span ng-class="{active: selected[continent.name] === $index}"
ng-click="select(continent.name, $index)">{{country}}</span>
</li>
</ul>
</li>
</ul>
</div>
function ContinentController($scope) {
$scope.continents = [{
name: 'europe',
countries: ["Englad", "France", "Germany", "Italy"]
}, {
name: 'asia',
countries: ["Japan", "China", "Iran", "Korea"]
}, {
name: 'Africa',
countries: ["Somalia", "Egypt", "Ghana"]
}, ];
$scope.selected = {};
$scope.select = select;
initializeSelection();
function initializeSelection() {
for (var i = 0; i < $scope.continents.length; i++) {
$scope.selected[$scope.continents[i].name] = 0;
}
}
function select(name, index) {
$scope.selected[name] = index;
}
}
这是工作
fiddle
现在假设所有的名字都是唯一的。既然你提到你有ID,如果它们是唯一的,那么使用它们作为键而不是名称属性肯定会更好。