【问题标题】:AngularJS 1.x: filter bug(?) on null columnsAngularJS 1.x:在空列上过滤错误(?)
【发布时间】:2016-09-16 16:42:21
【问题描述】:

我有一个包含多个过滤器字段的表(每列一个)。

<table>
    <tr>
        <th><input type="text" ng-model="search.name"></th>
        <th><input type="text" ng-model="search.phone"></th>
        <th><input type="text" ng-model="search.secret"></th>
        <th><input type="text" ng-model="search.nullcol"></th>
    </tr>
    <tr ng-repeat="user in users | filter:search:strict">
        <td>{{user.name}}</td>
        <td>{{user.phone}}</td>
        <td>{{user.secret}}</td>
        <td>{{user.nullcol}}</td>
    </tr>
</table>

除了过滤包含空值的列外,一切正常:当我在过滤字段中键入内容时,所有带有 null 的行都会消失(正确),但删除过滤器不会恢复它们。

这里有一个 plunkr:https://plnkr.co/edit/viMHsxBHI4CjfjWqWjti

有没有办法让它工作?

【问题讨论】:

  • 我可能已经找到了解决方案:我在过滤器字段上放置了一个监视,当为空时,我从搜索对象中删除了该属性。这是更新后的 plunkr:plnkr.co/edit/7wE58QBUAqPHe8CGb4Bj 不过,我想知道是否存在更优雅的解决方案。

标签: javascript angularjs


【解决方案1】:

这是因为在输入文本并将其删除后,search.nullcol 的计算结果为空字符串而不是 null。

这是一种解决方案:您可以将ng-change 应用于nullcol 输入以检查它是否为空字符串。如果是这样,请将其设置为undefined。老实说,我不知道这是否是最佳做法,但它确实有效。我很惊讶我找不到这个怪癖的其他解决方案。

<th><input type="text" ng-model="search.nullcol"  ng-change="checkIfEmpty()"></th>

添加到 JS:

$scope.checkIfEmpty= function(){ 
   if ($scope.search.nullcol === '') {
      $scope.search.nullcol = undefined;
   } 
}; 

如果输入为空,这将“重置”过滤器。https://plnkr.co/edit/Uv5DdQ70kGRYZQEwXgrn?p=preview

【讨论】:

  • 感谢您的回复。您的解决方案与我的类似,在我在上面发表评论之前没有看到它。我仍然不完全理解发生了什么:我很欣赏“空字符串”可以被认为与空值不同,但对于非空值也是如此。我仍然认为在这种情况下需要进行适当的修复。
猜你喜欢
  • 1970-01-01
  • 2014-05-03
  • 2014-02-01
  • 2019-08-11
  • 2015-10-09
  • 2013-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-08-08
相关资源
最近更新 更多