Search code examples
javascriptangularjsangularjs-ng-repeatangular-ng-if

AngularJS: ngIf in array of array with different properties


my object:

objects = [
{
    name: "1",
    foo: [{
      value: 0.5,
      ignored: null,
      text: "foo1"
    }, {
      value: 0,
      ignored: null,
      text: "foo"
    }]
},
{
    name: "2",
    foo: [{
      value: 0,
      ignored: null,
      text: "foo"
    }, {
      value: 0.5,
      ignored: null,
      text: "foo2"
    }]
},
{
    name: "3",
    foo: [{
      value: 0.5,
      ignored: null,
      text: "foo3"
    }]
},
{
    name: "4",
    foo: [{
      value: 0,
      ignored: 1,
      text: "foo4"
    }]
},
{
    name: "5",
    foo: [{
      value: 0,
      ignored: null,
      text: "foo5"
    }]
}]

my AngularJs template html:

<div class="row" ng-repeat="object in objects">
  {{ object.name }}
  <div ng-repeat="foo in object.foo">
    <div ng-if="foo.value > 0 || foo.ignored == 1">
      {{ foo.text }}
    </div>
  </div>
</div>

My result is:

1 foo1
2 foo2
3 foo3
4 foo4
5

but i do not want display object.name for case N°5.

How to use 2nd ng-repeat and ng-if in 1st ng-repeat please?

<div class="row" ng-repeat="object in objects" ng-if="...???...">
  {{ object.name }}
  any text !!
</div>

Solution

  • You can use a filter function in ng-if.

    Changed template:

    <div class="row" ng-repeat="object in objects" ng-if="myFilter(object)">
      {{ object.name }}
      <div ng-repeat="foo in object.foo">
        <div ng-if="foo.value > 0 || foo.ignored == 1">
          {{ foo.text }}
        </div>
      </div>
    </div>
    

    Filter function in your controller:

    $scope.myFilter = function(o) {
      // Returns a truthy value if the foo-subarray meets the criteria.
      var found = o.foo.find(function(fooElement) {
        return fooElement.value > 0 || fooElement.ignored == 1;
      });
      return found;
    };
    

    Result:

    1
    foo1
    2
    foo2
    3
    foo3
    4
    foo4