如何仅过滤显示的元素? (不要过滤$$ hashKey)

时间:2016-12-01 17:44:12

标签: javascript html angularjs coffeescript

对象:

L2

Javascript(coffescript):

    Object
    $$hashKey: "object:25"
    id: 1
    category: "Fruit"
    name: "Apple"
    color: "red"
    __proto__: Object

HTML:

    $scope.fruits = [
       {id: 1, category: "Fruit", name: "Apple", color: "red"}
    ]

过滤代码(js / coffee)

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

所以我想要的是仅过滤显示的元素(id,类别,名称和颜色),但出于某种原因,当我在输入上键入25时,对象仍然显示,因为他的$$ haskKey。 / p>

1 个答案:

答案 0 :(得分:1)

感谢您添加过滤器代码。 解决方案应该像搜索匹配时明确忽略$$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语句更改为guard子句,这会降低代码缩进的级别
  • 将短doesMatch功能更改为单行
  • 在条件语句中使用andisisnt

主要更改是跳过key等于$$hashkey

的任何属性

这是未经测试的,所以我希望它适合你。