javascript 带有 ng-repeat、ng-show“显示更多”和延迟加载的 Angular 指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27437882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular directive with ng-repeat, ng-show "Show more" and lazy-load
提问by chrney_p
I use this directive, iterating over an array "myArr", filtering for a few conditions.
我使用这个指令,遍历数组“myArr”,过滤一些条件。
<myDirective
myData='item'
ng-repeat="item in filteredArr = (myArr | filter:searchField | filter:checkboxFilter)"
ng-show="$index < visible"
/>
This gives me two issues I'd like to get some input on:
这给了我两个我想获得一些意见的问题:
a) the ng-show part is there because I have a condition that handles this:
a) ng-show 部分在那里,因为我有一个处理这个的条件:
<p>
<a ng-click='visible=visible+10' ng-show='visible < filteredArr.length'>Show more</a>
</p>
in order to show or hide the "Show more" part. I cannot come up with another idea on toggling this and/or the items itself. $scope.visible is, inside the controller, set to 10, once we start. I couldn't use limitTo as it does not give me the possibility to determine if there's more to show or not, as it of course "chops" the array to the set limit.
为了显示或隐藏“显示更多”部分。我无法想出另一个关于切换这个和/或项目本身的想法。$scope.visible 在控制器内部设置为 10,一旦我们开始。我不能使用 limitTo,因为它不能让我确定是否有更多内容要显示,因为它当然会将数组“砍”到设定的限制。
b) Inside the directive, the template prints an
b) 在指令内部,模板打印一个
<img ng-src="...">
tag. How can I prevent these images to load as long as they're not shown in the above structure?
标签。只要这些图像未显示在上述结构中,我该如何阻止它们加载?
Thanks a lot in advance!
非常感谢!
回答by New Dev
Use ng-if
instead of ng-show
.
使用ng-if
代替ng-show
。
Unlike ng-show
, falsey ng-if
removes the element from the DOM.
与 不同ng-show
,falseyng-if
从 DOM 中删除元素。
EDIT:
编辑:
Also, you can, in fact, use limitTo
filter, which would make your code much cleaner:
此外,事实上,您可以使用limitTo
过滤器,这将使您的代码更清晰:
<div ng-init="limit = 2">
<foo ng-repeat="item in items | limitTo: limit as results"></foo>
</div>
<button ng-hide="results.length === items.length"
ng-click="limit = limit +2">show more...</button>