Click button to focus input label

In my app, I have a comment list, while I click one of these comments, it means that I want to reply this comment. So I want to focus input label while I click the comments. But it doesn’t work.
In HTML:

    <button ng-click="Focus()">Focus</button>
    <input type="text" id="test_input" placeholder="white your comment"></input>

In js:

  $scope.Focus() {
    var oInput = document.getElementById("test_input");
    oInput.focus();
  }
1 Like

Did u find any solution?

You shouldn’t do any DOM operations within controllers. That’s what directives are for. And a directive might be a solution here.

Really, is that the only way.
Does it take a directive to do something that has existed in Javascript/HTML for over 20 years?
There must be a better way than having to write a custom directive to perform a native method surely please tell me there is.

By using a directive you are making sure that the code is modular and scalable. If you name your directive something like onClickFocusId and implement it as a custom click handler, you have just created a directive which can be used on pretty much any html element out there.

<button data-on-click-focus-id="id_of_your_focus_target" [...]>

Write once, run anywhere!

Isn’t that amazing? :wink:

I get it. But it is already written in Javascript… it is called the focus() method :slight_smile:
You can do this

<button onclick="document.getElementById('id_of_your_focus_target').focus()"/>

Or you can write a function if you want to hide the document.getElementById if desired.

1 Like

Yeah, there are many solutions to a problem :slight_smile:

But why re-invent the wheel when it is not needed.