问题
My component is passed a notification.
A notification has an account, and an account has many contacts.
So I could easily do something like
{{#if (is-greater-than notification.account.contacts.length 0)}}
<p>stuff</p>
{{/if}}
To check for the existence of a contact, but what if I wanted to only display if at least one contact has firstName 'John', how could I do this in the component template only? Or if not possible in the template what is the next best approach?
I tried having a isHidden property in my component and then in the didInsertElement hook looping through contacts and then communications with the aim of checking myself - however I find contact.get('communications').forEach doesn't get hit because that level of data hasn't been pulled from the server at that point.
回答1:
For the first question, you could write a helper to do that:
// helpers/contains-john.js
export default function(array) {
return array.any((item) => item.get('firstName') === 'John');
};
Then use it as a subexpression just like you have above:
{{#if (contains-john notification.account.contacts)}}
Stuff
{{/if}}
来源:https://stackoverflow.com/questions/31456016/in-an-ember-component-template-how-can-i-use-if-to-check-for-at-least-one-of-a