0

Angular 1 app. Basically, there is an array of JSON object like this:

ctrl.messages = 
[
    {id: 1, text: 'hello1',createdBy:{name: 'Jack', hasBeenRead: false} }
    ,{id: 2, text: 'hello2',createdBy:{name: 'Steven', hasBeenRead: true} }
];

Now, in the view I print the messages like this:

<div ng-repeat="message in messages">
    Message: {{message.text}}
</div>

Somewhere else I have this html:

<div ng-if="messages.length > 0">
<button ng-if="?">Mark all read</button>
<button ng-if="?">Mark all unread</button>
</div>

The buttons above will never be showing together. But only one of them (and only if there are messages at all).

I wonder if it possibile to add in the ng-if above (in the button) a code for understanding if the button has to be showing. The button Mark all read will be showing only if there is at least one message marked with hasBeenRead: false. The button Mark all unread will be showing only if all the messages have been read.

I could do this in the controller. But I thought it would be neater if I could add this directly in the view. The difficulty for me is to access the hasBeenRead in the JSON from the view without iterating. Just asking "is there at least one unread message?".

Is there a way to do it in this way?

1
  • 1
    No, there isn't. Your options is either to create a filter or create some flag in your controller on which the statement ng-if should point to. I would go with the latter. Commented Feb 13, 2018 at 12:01

1 Answer 1

3

Create filter as below

app.filter('hasBeenRead', function () {
    return function (input) {
        return input.some(val => !val.createdBy.hasBeenRead);
    }
});


<div ng-if="messages.length > 0">
    <button ng-if="!messages|hasBeenRead">Mark all read</button>
    <button ng-if="messages|hasBeenRead">Mark all unread</button>
</div>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.