0

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....

1 Answer 1

1

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(' ');
        }
    };
});
Sign up to request clarification or add additional context in comments.

2 Comments

Any idea about the reason why my filter was taking as input s0 = 'string0string1' and s1 = 'string1', starting from a unique concatenated string?
The first argument of a filter is always its input: the value that is before the | symbol. The following arguments are what is passed after the name of the filter, separated by :.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.