对象:
Object
$$hashKey: "object:25"
id: 1
category: "Fruit"
name: "Apple"
color: "red"
__proto__: Object
javaScript(咖啡本):
$scope.fruits = [
{id: 1, category: "Fruit", name: "Apple", color: "red"}
]
html:
<input type="search" ng-model="fruitSearch"/>
<div ng-repeat="i in filtro = (fruits | scFilter:fruitSearch)">
<div>{{i.id}}</div>
<div>{{i.category}}</div>
<div>{{i.name}}</div>
<div>{{i.color}}</div>
</div>
过滤代码(JS/咖啡)
.filter "scFilter", () ->
(collection, search) ->
if search
regexp = createAccentRegexp(search)
doesMatch = (txt) ->
(''+txt).match(regexp)
collection.filter (el) ->
if typeof el == 'object'
return true for att, value of el when (typeof value == 'string') && doesMatch(value)
doesMatch(el)
false
else
collection
所以我想要的是仅过滤显示的元素(ID,类别,名称和颜色),但是由于某种原因,当我在输入上键入25时,该对象仍然显示出来,因为他的$$ HASKKEY。<<<<<<<<
感谢您添加过滤器代码。该解决方案应像搜索匹配项时明确忽略$$hashKey
一样简单:
.filter "scFilter", () ->
(collection, search) ->
return collection unless search
regexp = createAccentRegexp(search)
doesMatch = (txt) -> (''+txt).match(regexp)
collection.filter (el) ->
if typeof el == 'object'
return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey'
else
doesMatch(el)
我添加了一些小重构:
- 我将最高级别的if语句更改为后卫条款,这降低了代码的压痕层
- 将简短的
doesMatch
功能更改为一个衬里 - 在您的条件语句中使用
and
,is
和isnt
主要更改是跳过任何 key
等于 $$hashkey
这是未经测试的,所以我希望它对您有用。