【问题标题】:Angular-filter by select value按选择值进行角度过滤
【发布时间】:2016-06-26 12:32:32
【问题描述】:

我有一个应用程序,我想根据“选择”包含产品类型的值过滤一长串产品。过滤器有效,但只有在我选择了一些东西之后。它最初设置“显示全部”选项,但会过滤掉所有内容。如果我选择其他东西,它会起作用,如果我重新选择“显示全部”它会起作用。但是为什么过滤器最初不起作用?

模型(看起来像这样):

$scope.products = {[
    {name: 'productA',Type: 1},
    {name: 'productB',Type: 1},
    {name: 'productC',Type: 2},
    {name: 'productD',Type: 2},
]};

$scope.productTypes = {[
    {Name: 'typeAlpha',Type: 1},
    {Name: 'typeBravo',Type: 2},
]};

HTML:

<select id="productFilter" data-ng-model="productFilter">
    <option value="" selected="selected">Show all</option>
    <option data-ng-repeat="type in productTypes" value="{{type.Type}}">{{type.Name}}</option>          
</select>
<p data-ng-repeat="product in products | filter:{Type:productFilter} ">{{product.Name}}</p>

【问题讨论】:

  • 这应该是什么意思 $scope.products = {[...]}; ?它应该是数组 $scope.products = [{...}, ...];或对象 $scope.products = {};此示例不起作用。

标签: angularjs select filter angularjs-ng-repeat


【解决方案1】:

您设置了 $scope.productFilter = ''。 所以它在过滤器处默认返回空白。

【讨论】:

    【解决方案2】:

    我建议在选项上使用 ng-options 而不是 ng-repeat:

    <select id="productFilter" ng-model="productFilter" 
      data-ng-options="type.type as type.name for type in productTypes">
        <option value selected="selected">Show all</option>
    </select>
    <p data-ng-repeat="product in products | filter:(!!productFilter || undefined) && {type: productFilter}">
        {{product.name}}
    </p>
    

    对于“显示全部”,过滤器必须返回 undefined (ng-repeat filter "show all" items if no filter selected)

    还删除了数组周围的 {..} 并更好地使用小写的属性:

      $scope.products = [
        {name: 'productA', type: 1},
        {name: 'productB', type: 1},
        {name: 'productC', type: 2},
        {name: 'productD', type: 2}
      ];
    
      $scope.productTypes = [
        {name: 'typeAlpha', type: 1},
        {name: 'typeBravo', type: 2}
      ];
    

    这是一个 jsbin(基于 Hiskinds) http://jsbin.com/yepaqikodo/1/edit?html,js,output

    【讨论】:

      【解决方案3】:

      在第二个 ng-repeat 过滤器中使用 product.Type 而不是Type

      【讨论】:

      • 嗯...这似乎总是过滤掉所有内容
      • 它到底在做什么?
      【解决方案4】:

      这是一个基于上述代码的工作示例:http://jsbin.com/buzafisuko/edit?html,js,output

      Slava.N 的评论是正确的,您不应将 productTypes 和 product 包装在 {}

      另外,JavaScript 是一种区分大小写的语言,product.Name 始终未定义,您应该在 HTML 中使用 product.name

      【讨论】:

        猜你喜欢
        • 2015-10-17
        • 1970-01-01
        • 2021-10-29
        • 2017-06-03
        • 2020-01-26
        • 2017-11-02
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多