Tony
Tony

Reputation: 12705

AngularJS, ng-repeat + filter to be called from controller

I have a tricky question

html:

ng-repeat="item in obj.Items | filter:someFilter"

JS:

$scope.someFilter = function (item) { ... }

which works. But the problem is, I need to be able to manually invoke the someFilter somewhere inside in controller.

OK, I know I can do the $filter("someFilter")(...) but that filter requires an item object from the ng-repeat. So, how can I provide that argument ?

Upvotes: 0

Views: 397

Answers (2)

Stepan Kasyanenko
Stepan Kasyanenko

Reputation: 3186

You can define a filter in two ways.

  • As a function of $scope.It's your way.
  • Create your own filter.

In the second case, when you call $filter, then as a parameter you will need to pass an array to filter your items.

Live example on jsfiddle

<form name="ExampleForm">
  Filter by $scope function fillArr
  <div ng-repeat="a in arr|filter:fillArr">
    {{a}}
  </div>
   Filter by filter filArrFilter
  <div ng-repeat="a in arr|filArrFilter">
    {{a}}
  </div>
    Filtered in $scope manualy
  <div ng-repeat="a in filteredArr">
    {{a}}
  </div>
</form>

And JS controller

$scope.arr = [1, 2, 3, 4, 5, 6, 8];
$scope.fillArr = function(item) {
  return item % 2 == 0;
}
$scope.filteredArr = $filter('filArrFilter')($scope.arr);

And JS filter

.filter('filArrFilter', function() {
return function(items) {
  var result = [];
  angular.forEach(items, function(item) {
    if (item % 2 == 0)
      result.push(item);
  });
  return result;
}
})

Upvotes: 0

Shashank
Shashank

Reputation: 2060

Please find the code below for the issue raised:

angular.forEach(obj.Items, function (key, value) {
    $scope.someFilter(value);
});

Upvotes: 1

Related Questions