角度ng-如果有任何子项包含

时间:2016-10-15 22:26:28

标签: javascript angularjs angular-ng-if

如果数据集包含符合条件的任何对象,我会尝试根据返回的数据有条件地显示和隐藏列。

以下是我的搜索结果中返回的数据示例

[
    {
        "id": "typeahead-241-1091-option-0",
        "label": "Android Home Page",
        "model": {
            "type": "link",
        }
    },
    {
        "id": "typeahead-241-1091-option-1",
        "label": "Google",
        "model": {
            "type": "link",

        }
    },
    {
        "id": "typeahead-241-1091-option-2",
        "label": "Forgotten Google Play Password",
        "model": {
            "type": "kb",

        }
    }
]

现在我根据类型在列中显示数据。

<div class="flexitem">
  <h4>External Links</h4>
  <div ng-repeat="match in matches" ng-if="match.model.type == 'link'">{{match.label}}</div>
</div>
<div class="flexitem">
  <h4>Knowledge Base</h4>
  <div ng-repeat="match in matches" ng-if="match.model.type == 'kb'">{{match.label}}</div>
</div>
<!-- the below has no results. I want it hidden altogether
currently it shows the <h4>Products</h4> with nothing below it-->
<div class="flexitem">
  <h4>Products</h4>
  <div ng-repeat="match in matches" ng-if="match.model.type == 'product'">{{match.label}}</div>
</div>

我需要完成的是在flexitem div上完全放置条件,只显示该类型是否有结果。因此,如果类型==&#39;产品&#39;没有结果,那么甚至不显示div。该行上的ng-if可以正常工作,但循环所有匹配子项以确定是否有结果的最佳方法是什么? indexOf不通过子数组工作。

1 个答案:

答案 0 :(得分:1)

使用Array.filter将逻辑放在角度侧,以分隔数组;

角度控制器:

$scope.linkMathches = $scope.matches.filter(function(m){
  return m.model.type === 'link'
});
$scope.kbMathches = $scope.matches.filter(function(m){
  return m.model.type === 'kb'
});

HTML:

<div class="flexitem" ng-if="linkMathches.length">
  <h4>External Links</h4>
  <div ng-repeat="match in linkMathches">
    {{match.label}}
  </div>
</div>
<div class="flexitem" ng-if="kbMathches.length">
  <h4>Knowledge Base</h4>
  <div ng-repeat="match in kbMathches">
    {{match.label}}
  </div>
</div>

进一步了解model.type中的动态值:

角度控制器:

$scope.typeMatches = {
  link: {title: 'External Links', matches: []},
  kb: {title: 'Knowledge Base', matches: []},
  product: {title: 'Products', matches: []}
};

$scope.matches.forEach(function(match){
  $scope.typeMatches[match.model.type].matches.push(match);
});

HTML:

<div class="flexitem"
    ng-if="value.matches.length"
    ng-repeat="(key,value) in typeMatches">
  <h4>{{value.title}}</h4>
  <div ng-repeat="match in value.matches">
    {{match.label}}
  </div>
</div>