如果子数组的长度大于零,则显示对象

时间:2017-03-02 06:48:10

标签: javascript html angularjs angularjs-directive

<select id="type" required name="type" ng-options="type.Name for type in types| filter:{Active:true} | filter:subTypeFilter(type)"><option value="" disabled selected>Choose your option</option>

$scope.subTypeFilter = function (type) {
    return function (item) {
        return item.SubTypes.length > 0;
    }
}

我试图只显示'类型',它们的'SubType'数组为null或长度大于0。

它没有用,并且想知道是否有人知道我做错了? :)

谢谢。

2 个答案:

答案 0 :(得分:1)

您应该 ng-model 才能使其正常运作。

由于您使用的是 ng-repeat 角度指令,因此会搜索 ng-model

请运行以下代码

&#13;
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


<select id="type" ng-model="typeSelected" required name="type" ng-options="type.name for type in types | filter:subTypeFilter(type)"><option value="" disabled selected>Choose your option</option>


</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.types = [{
        "name": "Alabama",
        "SubTypes": []
      }, {
        "name": "Alaska",
        "SubTypes": ["USA"]
      }, {
        "name": "Arizona",
        "SubTypes": ["USA"]
      }, {
        "name": "Alberta",
        "SubTypes": ["USA"]
      }, {
        "name": "British columbia",
        "SubTypes": []
    }];
    $scope.subTypeFilter = function (type) {
    return function (item) {
    console.log(item)
        return item.SubTypes.length > 0;
    }
}
});
</script>

<p>This example shows how to fill a dropdown list using the ng-options directive.</p>

</body>
</html>
&#13;
&#13;
&#13;

Here is a working DEMO

答案 1 :(得分:0)

难道你不必跳过第二个嵌套函数吗?

$scope.subTypeFilter = function (type) {
        return type.SubTypes != null && type.SubTypes.length > 0;
}

我认为该项目将是未定义的,因为它似乎是从无处传递