Search code examples
angularjsangularjs-ng-repeatangular-ng-if

Check length of an array of objects for a specific value in ng-if


I'm passing an array of objects that looks like this:

"articles": [
    {
        "_id": "1234",
        "type": "location",
        "content": {}
    },  
    {
        "_id": "1235",
        "type": "event",
        "content": {}
    }, ...

Then I use a ng-repeat to loop over this array where I filter by event:

    <div ng-if="articles.type == event && articles.length > 0">
        <h3>Events</h3>
        <ul>
            <li ng-repeat="article in articles | filter: { type: 'event'} track by $index">
                <h2>{{article.content.title}}</h2>
                <p>{{article.content.intro}}</p>
            </li>
        </ul>
    </div>

    <div ng-if="articles.type == location && articles.length > 0">
        <h3>Hotspots</h3>
        <ul>
            <li ng-repeat="article in articles | filter: { type: 'location'} track by $index">
                <h2>{{article.content.title}}</h2>
                <p>{{article.content.intro}}</p>
            </li>
        </ul>
    </div>

The behaviour I'm trying to achieve is if there are no articles with type event or location than I'm not showing them.

My question is how do I check this in my ng-if because now I'm checking the whole array's length instead of the array's length for that type of article.


Solution

  • Create a method in scope

    $scope.isExists=function(type){
      var obj = $scope.articles.find(function(x){ return x.type == type ; });
      return obj !== null;
    }
    

    Then try like this

    in html

    <div ng-if="isExists('event')">
    

    and

    <div ng-if="isExists('location')" >