最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - ngClick but prevent any active inputs from losing focus - Stack Overflow

matteradmin3PV0评论

In my Angular view I have an input field and some clickable goodies using ng-click.

Is there an angular way or simple vanilla js way to prevent the input field from LOSING focus (if it was in focus) when one of these ng-clicks is clicked?

<input type="text" class="form-control" ng-model="foo">

<button ng-click="someThing()">click me</button>

In my Angular view I have an input field and some clickable goodies using ng-click.

Is there an angular way or simple vanilla js way to prevent the input field from LOSING focus (if it was in focus) when one of these ng-clicks is clicked?

<input type="text" class="form-control" ng-model="foo">

<button ng-click="someThing()">click me</button>
Share edited Jun 10, 2016 at 22:29 spazm 4,8091 gold badge35 silver badges34 bronze badges asked Jan 28, 2016 at 20:58 Sean256Sean256 3,1094 gold badges33 silver badges42 bronze badges 2
  • call ` $(pattern).focus() ` in the method used in your ng-click ;) for example in ` someThing() ` – anotherdev Commented Jan 28, 2016 at 21:02
  • Why do you want that it should not loose focus? – P. Jairaj Commented Jan 28, 2016 at 21:02
Add a ment  | 

2 Answers 2

Reset to default 12

Not with ng-click, because by the time that fires, the clicked element has already taken the focus from the input.

But ng-mousedown should work, if you $event.preventDefault() in your event handler. Here's a demonstration in vanilla JS; the same should work in Angular:

    var preventBlur = function(event) {
      console.log("click");
      event.preventDefault();
    }
    <input type='text' onblur="alert('blurred')">
    <button onmousedown="preventBlur(event)">Click</button>
    

If you click the button while the input field is in focus, the mousedown will trigger without causing the input field to lose focus.

The easiest solution is to use javascript

$scope.someThing = function () {
    //implementation...
    document.getElementById("yourInputIt").focus();
};
Post a comment

comment list (0)

  1. No comments so far