How to select the content of an input in ng-focus?

2

In an input I have a method that selects the contents of the field when clicking on it.

<input ng-click="selecionaTudo($event)">

The function is this:

$scope.selecionaTudo= function($event){
       $event.target.select();
}

It works perfectly, but I want to use it in ng-focus, and in that event it does not work:

<input ng-focus="selecionaTudo($event)">

Can anyone tell me why? What alternatives do I have?

Example of how you would like it to look:

    
asked by anonymous 23.03.2016 / 13:08

3 answers

0

I used ng-click and ng-focus and it worked, in the 2 cases called the function, but to get the value of the field I used

  

$ event.target.value

Only one question: why pick focus? when the input is empty will always come empty, to pick up after the user finishes filling has to be ng-blur. But I do not know what you're doing, if you focus on the input, just change the .select () to .value and that's fine.

    
23.03.2016 / 14:04
0

The correct thing is to use the mouseenter event.

  

This event is triggered when the mouse cursor is placed on an element, if the user moves the mouse over that element, the event is not fired again.

See working

var app = angular.module('appSelecionaTexto',[]);
app.controller('SelecionaTextoController', function($scope){
  $scope.selecionaTudo= function($event){
    $event.target.select();
  }
});
input {
  width: 250px;
}
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script><divng-app="appSelecionaTexto">
  <div ng-controller="SelecionaTextoController">
    <input value="Texto a ser selecionado :) :D :P" ng-mouseenter="selecionaTudo($event)">
  </div>
</div>
    
27.10.2017 / 08:04
-2
app.directive('selectOnFocus', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('focus', function () {
                if (!$window.getSelection().toString()) {
                    // Required for mobile Safari
                    this.setSelectionRange(0, this.value.length)
                }
            });
        }
    };
});

<input select-on-focus>
    
31.05.2017 / 13:51