問題描述
單擊時更改 ng‑class(嵌套 ng‑repeat) (Changing ng‑class when clicked (nested ng‑repeat))
這是我的角度代碼..(描述我遇到的問題是按鈕重複的嵌套 ng‑repeat 是對列出的所有“作業”的行為(單擊時)..
<div class="row" ng‑repeat="job in jobs">
<div class="btn‑group btn‑group‑justified" role="group">
<div class="btn‑group" role="group" ng‑repeat="status in job.statuscollection">
<button type="button" class="btn btn‑default" ng‑class="{ 'btn‑info': $index == selectedIndex }" ng‑click="itemClicked($index)">{{status.name}}</button>
</div>
</div>
</div>
這是我的 js 代碼..
$scope.jobs = [
{
_id: new Date().toISOString(),
statuscollection: [
{ name: "Off‑Site"},
{ name: "Enroute" },
{ name: "On‑Site" },
]
docType: "job",
},
{
_id: new Date().toISOString(),
statuscollection: [
{ name: "Off‑Site"},
{ name: "Enroute" },
{ name: "On‑Site" },
]
docType: "job",
}];
這是我的 ng‑click 功能..
$scope.itemClicked = function ($index) {
$scope.selectedIndex = $index;
console.log($scope.jobs[$index]);
}
我有不止一份工作,我在代碼中只包含了一份工作少了。但是當瀏覽器以正確的方式生成此數據時,單擊“作業”按鈕之一對每個作業執行相同的操作。
意思是,如果我單擊“打開”按鈕‑site" 對於一項工作,它對所有工作都是重複的。我怎樣才能做到這一點,以便僅單擊工作的一個按鈕只針對該工作而不是全部工作?
參考解法
方法 1:
Use $parent.$index
instead of $index
to refer to the outer ng‑repeated loop (the job loop, that is):
<button type="button" class="btn btn‑default" ng‑class="{ 'btn‑info': $parent.index == selectedIndex }" ng‑click="itemClicked($parent.$index)">{{status.name}}</button>
$index
is the index of the inner loop.
$parent.$index
is the index of the outer loop.
方法 2:
The proper Angular approach to track indices across multiple ngRepeats
is to use ngInit
to create a local variable that aliases $index
for each instance of ngRepeat
. Using $parent
to acquire its $index
position is generally discouraged.
And in the example below, we have two ngRepeats
and therefore two aliased index variables: outerIndex
and innerIndex
:
<tbody ng‑repeat="country in countries" ng‑init="outerIndex = $index">
<tr ng‑repeat="city in country.cities" ng‑init="innerIndex = $index">
<td>{{city}}</td>
<td>{{country.name}}</td>
<td>({{outerIndex}}, {{innerIndex}})</td>
</tr>
</tbody>
Plunker: http://plnkr.co/edit/VA1XWWrG3pghEcWli06F
Final Edit
After understanding more of the context behind the question, it actually makes more sense for the OP to set an isActive
property on the selected object instead attempting to track and match indices. That said the approach noted above is still valid and applicable for tracking indices across multiple ngRepeats
$scope.itemClicked = function (status, job) {
if (status.isActive) {
status.isActive = false;
} else {
angular.forEach(job.statuscollection, function(status) {
status.isActive = false;
});
status.isActive = true;
}
}
Updated plunker: http://plnkr.co/edit/v70fY30PjoTXCrhOPVZB
(by LatentDenis、Tarun Dugar、lux)