【问题标题】:ng-true-value='0' picking up wrong valuesng-true-value='0' 选择错误的值
【发布时间】:2016-09-26 21:15:36
【问题描述】:

有关演示,请参阅此处的 jsfiddle 并单击 Out of Stock 复选框。

它应该只显示数量为 0 的库存,但它也显示数量为 30。我认为这是因为它与字符串值匹配。

我认为问题在于:

ng-true-value='0'

解决此问题的最佳方法是什么?请问可以提供代码示例吗?

【问题讨论】:

标签: javascript html angularjs checkbox


【解决方案1】:

由于filter 也返回部分匹配的数据,因此当您与数量0 进行比较时,也与30 匹配,因为它还包含0

您可以在过滤器中使用true 进行精确匹配,例如:filter: searchInventory: true

可以通过一些棘手的方法仅对qty 进行精确匹配。当使用true 作为精确匹配时,当使用false 不是精确匹配时,所以使用true 仅用于'qty = 0'。

可以试试:

在控制器中添加另一个函数和变量

$scope.exactMatching = false; // initially set false

  $scope.changeStockFilter = function() { // this function call on change checkbox value
    if($scope.searchInventory.qty === '0') {
        $scope.exactMatching = true; // if qty 0 then set true
    } else {
       $scope.exactMatching = false;
    }
  };

在 html 中:

<div class="checkbox">
    <input type="checkbox" data-ng-model='searchInventory.qty' data-ng-true-value="'0'" data-ng-false-value='' ng-change="changeStockFilter()"> Out of Stock
</div>

 <div ng-repeat="item in inventory | filter: searchInventory : exactMatching | orderBy:sortOrder"> 

PLUNKER DEMO LINK

【讨论】:

    【解决方案2】:

    使严格值动态化:

    <div ng-repeat="item in inventory | filter: searchInventory:!!searchInventory.qty | orderBy:sortOrder">
    

    注意:如果您有多个相似的标准,这可能会变得混乱

    http://jsfiddle.net/wYfs4/648/

    【讨论】:

      【解决方案3】:

      它很丑,但它有效:

      <input type="checkbox" data-ng-model='searchInventory.qty' data-ng-true-value="0" data-ng-false-value='!0||0'> Out of Stock
      <input type="checkbox" data-ng-model='searchInventory.status' data-ng-true-value='inactive' data-ng-false-value='!inactive || inactive'> Inactive
      
      <div ng-repeat="item in inventory | filter: searchInventory:true | orderBy:sortOrder">
      

      【讨论】:

        【解决方案4】:

        根据filter docs,您需要添加额外的参数(比较器)以进行严格比较

        尝试改变:

        <div ng-repeat="item in inventory | filter: searchInventory | orderBy:sortOrder">
        

        <div ng-repeat="item in inventory | filter: searchInventory:true | orderBy:sortOrder">
        

        【讨论】:

        • 谢谢,确实有帮助 - 但问题是当复选框未选中时,它不会返回完整列表。
        • 可能需要使用自定义过滤功能
        猜你喜欢
        • 1970-01-01
        • 2016-01-19
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2016-09-04
        • 1970-01-01
        • 2015-07-26
        • 2016-06-24
        相关资源
        最近更新 更多