将过滤器分配给Angular JS中的对象变量

Jor*_*ash 8 angularjs ng-repeat angularjs-ng-repeat angularjs-filter

我有一个ng-repeat使用这样的过滤器:

#1
<div class="contestReports" ng-repeat="contest in contests | filter:{votingOver:true}">
    <contestreport></contestreport>
</div>
Run Code Online (Sandbox Code Playgroud)

我想让客户能够过滤它,所以我已经将过滤器分配给这样的变量:

#2
<div ng-init="reportFilter = {votingOver:true}"></div>
<div class="contestReports" ng-repeat="contest in contests | filter:reportFilter">
    <contestreport></contestreport>
</div>
Run Code Online (Sandbox Code Playgroud)

代码#1正在运行,但代码#2不是,我不知道为什么.

she*_*hen 3

你是否也尝试过包裹ng-init

<div ng-init="(reportFilter = '{votingOver:true}')"></div>
Run Code Online (Sandbox Code Playgroud)

然而,正如我之前在评论中所说的 - angularjs 文档指出,在大多数情况下使用 ngInit 都是一种不好的做法。因此,如果可能的话,这不应该成为您问题的解决方案。

你的#2代码确实有效,请检查这个plunk - http://plnkr.co/edit/dBDyYPd3ZoUVdXngu52t?p=preview

//html
  <div ng-init="reportFilter = {votingOver:false}"></div>
<div class="contestReports" ng-repeat="contest in contests | filter:reportFilter">
  {{contest | json}}
</div>

  </div>

//js in controller
  $scope.contests = [
    {id:1, title:'1', votingOver:false},
    {id:2, title:'2', votingOver:true},
    {id:3, title:'3', votingOver:true}
    ];
Run Code Online (Sandbox Code Playgroud)