简体   繁体   English

AngularJS ng-repeat和切换过滤器开/关?

[英]AngularJS ng-repeat and toggle filter on/off?

I do not know how to write this filter expression. 我不知道如何编写此过滤器表达式。

I have an array of documents: 我有一系列文件:

[{title: 'doc1', read: false}
{title: 'doc2', read: false}
{title: 'doc3', read: false}
{title: 'doc4', read: true}
{title: 'doc5', read: false}]

On the view I have 我认为

<input type="checkbox" ng-model="filterRead">
<div ng-repeat="doc in documents track by $index | filter: ??? ">
   {{doc.title}}
</div>

If the checkbox/filterRead is true, assign no filter and show all the documents. 如果checkbox / filterRead为true,则不分配任何过滤器并显示所有文档。 If the checkbox is false, only show the documents where doc.read=false. 如果复选框为false,则仅在doc.read = false的地方显示文档。 I do not know how to write this filter expression elegantly. 我不知道如何优雅地编写此过滤器表达式。

According to your logic, you don't need a filter, you could use an ng-if: 根据您的逻辑,您不需要过滤器,可以使用ng-if:

Controller: (or if you want have the logic straight in the HTML) 控制器:(或者如果您想直接在HTML中使用逻辑)

$scope.showDoc = function () {
    return $scope.filterRead || !doc.read;
}

And HTML: 和HTML:

<div ng-repeat="doc in documents track by $index" ng-if="showDoc()">
   {{doc.title}}
</div>

It is possible to do it in template only. 只能在模板中执行此操作。 Here is an example: 这是一个例子:

<input type="checkbox" ng-model="filterRead.read" ng-true-value="false" ng-false-value="'!null'">
<div ng-repeat="doc in documents | filter:filterRead track by $index ">
    {{doc.title}}
</div>

ngFalseValue directive does the trick here. ngFalseValue指令在这里ngFalseValue了作用。 When checkbox is not selected the model filterRead.read is set to something which is not equal to both read true or false. 当复选框未选择模型filterRead.read设置为一些东西,不等于这两个read真或假。 So as the result all records are rendered. 因此,所有记录均被呈现。

Demo: http://plnkr.co/edit/GO9vAZI3ghZuFb2eqa6h?p=preview 演示: http //plnkr.co/edit/GO9vAZI3ghZuFb2eqa6h?p = preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM