【问题标题】:AngularJS Find a specific item based on property value using filterAngularJS使用过滤器根据属性值查找特定项目
【发布时间】:2015-05-27 06:25:52
【问题描述】:

我的情况是: 自定义过滤器以 JSON 格式返回 Product 类型的对象数组。每个产品对象都有 4-5 个属性,包括标题。

在 div 元素中,我想稍后使用标题为“Document Cloud”的产品的属性

基于这个答案How to filter by object property in angularJS 我将 HTML 代码编写为:

<div ng-repeat="product in filteredTopProducts=((products | categoryProductsSearchFilter:searchData:{title:'Document Cloud'}))" class='top-product-icon' ng-click="productClicked(product)">

    <img class='top-product-icon-img' ng-src="{{product.thumbnail}}"/>
    <div class='top-product-icon-title' ng-bind="product.title"></div>
</div>

1) products 是过滤器的输入

2) categoryProductsSearchFilter 是过滤器名称

3) searchData 是一个文本框模型名称 (ng-model),用户可以从中手动搜索和过滤产品

问题是上面没有过滤特定产品,而是显示所有产品,这意味着 {title:'Document Cloud'} 不起作用。

【问题讨论】:

  • 一个 jsfiddle 会很棒!

标签: javascript angularjs


【解决方案1】:

您需要使用 ng-model 进行输入,该输入将按标题过滤您的对象。比你 ng-repeat 只需按查询添加过滤器

<label for="filter">Filter by title</label>
<input type="text" ng-model="query.title">
<div ng-repeat="product in products | filter:query" ng-click="productClicked(product)">

指定要应用过滤器的属性

<input type="text" ng-model="queryTitle"> 
<div ng-repeat="product in products | filter:{ title: queryTitle }">

【讨论】:

  • 你有一个很好的答案在这里。但在我看来,var(查询)的设置并没有真正更糟糕。这里的问题是过滤器的混乱语法你提供了一个很好的例子
  • 编写一个单独的过滤器来返回我想要过滤的特定产品是一种好习惯吗?你不觉得上面的代码可能会让事情变得更复杂吗?
  • @Okazari 是的,如果我们在这里不需要过滤器输入,我们可以只使用
    。跨度>
  • @Sandeep 如果过滤器非常复杂,您应该生成自己的过滤器(例如:null 变为“N/A”,1 变为“1A”,2 变为“2A”)。对于数组上的简单文本过滤器,请使用内置的 angularjs 过滤器(此处为 ng-repeat)。 “queryTitle” var 可以根据需要进行初始化。 (或者像skymk所说的那样是静态的)
猜你喜欢
相关资源
最近更新 更多
热门标签