Robert Johnson
Robert Johnson

Reputation: 662

How to allow for "named arguments" in a custom AngularJS filter?

I am creating a custom Angular filter and I would like to provide the closest thing possbile to "named arguments" (a la Python), primarily for the purpose of boolean options so as to avoid passing an unreadable sequence of true/false values.

If I only had to consider calling from "raw" javascript I would accept some kind of options object:

myFilter(someValue, {
    foo: false,
    bar: true
});

However I would like this to be easy to use from within Angular expressions too. Is it possible to pass objects like this within an expression? If not, or perhaps if it is simply too awkard, what would be a more idiomatic approach?

Upvotes: 1

Views: 250

Answers (1)

devqon
devqon

Reputation: 13997

Yeah why not, you can use named arguments easily in a filter:

app.filter("myFilter", function() {
    return function(item, filterConfig) {

        if (filterConfig.foo) {
            // return something
        } else {
            // return something else
        }
    }
});

And usage:

{{ myValue | myFilter:{foo:false} }}

See this jsfiddle

Upvotes: 2

Related Questions