gpt4 book ai didi

AngularJS 复选框过滤器

转载 作者:行者123 更新时间:2023-12-03 13:15:32 25 4
gpt4 key购买 nike

我想过滤结果。

有一个酒单,我的愿望是当没有选中复选框时,显示整个酒单。

  • 仅选中 1 个复选框时显示相关类别
  • 选中多个复选框时显示相关类别

  • 我是 AngularJS 的新手,我尝试使用 ng-model 没有成功,这里是没有 ng-model 与函数关联的代码:
    <html ng-app="exampleApp">
    <head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script>

    <script>
    angular.module("exampleApp", [])
    .controller("defaultCtrl", function ($scope) {
    $scope.wines = [
    { name: "Wine A", category: "red" },
    { name: "Wine B", category: "red" },
    { name: "wine C", category: "white" },
    { name: "Wine D", category: "red" },
    { name: "Wine E", category: "red" },
    { name: "wine F", category: "white" },
    { name: "wine G", category: "champagne"},
    { name: "wine H", category: "champagne" }

    ];


    $scope.selectItems = function (item) {
    return item.category == "red";
    };

    $scope.selectItems = function (item) {
    return item.category == "white";
    };

    $scope.selectItems = function (item) {
    return item.category == "champagne";
    };
    });
    </script>
    </head>
    <body ng-controller="defaultCtrl">

    <h4>red: <input type="checkbox"></h4>
    <h4>white: <input type="checkbox"></h4>
    <h4>champagne: <input type="checkbox"></h4>



    <div ng-repeat="w in wines | filter:selectItems">
    {{w.name}}
    {{w.category}}
    </div>


    </body>
    </html>

    如何使用 ng-model 或 ng-change 将功能关联到每个复选框按钮以具有实时过滤模型?

    最佳答案

    有几种可能的实现方式。这是一个:

  • 有一个$scope.filter = {}对象来保存每个过滤器的状态。例如。 {red: true, white: false...} .
  • 使用 ng-model 将每个复选框与相应的属性相关联.例如:input type="checkbox" ng-model="filter['red']" /> .
  • 有一个函数(例如 $scope.filterByCategory(wine) )决定是否应该显示葡萄酒(基于 $scope.filter 对象)。
  • 使用该功能根据项目的类别过滤项目。例如。 <div ng-repeat="wine in wines | filter:filterByCategory">

  • filterByCategory函数可以这样实现:
    function filterByCategory(wine) {
    // Display the wine if
    var displayWine =
    // the wine's category checkbox is checked (`filter[category]` is true)
    $scope.filter[wine.category] || // or

    // no checkbox is checked (all `filter[...]` are false)
    noFilter($scope.filter);

    return displayWine;
    };

    在哪里 noFilter()是一个检查是否有任何过滤器被激活的函数(如果没有则返回 true):
    function noFilter(filterObj) {
    return Object.
    keys(filterObj).
    every(function (key) { return !filterObj[key]; });
    }

    另见 short demo .

    更新 :

    我创建了一个修改版本,它支持多个过滤器(不仅仅是按类别过滤)。
    基本上,它动态检测可用属性(基于第一个 wine 元素),添加控件(复选框组)以根据每个属性应用过滤器,并具有自定义过滤器功能:
  • 过滤每个 wine项目,基于每个属性。
  • 如果一个属性没有应用过滤器(即没有选中复选框),它将被忽略。
  • 如果属性选中了复选框,则用于过滤掉 wine项目(见上文)。
  • 有使用 AND(即所有属性必须匹配)或 OR(至少一个属性必须匹配)来应用多个过滤器的代码。


  • 另见 updated demo .

    关于AngularJS 复选框过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23983322/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com