AC3
AC3

Reputation: 355

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.

Upvotes: 0

Views: 4149

Answers (2)

Guillaume
Guillaume

Reputation: 549

Maybe something like this:

$scope.article_type = function(type) {
    for (i = 0; i < $scope.articles.length; i += 1) {
        if ($scope.articles[i].type === type) {
            return true;
        }
    }
    return false;
}

Then in your HTML:

<div ng-show="article_type('event')">

EDIT: Anik's answer is more optimal

Upvotes: 2

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

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')" >

Upvotes: 1

Related Questions