Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a filter to an object variable in Angular JS

I have an ng-repeat using a filter like this:

#1
<div class="contestReports" ng-repeat="contest in contests | filter:{votingOver:true}">
    <contestreport></contestreport>
</div>

I want to allow the customer to be able to filter it so I have assigned the filter to a variable like this:

#2
<div ng-init="reportFilter = {votingOver:true}"></div>
<div class="contestReports" ng-repeat="contest in contests | filter:reportFilter">
    <contestreport></contestreport>
</div>

Code #1 is working but Code #2 is not and I'm not sure why.

like image 917
Jordash Avatar asked Feb 18 '16 03:02

Jordash


People also ask

What are the correct way to apply filter in AngularJS?

In AngularJS, you can also inject the $filter service within the controller and can use it with the following syntax for filter. Syntax: $filter("filter")(array, expression, compare, propertyKey) function myCtrl($scope, $filter) { $scope. finalResult = $filter("filter")( $scope.

What is the role of a filter in AngularJS?

AngularJS Filters allow us to format the data to display on UI without changing original format. Filters can be used with an expression or directives using pipe | sign. Angular includes various filters to format data of different data types. The following table lists important filters.


1 Answers

Did you also try to wrap ng-init

<div ng-init="(reportFilter = '{votingOver:true}')"></div>

However, as I've stated in my comment earlier - angularjs documentation states that using ngInit is a bad practice in mostly all cases. So that should not be a solution to your problem if possible.

And your #2 code actually works, please check this 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}
    ];
like image 148
shershen Avatar answered Nov 05 '22 19:11

shershen