Explosion Pills
Explosion Pills

Reputation: 191729

Event on one element to trigger event on another

I'll use a specific example but this could apply to any event on one element triggering any event on another. Suppose that we want to focus an <input> when we click a <span>. We can do this using a directive like:

<div ng-controller="Ctrl">
    <span ng-focus-other>focus</span><input>
<div>

app.directive("ngFocusOther", function () {
    return function (scope, element) {
        element.bind("click", function () {
            this.nextSibling.focus();
        });
    };
});

However this does not seem very Angular. This would also not work were there any changes to the DOM (e.g. if <input> were moved before <span>). It would also be nice if the same code could work on multiple groups of <span>-<input> combinations perhaps each with a different DOM layout.

What is the Angular way of using one event to trigger another event on another element?

Upvotes: 0

Views: 142

Answers (1)

Fourth
Fourth

Reputation: 9351

Why not simply have clicking the span set a boolean called "inputFocused" to true and then let the input pay attention to that scope variable. I.e.

<span ng-click="inputFocused = true">FOCUS</span>
<input ng-focus="inputFocused" value="GIVE ME FOCUS">

Upvotes: 1

Related Questions