angular 过滤以显示匹配 parent 名称的唯一子复选框

angular Filter to display onlychild checkboxes matching parent name

我在使它正常工作时遇到问题...至少在某种程度上是正常的。

我有 parent 个复选框和 children 个复选框,它们来自 objects 个数组。

$scope.parents = [
    {name: 'check1', value: 'ck1'},
    {name: 'check2', value: 'ck2'}
];

$scope.children = [
    {name: 'child1', value' ch1', parent: 'ck1'},
    {name: 'child2', value: 'ch2', parent 'ck2'}
];

我可以让它工作,但问题是在某些情况下我有 8 个 children,目前我隐藏了任何不适合正确 parent 的复选框,但它们仍然显示在 DOM 上,这意味着 parent 复选框之间有一个巨大的 space,即使没有选中任何内容。我试过使用 ng-if 而不是 ng-hide,但这也不起作用,它们仍然显示相同。它运行正常,只有匹配 parent 值的 children 出现,但它们仍然在 DOM 中,即使在不可见的情况下也会在屏幕上占据 space。

所以我想看看是否有一种使用 angular 过滤器的方法可以做到这一点,但我一直无法让它工作...

我试过了

ng-repeat="parent in parents track by $index"
...<checkbox>...
ng-repeat="child in children | filter: {'parent': {{parent.value}}} track by $index" 
...<checkbox>...

但这不能正常工作,我收到一个错误...基本上我需要比较 children 中的 'parent' 属性 和 parent.value parent 复选框...有没有办法通过我正在使用的过滤方法来做到这一点?如果没有,是否有一种简单的方法只让匹配的元素显示在 parent 下方,而不是所有元素?

理想情况下,在选中 parent 之前,复选框之间的 space 很少,然后添加 children 并通过调整其他复选框为它们腾出空间向下...

如有任何帮助,我们将不胜感激

您可以创建自定义过滤器来检查父复选框的选中状态并相应地显示子复选框

js

  $scope.myCustomFilter = function(row){
    var flag = false;
    angular.forEach($scope.parents, function(value, key){
        if(value.checked){
          if(value.value == row.parent)
            flag = true;
        }
    });

    return flag;
  }

html

<div ng-repeat ="item in parents">
   <input type="checkbox" ng-value="item.value" ng-model="item.checked"> {{item.name}}
</div>
<div ng-repeat ="item in children | filter: myCustomFilter">
   <input type="checkbox" ng-value="item.value"> {{item.name}}-Parent: {{item.parent}}
</div>

Demo

一种更简单的处理方式是在嵌套的 ng-repeat.

中有一个 ng-if
<div ng-repeat="parent in parents">
    <label>
        <input type="checkbox" ng-model="selectedParent[parent.value]" value="parent.value"/>
        <span ng-bind="parent.name"></span>
    </label>
    <div ng-repeat="child in children" ng-if="selectedParent[child.parent] && child.parent === parent.value">
        <label>
            <input type="checkbox" ng-model="selectedChild[child.value]" value="child.value"/>
            <span ng-bind="child.name"></span>
        </label>
    </div>
</div>

以上代码将确保

  • children 元素仅在选择 parent 时出现
  • 其他不必要的元素不是由 Angularjs
  • 创建的
  • 复选框元素
  • 之间没有不必要的space
  • 对于给定的 parent
  • ,无论 children 的数量如何,这都将起作用