简体   繁体   中英

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. If the checkbox is false, only show the documents where 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:

Controller: (or if you want have the logic straight in the HTML)

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

And 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. When checkbox is not selected the model filterRead.read is set to something which is not equal to both read true or false. So as the result all records are rendered.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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