Search code examples
javascriptangularjsangularjs-components

AngularJS component require: componentOne OR componentTwo


I want to pass some functions in my template to the current active parent component:

<div ng-click="thisComponent.parentComponent.fn()"></div>

The parent component depends on the page and configuration you are viewing, so I tried:

app.component('thisComponent', {
    controllerAs: 'thisComponent'
    require: {
        parentComponent : '?^componentOne' || '?^componentTwo'
    },
    controller: function() {
        this.$onInit = () => {
            // Returns null when the parent is componentTwo
            console.log(this.parentComponent);
        }
    }
});

The code doesn't break, it actually works when componentOne is the parent, but when it's not, this.parentComponent evaluates to null, without trying componentTwo.


Update 2018-02-28

Got it working with @Korte's answer (see below), but still wondering why the code above does not work. How come it does not evaluate the next option when the first returns null? Anyone care to explain?


Solution

  • You could require both parent components, then check which one is defined.

    e.g.

    app.component('thisComponent', {
        controllerAs: 'thisComponent',
        require: {
            firstParent : '?^componentOne',
            secondParent: '?^componentTwo'
        },
        controller: function() {
            this.$onInit = () => {
                this.parentComponent = this.firstParent || this.secondParent;
                console.log(this.parentComponent);
            }
        }
    });
    

    Here's a working fiddle.