Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array contains value in angularjs

On client side I have $scope.loggedInUser, which refers to mongoose user schema. Another schema I'm using is a conversation schema. Every user can join conversation, in that case he will be added to conversation.participants array, which is defined like that:

var conversationsSchema = new Schema({
    participants: {type: Array, default: []}
});

I want to display only conversation with current user (i.e. loggedInUser) in participants array. I tried

ng-repeat="conversation in conversations" ng-if="conversation.participants.indexOf(logged_in_user) > -1"

but I dodn't see any. How can I check if element exists in array in ng-if (or generally in angular) correctly?

like image 486
vitalym Avatar asked Mar 27 '26 06:03

vitalym


1 Answers

You could use a filter like

ng-repeat="conversation in conversations | filter:logged_in_user"

I'm not sure if the view side implementation will dig into the nested collection, you might have to filter it in the controller

filteredConversations  = $filter(this.conversations,
{name:logged_in_user},doFiltering);

where do filtering is a method to do the actual work, something like:

function (actual, expected) {
return actual.participants.indexOf(expected) > -1;
}

be sure to inject $filter into your controller if you do it controller side.

like image 80
Miniver Cheevy Avatar answered Mar 28 '26 23:03

Miniver Cheevy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!