Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ngRepeat on element returned from a function (a filter, actually) - AngularJS?

I need to use something like the following:

<ul>
  <li ng-repeat='item in getShopItems(shop.id)'>{{item.name}}</li>
</ul>

I have to use a function since I need the current element of the ngRepeat to apply the filter.

The getShopItems(id) function is as follows:

$scope.getShopItems = function(id){
  filteredItems = $filter('filter')($scope.items, {shop_id: shop_id});
  return filteredItems; 
}

Using ngInit can help but the official documentation discourages it.

If we cannot use functions for ngRepeat, how else should I apply the filter. Thanks in advance.

And here's a plunker: http://plnkr.co/ugOZ7QgQ3EHVQUGWTCII [not working]

EDIT: provider and shop are the same

EDIT: I don't want to filter in view like item in items | filter:{}

like image 879
Faizuddin Mohammed Avatar asked Aug 16 '26 09:08

Faizuddin Mohammed


2 Answers

You could use filter as custom filter:

<ul>
  <li ng-repeat='item in items | filter:getShopItems'>{{item.name}}</li>
</ul>

and modify filter function a little:

$scope.getShopItems = function(item) {
  return item.provider_id == $scope.shop.id; 
}
like image 72
dfsq Avatar answered Aug 17 '26 22:08

dfsq


I think, you have two solution, either you init your array in your controller :

function getShopItems(id){
  filteredItems = $filter('filter')($scope.items, {provider_id: provider_id});
  return filteredItems; 
}

$scope.filterItems = getShopItems($scope.shop.id)

And for the views :

    {{item.name}}

But it is possible that this solution does not work in your case, for example if your id is suseptible to change.

A other way would be directly use your filter in the views :

<ul>
  <li ng-repeat='item in items|filter:{"id":shop.id}'>{{item.name}}</li>
</ul>

I would also recommand you to read this thread: How to Loop through items returned by a function with ng-repeat?

like image 27
Luc DUZAN Avatar answered Aug 17 '26 22:08

Luc DUZAN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!