Select text in item

I have an input element and it contains the text inside it using ng-model, then I try to select all the text by creating my own detective:

 .directive('selectText', function() { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { elem.bind('focus', function() { $(elem).select(); }); scope.$watch("edit",function(newValue,oldValue) { $(elem).select(); }); } }; }) 

This works well, but I do not want the text to be also selected when the user foucusout from the control and focusin again. It should just select the text only once (not in the second focus). Also, how can I remove focus from an element when all the text is selected?

+5
source share
2 answers

You can create a variable that will contain a boolean if the item is selected and select the item only if it is not already selected. Like this:

 .directive('selectText', function() { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { var selected = false; elem.bind('focus', function() { if (!selected) { $(elem).select(); selected = true; } }); scope.$watch("edit",function(newValue,oldValue) { $(elem).select(); }); } }; }) 
0
source

 function Ctrl3($scope) { $scope.title = 'My relevant title'; } angular.module('scopePropertiesModule', []) .directive('selectText', function() { return { require: 'ngModel', link: function(scope, elem, attrs, ctrl) { var counter = 0; elem.bind('focus', function() { console.log(counter) if (counter < 1) { $(elem).select(); /*setTimeout(function() { $(elem).blur(); }, 1000);*/ counter++; } }); scope.$watch("edit", function(newValue, oldValue) { $(elem).select(); }); } }; }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script> <div ng-app="scopePropertiesModule"> <div ng-controller="Ctrl3"> <input select-text ng-model="title"> </div> </div> 

Check this.

0
source

Source: https://habr.com/ru/post/1270421/


All Articles