AngularJS Components: Opposite the "callback" binding?

Sometimes a custom AngularJS component benefits from the fact that it has a way to initiate certain behavior. A common example might be to reset a component to its original state. But it doesn't look like AngularJS has a clean way to implement this functionality. The approaches I can imagine seem less ideal.

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

In component

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

      

In the parent

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

      

2. Use one-way binding and "fake" shift

In 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 the newline must be structured so that AngularJS thinks the binding has changed.)

3. Access to the controller directly from the parent

In the parent

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

      

There seems to be a more idiomatic and / or elegant approach that I am missing.

+3


source to share





All Articles