简体   繁体   English

Angular JavaScript过滤器函数,使用$ scope输入进行更新

[英]Angular JavaScript filter function, updating with $scope input

I'm currently writing a little function to take a $scope value from an input field, then add it to a new array containing invited users. 我正在编写一个小函数来从输入字段中获取$ scope值,然后将其添加到包含受邀用户的新数组中。

To prevent duplicate entries into the array I'm trying to use JavaScript's filter method. 为了防止重复进入数组,我正在尝试使用JavaScript的过滤方法。

My problem is when I look at whats being output to the console, the console.log inside the filter function always prints the same Email value, it doesn't seem to update and consider the new input. 我的问题是,当我查看输出到控制台的是什么时,过滤器函数内的console.log始终打印相同的电子邮件值,它似乎没有更新并考虑新的输入。 eg a user has added 2 users, the first will be added and the invitesArr will only contain the first Email. 例如,用户添加了2个用户,第一个将被添加,而invitesArr将只包含第一个电子邮件。

        var invitesArr = $scope.invites;
        console.log(invitesArr)
        console.log($scope.searchContacts)

        if ($scope.invites.length >= 0) {
            invitesArr.filter(function(invitesArr) {
                console.log(invitesArr.Email)
                return invitesArr.Email === $scope.searchContacts;
            });

            if (invitesArr == false) {
                courseAccountService.inviteGuestToCourse($scope.courseId,$scope.searchContacts).
                then(function(invitation) {
                    $scope.invites.push(invitation);
                });
            }
        }

Try the below code: 请尝试以下代码:

var invitesArr = $scope.invites;
    console.log(invitesArr)
    console.log($scope.searchContacts)

    if ($scope.invites.length >= 0) {
       //use arrow operator instead of function.
       var duplicateEmails = invitesArr.filter((item) => {
            console.log(invitesArr.Email)
            //assuming datatype of item.Email and $scope.searchContacts are same else use == for comparision
            return item.Email === $scope.searchContacts; 
        });

        //Check for length and then push to your invites
        if (duplicateEmails.length==0) {
            courseAccountService.inviteGuestToCourse($scope.courseId,$scope.searchContacts).
            then(function(invitation) {
                $scope.invites.push(invitation);
            });
        }
    }

Hope it helps!! 希望能帮助到你!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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