[英]Show and hide spans inside parent div on click not working as expected
我的標記看起來像:
<div class="box" ng-click="listThis()" ng-show="isVisible">
<span class="text">content ....</span>
<span class="text2">content2 ....</span>
<span class="text3">content3 ....</span>
我的代碼如下:
var spans = 2;
var i = 0;
$scope.newlist= [];
while (i < spans){
$scope.newlist.push(i+1);
i++;
}
$scope.listThis=function(){
$scope.isVisible=!$scope.isVisible;
}
但是,當我單擊/關閉class =“ box”內的所有內容時,它們將被隱藏,並且不會真正限制我的span值,例如,僅顯示2個span。
現在確定我是否錯過了任何東西,或者有更好的方法呢?
這是因為您的ng-show位於包含跨度的div上。 因此,如果isVisible
為false,則將隱藏整個div及其所有內容。 要更改此設置,您應該為每個跨度創建條件,這些條件將相應地顯示/隱藏。 例如:
<div class="box">
<span class="text" ng-click="listContentOne()" ng-show="oneIsVisible"></span>
在您的控制器中:
$scope.listContentOne = function() {
$scope.oneIsVisible = !$scope.oneIsVisible;
}
這是您想要實現的非常簡單和基本的版本,但是有了這些信息,您應該能夠得出自己的解決方案。
第一個答案是有關ng-show問題的一個很好的答案。
根據您的評論,您可能希望將ng-repeat與過濾器一起使用。
首先,這是一個工作的小伙子
HTML:ng-repeat- limit
是$ scope變量。 “ limitTo”過濾器返回列表的前n個元素。
<div>
<span ng-repeat="span in spans | limitTo: limit">{{span.content}}<br/></span>
</div>
JS:
//Now your span elements are objects with the attribute "content"
$scope.spans = [{content:"Test1"},{content:"Test2"},{content:"Test3"}]
您可以使用ng-model="limit"
將輸入綁定為limit
。 或者只是在JS中執行$scope.limit = 2
希望能有所幫助。
ng-repeat
可能更多是您想要的。 假設您具有跨度設置的動態內容,如下所示:
$scope.spans = [
{content: 'content1'},
{content: 'content2'},
{content: 'content3'}
]
然后您的html應該是這樣的:
<span ng-repeat="span in spans">{{span.content}}</span>
從那里開始,您可以根據自己的選擇進行選擇。 如果您的跨度已排序並且只想顯示一定數量,請在某處添加$scope.limit
並使用limitTo :
<span ng-repeat="span in spans | limitTo: limit">{{span.content}}</span>
否則,將另一個變量放在跨度對象上,稱為visible
,將其設置為true或false,然后執行
<span ng-repeat="span in spans" ng-show="span.visible">{{span.content}}</span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.