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

时间:2015-11-12 10:57:33

标签: angularjs angularjs-ng-repeat angular-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.

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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