[英]Show and hide button in ng-repeat list
我的ng-repeat列表中的每個項目都有一個按鈕。 默認情況下隱藏按鈕,我想在用戶選擇列表項時顯示按鈕,並在用戶選擇另一個列表項時隱藏按鈕。 我無法使其工作,當用戶選擇列表項時,按鈕保持隱藏狀態。
以下是我到目前為止所嘗試的相關代碼。
HTML:
<ul ng-repeat="thing in things" role="presentation" id="thing-details" ng-click="selectthing($index)" >
<li>
<p>Name: {{thing.name}} </p>
<button class="btn btn-block" ng-show="false" id="thing-delete" >Delete</button>
</li>
</ul>
JS代碼:
$scope.selectthing = function(idx) {
$(this).find('ul.btn').show(); // this is not working
.
.
.
// do some awesome stuff with the selected thing.
}
我的問題是:如何在用戶選擇列表項時顯示按鈕,並在用戶另一個列表項時隱藏按鈕?
你幾乎得到了它:
<ul ng-repeat="thing in things">
<li>
<p ng-click="$parent.selectedIndex = $index">Name: {{thing.name}}</p>
<button class="btn btn-block"
ng-show="$parent.selectedIndex == $index">Delete</button>
</li>
</ul>
你正在混合Angular和jQuery,這是地獄的滑坡:)(好吧,警告:指令,但這是一個不同的故事)。 如果你發現自己要在你的控制器中編寫jQuery,那么警鍾應該響起你正在打破MVC分離並錯過更簡單的東西。
這里的訣竅是讓你的ng-show以當前正在呈現的項目是否是選定的項目為條件。 要檢測到這一點,請在所選索引的范圍內進行記錄。 像這樣......
HTML視圖:
<ul ng-repeat="thing in things" role="presentation" id="thing-details" ng-click="selectthing($index)" >
<li>
<p>Name: {{thing.name}} </p>
<button class="btn btn-block" ng-show="$index===selectedIndex" id="thing-delete" >Delete</button>
</li>
</ul>
JS控制器:
$scope.selectedIndex = -1;
$scope.selectthing = function(idx) {
$scope.selectedIndex = idx;
.
.
.
// do some awesome stuff with the selected thing.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.