【问题标题】:Show all filter on Aurelia value converter在 Aurelia 值转换器上显示所有过滤器
【发布时间】:2016-08-12 07:16:49
【问题描述】:

目前我的应用程序当前显示练习,然后使用选择选项按肌肉群过滤它们。我很难理解如何最初显示所有这些。

一旦加载应用程序,它就已经被肌肉群过滤了,或者如果它被“all”值过滤,它不会显示任何内容,因为这不是我的 JSON 中指定的肌肉群。它的组织方式如下:

选择调用过滤器的选项(肌肉过滤器只是所有肌肉群的数组)

<div class="form-group">
   <label for="muscle">Show:</label>
      <select id="muscle" ref="muscle">
      <option value="all">All</option>
      <option repeat.for="muscle of muscleFilters" value.bind="muscle">${muscle}</option>
   </select>
</div>

显示

<div class="col-sm-6 col-md-3" repeat.for="exercise of exercises | sortMuscle:muscle.value">
${exercise.title}
</div>

排序功能

export class SortMuscleValueConverter {
  toView(array, propertyName) {
    return array
      .slice(0).filter(function (i) {
          return (i.muscle === propertyName);
      });
  }
}

选择“全部”选项后,如何显示所有数据?我还有一个搜索功能,需要在提交时清除所有过滤器,以便搜索所有数据。

提前致谢。

【问题讨论】:

    标签: javascript aurelia


    【解决方案1】:

    您可以在值转换器中使用简单的if 语句:

    // Note: convertor name is misleading - it does filtering, not sorting
    export class SortMuscleValueConverter {
      toView(array, propertyName) {
        if (propertyName === 'all') {
          return array;
        }
    
        // Simplified filter
        return array.filter(i => i.muscle === propertyName);
      }
    }
    

    作为替代方案,这里有一个通用的FilterValueConverter,您可以使用它来过滤任何属性(使用相等性):

    export class FilterValueConverter {
      toView(array, propertyName, filter) {
        if (!filter) {
          return array;
        }
    
        return array.filter(item => item[propertyName] === filter);
      }
    }
    

    用法:

    <!-- option for All needs to have an empty value -->
    <option value="">All</option>
    
    <div class="col-sm-6 col-md-3" 
         repeat.for="exercise of exercises | filter:'muscle':muscle.value">
      ${exercise.title}
    </div>
    

    【讨论】:

    • 答案绝对准确。欣赏它。我之前确实尝试在转换器中使用 if 语句,但它没有返回原始数组!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 2012-12-29
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多