floatingpurr
floatingpurr

Reputation: 8599

AngularJS filter multiple values if at least one of them is empty

I'm using a filter to evaluate a couple of strings. If both of them are defined, I want to display them

string0 string1

else, I want to display a message like this:

at least one of the strings is empty

Here there is my filter

.filter('getStrsOrNoData', function () {
    return function (s0, s1) {
        if (s0 && s1 ) {
            return s0 + ' ' + last;
        } else {
            return 'at least one of the strings is empty';
        }
    };
})

and here is how I declare it in HTML, passing in 2 arguments:

<p>{{string1 + string2 | getStrsOrNoData : string1 : string2 }}</p>

My problem is that when s0 && s1 is true, the displayed value is

string0string1 string0

I think the problem is string1 + string2 but I don't know how to state two vars on the left side of the pipe....

Upvotes: 0

Views: 80

Answers (1)

JB Nizet
JB Nizet

Reputation: 692281

I wouldn't do it like that. Instead, I would create a filter that takes an array of strings as input, and no other argument. The filter would join the strings in the array if they're all defined, or would display an error message if at least one is falsy

Usage example:

{{ [string1, string2] | joinOrError }}

Untested Code:

.filter('joinOrError', function() {
    return function(array) {
        if (array.some(function(string) {
            return !string
        })) {
            return 'at least one of the strings is empty';
        }
        else {
            return array.join(' ');
        }
    };
});

Upvotes: 1

Related Questions