【问题标题】:AngularJS ng-repeat and toggle filter on/off?AngularJS ng-repeat和切换过滤器开/关?
【发布时间】:2015-05-13 04:51:27
【问题描述】:

我不知道这个过滤器表达式怎么写。

我有一个文档数组:

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

我的观点

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

如果 checkbox/filterRead 为 true,则不分配过滤器并显示所有文档。如果复选框为 false,则仅显示 doc.read=false 的文档。我不知道如何优雅地编写这个过滤器表达式。

【问题讨论】:

标签: javascript angularjs filter


【解决方案1】:

根据您的逻辑,您不需要过滤器,您可以使用 ng-if:

控制器:(或者如果你想在 HTML 中直接使用逻辑)

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

还有 HTML:

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

【讨论】:

    【解决方案2】:

    只能在模板中进行。这是一个例子:

    <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 指令在这里起到了作用。当未选中复选框时,模型 filterRead.read 设置为不等于 read 真或假的东西。所以结果是所有的记录都被渲染了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      相关资源
      最近更新 更多