简体   繁体   English

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

[英]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. 我必须使用一个函数,因为我需要ngRepeat的当前元素来应用过滤器。

The getShopItems(id) function is as follows: getShopItems(id)函数如下:

$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. 使用ngInit可以提供帮助,但官方文档不鼓励它。

If we cannot use functions for ngRepeat , how else should I apply the filter. 如果我们不能使用ngRepeat函数,我应该如何应用过滤器。 Thanks in advance. 提前致谢。

And here's a plunker: http://plnkr.co/ugOZ7QgQ3EHVQUGWTCII [not working] 这里有一个吸血鬼: http ://plnkr.co/ugOZ7QgQ3EHVQUGWTCII [不工作]

EDIT: provider and shop are the same 编辑: providershop是相同的

EDIT: I don't want to filter in view like item in items | filter:{} 编辑:我不想在视图中过滤item in items | filter:{} item in items | filter:{}

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; 
}

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. 但是,这种解决方案可能不适用于您的情况,例如,如果您的ID可以改变。

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

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

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