I am relatively new to AngularJS and am coming from a PHP background.
One of the new features for PHP7 was the Null coalescing operator.
In short, it checks if a value is set and if it is then it shows one value, otherwise it shows another.
I wanted to do a similar thing in AngularJS since I was retrieving data from a database using an inner join and so some values are returned as null
. As a result of this, I needed a fallback.
Here is the filter code:
app.filter("or", function() {
return function(input, replace, whatIsNull) {
//set the defaults
whatIsNull = typeof whatIsNull == "undefined" ? ["", 0, 0.0, "0", undefined, null, false, []] : whatIsNull;
replace = typeof replace == "undefined" ? undefined : replace;
return whatIsNull.indexOf(input) > -1 ? replace : input;
}
});
Then I use it in the following:
<p>{{ myStr | or: "N/A" }}</p>
<!-- or as... -->
<p>{{ myStr | or: "N/A": [undefined, false] }}</p>
The first example will use the default values of PHP's empty function.
The second example uses a custom array of values that will result in the fallback from or.
Is there a more effective way of setting default values of functions?
The way I would normally do this would be to set it inline in the function declaration (Something that was added in ECMAScript 2015).
{{}}
things? 'Cause{{ myStr | or: "N/A": (v) => !!v }}
could be cool. \$\endgroup\$