1

I am learning AngularJS. I am trying to make a custom directive that checks if email already exists. I get my emails from array that has like 9 users and I can successfully get them using Factory. My problem with my custom directive is that no matter what input I enter the button will be disabled. The idea of the directive is when I lose focus it will check if the email exist or it doesn't if it does it will disable the button if it doesn't then the button will be enabled.

.directive("registerUser",function(){
                            return {
                             
                                link:function($scope, element) {
                                    element.bind('blur',function () {
                                        var emailInput = element.val();
                                        var flag = "false";
                                        $scope.registeredUsers.forEach(element => {
                                            if(emailInput === element.email){
                                               flag = "true";
                                               console.log(emailInput);
                                               console.log(flag);
                                               return;
                                            }
                                        });
                                        $scope.invalidemail = flag;

                                    });}
                           }
                         })

That is my directive as you can see I tried using flags it didn't work I tried changing the flag to booleans still not working I will also show my HTML. I am not sure if var emailInput = email.val() making problems to me because I am not using ng-model.

<form action="">
    <input type="text" name="emailField" ng-model="emailInput" register-user>
    <input type="button" name="" value="check" ng-disabled= invalidemail>
</form>

That is my HTML. Note I am not checking if email is valid in this task. I am just checking if the email already exist in my array or not.

4

1 回答 1

1

的值flag被设置为"true"or的字符串,"false"而不是 or 的布尔truefalse

// not "false"
var flag = false;
// subsequently set it to true not "true"

您的表单模板ng-disabled与绑定值之间有一个空格。

<input type="button" name="emailButton" value="check" ng-disabled="invalidemail" />

您还可以更简洁地编写此代码Array.some(),以查看数组是否包含您的值。

const emailInput = element.val();
$scope.invalidemail = !$scope.registeredUsers.some(element => emailInput === element.email);
于 2020-09-14T23:30:48.847 回答