【问题标题】:How do i filter only the displayed elements? (dont filter the $$hashKey)如何仅过滤显示的元素? (不要过滤 $$hashKey)
【发布时间】:2017-04-16 11:21:55
【问题描述】:

对象:

    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/coffee)

    .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,该对象仍然显示。

【问题讨论】:

  • 请提供您的过滤器代码,如果您使用的是图书馆中已有的,请提供描述/链接/文档
  • 添加了过滤代码。

标签: javascript html angularjs coffeescript


【解决方案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 语句更改为保护子句,这降低了代码的缩进级别
  • 将简短的 doesMatch 函数更改为单行
  • 在条件语句中使用andisisnt

主要变化是跳过key等于$$hashkey的任何属性

这是未经测试的,所以我希望它对你有用。

【讨论】:

  • 非常感谢!现在它不过滤 hashKey,如果我只能要求更多,它也会过滤一个数值,例如对象“Apple”的权重为 15,所以如果我输入 15,它会为我带来这个对象(假设在html中显示重量)$scope.fruits = [ {id: 1, category: "Fruit", name: "Apple", color: "red", weight: 15} ]
  • 我在玩这行“typeof(value) is 'string'”,我设法通过将'string'换成'number'来做我想做的事,但我怎么能加一个加号,所以我可以过滤两者,例如(typeof(value)是'string'和/或'number')
  • 没关系,我设法找到了解决方案,呵呵,只是复制了以下行: (return true for att, value of el when typeof(value) is 'string' and doesMatch(value) and att isnt '$$hashKey' 和 att isnt 'id') 并输入 'number' 而不是 'string'
猜你喜欢
  • 2018-03-20
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多