【问题标题】:angularjs : filter an array with a comboboxangularjs:使用组合框过滤数组
【发布时间】:2014-05-21 16:42:14
【问题描述】:

我知道如何以输入文本作为过滤器来过滤数组。 是否可以使用带有组合框的 angularjs 的过滤器属性作为过滤器选项?

例如,我有一组年份:[2014,2014,2013,1987,1987] 我想使用具有以下值的组合框过滤此数组:{blank,2014,2013,1987} 在此组合框中,如果单击空白,则数组显示初始值,否则显示过滤后的值。

如果我单击 Select 标记的第一个选项,下面的代码不允许我重新初始化数组:

<select ng-model="search.date" ng-options="year for year in years">
        <option value=""></option>
</select>
<table class="table table-striped">
     <thead>
       <tr>
          <th>Label</th>
          <th>Categorie</th>
          <th>Montant</th>
          <th>Date</th>
       </tr>
     </thead>
     <tbody>
        <tr ng-repeat="budget in filteredBudgets | filter:search:strict">
          <td>{{budget.label}}</td>
          <td>{{budget.category}}</td>
          <td>{{budget.real}}</td>
          <td>{{budget.date}}</td>
        </tr>
     </tbody>
</table>

提前致谢。

【问题讨论】:

  • 不清楚,为什么不分享你的 html 和编码的应用程序到目前为止
  • 我的代码:&lt;select ng-model="search.date" ng-options="year for year in years"&gt;&lt;option value=""&gt;&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;tr ng-repeat="budget in filteredBudgets | filter:search:strict"&gt;....&lt;/tr&gt; 抱歉,我不知道如何使用简答命令转到下一行。
  • 您知道您可以编辑您的问题并将其包含在其中吗?

标签: arrays angularjs filter


【解决方案1】:

问题是一旦你选择了空选项,modelValue 就变成了null
因此,将对象{date: null} 传递给filter,它将尝试使用date: null 的许多项目。

为了满足您的这一特定要求(即将search 中的null 值视为根本没有定义),您可以定义一个接收项目的函数并且(基于search 对象) 确定是否应将其过滤掉。

然后,您可以将该谓词函数用作 Angular 的 filter 过滤器的参数。

例如:

<tr ng-repeat="budget in filteredBudgets | filter:filterBySearch">

$scope.filterBySearch = function (item) {
    return Object.keys($scope.search || {}).every(function (key) {
        var value = $scope.search[key]; 
        return (value === undefined) || 
               (value === null) ||
               value === item[key];
    });
};

另请参阅此short demo


here 提供了一个稍微复杂一点的演示。它允许将strict 参数传递给谓词函数。


更新

另一种方法是实现具有以下功能的自定义指令(并将其添加到&lt;select&gt; 元素):

它将监视模型值的变化并将任何 null 值转换为 undefined
这解决了问题,因为如果search 的属性的值为undefined,就好像它根本不存在。

例如:

<select ... null-is-undefined>...</select>

app.directive('nullIsUndefined', function () {
    return {
        restrict: 'A',
        require: 'ngModel',   // <-- this is required for accessing the ngModelController
        link: function postLink(scope, elem, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (newViewValue) {
                if (newViewValue === null) {
                    newViewValue = undefined;
                }
                return newViewValue;
            });
        }
    };
});

另请参阅此short demo

【讨论】:

  • 非常感谢您的回答。在您的两个解决方案之间是否有一个最好(正确)的解决方案?或者他们是平等的?
  • 两者都是“合适的”(他们完成了工作并且足够Angular)。我认为第二个效率更高一些(尤其是随着项目列表的增长),但是您需要确保您对无法将模型设置为 null 的事实感到满意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 2014-01-30
  • 2017-06-28
  • 1970-01-01
相关资源
最近更新 更多