Imdad Imdad -4 years ago 87
AngularJS Question

Display object if the sub array has length of more than zero

<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;
}
}


I am trying to display only the 'types' that either...has a 'SubType' array of null or of a length greater than 0.

It's not working and was wondering if anyone knows that I am doing wrong? :)

Thank you.

Answer Source

You should have a ng-model to make it work.

Since you are using ng-repeat angular directive, it searches for an ng-model

Please run the below code

<!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>

Here is a working DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download