Chènevis
Chènevis

Reputation: 513

AngularJS concatenate two functions

I have two factories (because it is more readable) and one controller. I do not know if it is possible, but I want to sent the result of the two factories in one variable.

code

vm.result = [];
vm.validate = validate;
function validate(password1, password2) {
    vm.result = comparePasswordFactory.compare(password1, password2) + validNumberFactory.valid(password1);
    return vm.result;
}

compare returns:

return {
     color: 'green',
     text: 'Passwords match',
     validate1: 'true'
};

valid returns:

return {
    text: 'Number should be between 12 and 45',
    validate2: 'false'
};

I do not think what I wrote is correct. But, is this possible and/or is it a good option ?

Upvotes: 0

Views: 186

Answers (1)

pwolaq
pwolaq

Reputation: 6381

in order to validate using both functions you have to read and compare its validate1 / validate2 properties

var passwordOK = comparePasswordFactory.compare(password1, password2).validate1 === 'true';
var numberOK = validNumberFactory.valid(password1).validate2 === 'true';
vm.result = passwordOK && numberOK;

tip: better way would be to use boolean values instead of string, eg.

return {
    validate: false
}

pro way: consider using consistent api in your factories, then you could do something like:

var validators = [comparePasswordFactory, validNumberFactory];
var isValid = true;
for(var i=0;i<validators.length;i++){
    if(!validators[i].validate.call(this, password1, password2)){
        isValid = false;
        break;
    }
}
vm.result = isValid;

then you could easily add another validator (notice that all factories must implement validate method)

Upvotes: 1

Related Questions