How to set focus on textarea in angular ui modal every time you open modal?

I have a text box inside angular ui modal, and you need to set focus on it when the modal image becomes visible, it cannot be in the document loading, because it only works for the first time, opening the modal.

Modals have animation to open, I need to set focus after the animation is complete.

Based on the other issues studied here, I created the following directive:

.directive('focusMe', ['$timeout', focusMe]); function focusMe($timeout) { return function (scope, element) { scope.$watch(function () { $timeout(function () { element[0].focus(); }); }); }; }; 

But this directive always checks the focus of the text area. Since my modal has a different input field, when I click on it, the focus again changes to a text field that uses the directive. How to set focus only for the first time so that the modality becomes visible?

UPDATE

Additional Information: The problem of always keeping the focus on textarea has been resolved, in some way.

But since my modal has fading in the animation, in IE, the focus is displayed above the text box, on the outside, I need to use a timeout for IE to properly set the focus. This is not very nice. Any better way?

+6
source share
3 answers

I am using the next version of the focus-me directive with the angular ui-modal directive.

 angular.directive('focusMe', function($timeout) { return { scope: { trigger: '@focusMe' }, link: function(scope, element) { scope.$watch('trigger', function(value) { if(value === "true") { $timeout(function() { element[0].focus(); }); } }); } }; }); 

An example of using the focus-me directive in modal form:

 <div class="modal-header"> some header </div> <div class="modal-body"> <form name="someForm" method="post" novalidate=""> <fieldset> <textarea name="answerField" placeholder="Enter text..." focus-me="true" ng-model="model.text"></textarea> </fieldset> </form> </div> <div class="modal-footer"> some footer </div> 
+8
source

Later for an answer, but when using multiple directives, it is best to use attr, as u may run into the problem of a multiple directive creating a selection area

 ControlDirectives.directive('focusMe', function ($timeout) { return { link: function (scope, element, attr) { attr.$observe('focusMe', function (value) { if (value === "true") { $timeout(function () { element[0].focus(); }); } }); } }; }); <input name="baseCode" focus-me="true" type="text"/> 
+2
source

You will need to test this, I'm not sure if this will work, but you could embed the script in your modal HTML template with a simple one:

 ... <script>document.getElementById('fieldId').focus();</script> ... 
+1
source

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


All Articles