[英]angular hide when filtered array is empty
I have multiple ng-repeat
s which use a custom filter and I would like to hide the list. 我有多个使用自定义过滤器的
ng-repeat
,我想隐藏列表。 Each list has its own someScopeValue
value which is used to determine if a repeated item should be included (or filtered out). 每个列表都有其自己的
someScopeValue
值,该值用于确定是否应包含(或滤除)重复项。
My first attempt doesn't work and it's clear why not (items is only filtered in the ng-repeat
and ng-show
doesn't know about this: 我的第一次尝试不起作用,并且很清楚为什么不这样做(仅在
ng-repeat
过滤了项目,而ng-show
对此一无所知:
<!-- this is clearly not smart logic -->
<ul ng-show="items.length">
<li ng-repeat="item in items | customFilter:someScopeValue">text</li>
</ul>
...
<ul ng-show="items.length">
<li ng-repeat="item in items | customFilter:someScopeValue">text</li>
</ul>
Is there a way to also apply the filter to the ng-show
? 有没有办法将滤镜也应用于
ng-show
? Here are some ideas I have but curious if there's a best practice or smarter way to do this: 这是我的一些想法,但奇怪的是,是否有最佳实践或更聪明的方法可以做到这一点:
<!-- this would filter the list somewhere in each <ul> scope -->
<ul ng-show="filteredList.length">
<li ng-repeat="item in filteredList">text</li>
</ul>
Or, maybe I can use ng-init
in some smarter way? 或者,也许我可以以更聪明的方式使用
ng-init
?
<!-- this filters the list on-the-fly for each <ul> using some scope function -->
<ul ng-init="filteredList = filter(items, someScopeValue)" ng-show="filteredList.length">
<li ng-repeat="item in filteredList">text</li>
</ul>
You can created a new variable on your scope that will be the filtered array like this: 您可以在作用域上创建一个新变量,该变量将是过滤后的数组,如下所示:
<ul ng-show="filteredItems.length">
<li ng-repeat="item in items | filter:someScopeValue as filteredItems">{{item.value}}</li>
<li>Extra</li>
</ul>
When doing something like this you will have a $scope.filteredItems
created. 当做这样的事情时,您将创建一个
$scope.filteredItems
。
If you are not changing the data after you sort the data you could manipulate the array first inside the controller. 如果对数据排序后没有更改数据,则可以先在控制器内部操作数组。 Then just use your first suggestion of ng-show="filteredList.length".
然后,使用您的第一个建议ng-show =“ filteredList.length”。
Here's the route I went with your question. 这是我回答你的问题的路线。 I set a watch on a list in scope that was being modified by the filter, and based the show on another variable that was holding the length.
我在由过滤器修改的范围内的列表上设置了一个手表,并将显示基于另一个保存长度的变量。 Here's an example fiddle .
这是一个小提琴的例子。
$scope.counter = $scope.items.length;
$scope.$watch("items.length", function(newValue, oldValue) {
$scope.counter = newValue;
});
Yes, you can use ng-init
or introduce a variable in the template . 是的,您可以使用
ng-init
或在template中引入一个变量 。 But I would recommend to filter your data inside the controller and expose the filtered array to the template. 但是我建议您在控制器内部过滤数据,并将过滤后的数组暴露给模板。 Especially if you have to hide the parrent
<ul>
element. 特别是如果您必须隐藏parrent
<ul>
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.