AngularJS Components: Opposite of "callback" binding?

Viewed 72

Sometimes an AngularJS custom component benefits from having a method to trigger a particular behavior. A generic example might be to trigger a reset of the component to an initial state. But it doesn't seem like AngularJS has a clean way to implement this functionality. The approaches I can think of all seem less than ideal.

1. Add a method to the DOM element itself (not the component) and call it directly in the parent

In the component

$ctrl.$postLink = function () {
    $element[0].reset = $ctrl.doReset;

In the parent

$element.find("my-component")[0].reset();

2. Use a one-way binding and "fake" a change

In the component

bindings: {
    tiggerReset: "<"

and

$ctrl.$onChanges = function (changes) {
    if (changes.triggerReset && ! changes.triggerReset.isFirstChange())
        $ctrl.doReset();

In the parent

<my-component trigger-reset="$ctrl.triggerComponentReset" />

and

$ctrl.triggerComponentReset = new String("true");

(note that a new string must be constructed so that AngularJS thinks that the binding has changed.)

3. Access the controller directly from the parent

In the parent

$element.find("my-component").controller("myComponent").doReset();

It seems like there must be a more idiomatic and/or elegant approach that I'm missing.

0 Answers
Related