node.js 检查数组是否包含 angularjs 中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29197691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:33:20  来源:igfitidea点击:

Check if array contains value in angularjs

arraysangularjsnode.js

提问by vitalym

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:

在客户端,我有 $scope.loggedInUser,它指的是 mongoose 用户架构。我正在使用的另一个模式是对话模式。每个用户都可以加入对话,在这种情况下,他将被添加到conversation.participants 数组,其定义如下:

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?

但我没有看到。如何正确检查 ng-if(或通常为 angular)数组中是否存在元素?

采纳答案by Miniver Cheevy

You could use a filterlike

你可以使用像这样的过滤器

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:

其中 do 过滤是一种进行实际工作的方法,例如:

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

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

如果您在控制器端执行此操作,请务必将 $filter 注入您的控制器。