繁体   English   中英

如何在函数返回的元素上使用ngRepeat(实际上是一个过滤器) - AngularJS?

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

我需要使用以下内容:

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

我必须使用一个函数,因为我需要ngRepeat的当前元素来应用过滤器。

getShopItems(id)函数如下:

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

使用ngInit可以提供帮助,但官方文档不鼓励它。

如果我们不能使用ngRepeat函数,我应该如何应用过滤器。 提前致谢。

这里有一个吸血鬼: http ://plnkr.co/ugOZ7QgQ3EHVQUGWTCII [不工作]

编辑: providershop是相同的

编辑:我不想在视图中过滤item in items | filter:{} item in items | filter:{}

您可以将过滤器用作自定义过滤器:

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

并稍微修改过滤功能:

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

我想,你有两个解决方案,要么在控制器中初始化你的阵列:

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

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

对于意见:

    {{项目名称}}

但是,这种解决方案可能不适用于您的情况,例如,如果您的ID可以改变。

另一种方法是直接在视图中使用您的过滤器:

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

我还建议你阅读这个帖子: 如何循环使用ng-repeat函数返回的项目?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM