ng-disable not working when I am trying to use custom directive

86 Views Asked by At

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.

1

There are 1 best solutions below

3
On

The value of flag is being set to a string of "true" or "false" instead of boolean values of true or false.

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

Your form template has a space between ng-disabled and the bound value.

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

You can also write this more concisely using Array.some() to see if the array contains your value.

const emailInput = element.val();
$scope.invalidemail = !$scope.registeredUsers.some(element => emailInput === element.email);