简体   繁体   中英

ng-show if filtered array contains

I cant find a way to show an html-element only if an array contains a particular value among its objects. So if I have:

people[
    {
        id:1, name: 'frank', type: 'good'
        ,id:2, name: 'john', type: 'bad'
        ,id:3, name: 'mary', type: 'good'
    }
]

I would like to show some kind of heading for the types. So if the types are:

"great"
"good"
"bad"

with the array above, the heading for "great" should not be visible.

I have tried with both ngif and ngshow. Problem seems to be about syntax. The last one I tried is:

(people|filter:(type:'great'))

But I get an error in the console.

Is it possible to fix it directly in the html or should I rely on the controller for this kind of operation?

First, your example "array" is badly formed, I'm assuming you meant:

people = [
    { id:1, name: 'frank', type: 'good' },
    { id:2, name: 'john',  type: 'bad' },
    { id:3, name: 'mary',  type: 'good' }
];

Second, your questions is a bit confusing, but I'm assuming you want to show each person under a header corresponding to their type, and hide headers with no people. Try this:

<div ng-if="$filter('filter')(people,{type:'great'}).length > 0">
    <h1>Great</h1>
    <p ng-repeat="person in people | filter:{type:'great'}">{{person.name}}</p>
</div>
<div ng-if="$filter('filter')(people,{type:'good'}).length > 0">
    <h1>Good</h1>
    <p ng-repeat="person in people | filter:{type:'good'}">{{person.name}}</p>
</div>

You can improve this by creating a second array like:

types = [
    { id: 'great', header: 'Great' },
    { id: 'good',  header: 'Good' },
    { id: 'bad',   header: 'Bad' }
];

And then just nest your repeats:

<div ng-repeat="type in types" ng-if="$filter('filter')(people,{type:type.id}).length > 0">
    <h1>{{type.header}}</h1>
    <p ng-repeat="person in people | filter:{type:type.id}">{{person.name}}</p>
</div>
  • Note that I haven't tested this code, only looked it over. It probably includes bugs, but the method should work.
  • You will need to add $filter as a dependency of your controller, and inject it

The TL/DR is: the $filter service allows you to use Angular filters in JS expressions. The 'filter' filter returns an array, so filter your people and check the length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM