How do I use ngRepeat on an element returned by a function (actually a filter) - AngularJS?

I need to use something like the following:

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

      

I need to use a function as I need the current element ngRepeat

to apply the filter.

The function getShopItems(id)

looks like this:

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

      

Usage ngInit

might help, but official documentation discourages it.

If we cannot use functions for ngRepeat

, how else should I apply the filter. Thanks in advance.

And here is the plucker: http://plnkr.co/ugOZ7QgQ3EHVQUGWTCII [not working]

EDIT: provider

and shop

are the same

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

+3


source to share


2 answers


You can use the filter as a custom filter:

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

      



and change the filter function a bit:

$scope.getShopItems = function(item) {
  return item.provider_id == $scope.shop.id; 
}

      

+2


source


I think you have two solutions, you run 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 views:   

  •     {{Item.name}}  


But it is possible that this solution does not work in your case, for example if your ID can be changed.

Another way to directly use your filter in views:

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

      

I would also recommend that you read this thread: How to loop through elements returned by a function using ng-repeat?

+1


source







All Articles