Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngClick but prevent any active inputs from losing focus

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>
like image 737
Sean256 Avatar asked Jan 28 '16 20:01

Sean256


1 Answers

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.

like image 192
Daniel Beck Avatar answered Nov 19 '22 10:11

Daniel Beck