1
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ This is pretty cool, I've not used either technology in a while so I can't improve on this. However can you make lambda functions in angular {{}} things? 'Cause {{ myStr | or: "N/A": (v) => !!v }} could be cool. \$\endgroup\$ – Peilonrayz Nov 23 '17 at 15:33
  • \$\begingroup\$ @Peilonrayz I'm not hugely familiar with lambdas. I know that arrow functions were added in ECMAScript 2015. How would that work? \$\endgroup\$ – JustCarty Nov 23 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.