Exploring the wonders of AngularJS with ngShow and focus

Is there a way to display a textarea in Angular based on the value of a preview variable? Once the value of preview is set to true, I want to automatically focus on the textarea.

Controller Logic

.controller('MyCtrl', ['$scope', function ($scope) {
    $scope.preview = false;
    $scope.showPreview = function() {
        $scope.preview = true;
    }
}])

Directive Logic

.directive('previewFocus', function() {
    return function(scope, element, attrs) {
       scope.$watch('preview', 
         function (newValue) { 
            newValue && element[0].focus();
         },true);
      };    
});

Next, there is a div that triggers the showPreview() method when clicked:

<div ng-click="showPreview()">Add Post</div>

Followed by a textarea with the preview-focus directive:

<textarea class="previewInput" preview-focus></textarea>

I have checked the code and everything seems to be running correctly, including the callback on the scope.$watch function. However, the textarea does not receive focus. The focus works fine when the ngShow directive is not used. Here are two JSFiddle examples illustrating both scenarios.

Focus does not work: JSFiddle with ngShow

Focus works fine: JSFiddle without ngShow

Is there a proper way to utilize ngShow and still focus on the displayed element simultaneously?

Answer №1

To achieve this, utilize the $timeout feature:

.directive('previewFocus', function($timeout) {
    return function(scope, element, attrs) {
       scope.$watch('preview', 
         function (newValue) { 
            console.log('preview has been updated!')
            $timeout(function() {
                newValue && element[0].focus();
            }, 0, false);
         });
      };    
});

The reason why this solution works is because $timeout delays the execution of the code inside it until after the rendering phase (after ng-show's $watch has been executed, when the textarea becomes visible)

On a side note: I have removed the extra argument from your $watch - having a deep watch is unnecessary for monitoring changes in a primitive variable.

Check out the Demo Fiddle here

Answer №2

Here's a simple workaround that gets the job done (JSFiddle):

function (value) { 
  window.setTimeout(function() {
    value && element[0].focus();
  }, 0);
},true);

For better practice, it's recommended to use Angular's $timeout instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The title tag's ng-bind should be placed outside of the element

When using ng-bind for the title tag inside the header, it seems to produce unexpected behavior. Here is an example of the code: <title page-title ng-bind="page_title"></title> and this is the resulting output: My Page Sucks <titl ...

The specified container is not a valid DOM element

Recently, I decided to implement Redux into my React application. However, as I began setting everything up within my index.js file, I encountered an error message: https://i.sstatic.net/4kL2T.png. After some research, I learned that this error is related ...

Check Boxes in HTML Form Elements

My PHP code generates an HTML form that allows users to update information in a table when they press the update button. However, I am encountering an issue with the delete option. Whenever I click the update button, the information gets updated successful ...

Utilizing shared functions defined across different controllers

Can I utilize the code within these controllers for other purposes? .controller('GenericController', ['$scope', '$controller', '$rootScope', '$dialogs', '$state', '$http', '$modal& ...

Could it be a typical issue that arises when utilizing select elements and including both the $options.placeholder and id attributes for custom validation, resulting in $invalid always being

This is a sample snippet from my HTML document: <form name="form" ng-submit="submit()" novalidate> <label> Gender</label> <select name="gender" ng-model="gender" placeholder="Date of Birth - Gender" ng-required="true"> ...

A guide on monitoring data in a two-dimensional array with AngularJS

As a newcomer to AngularJS, I recently started working on developing a form and have come across a particular requirement. The form should include 4 textboxes by default, but users should also have the option to add another set of 4 textboxes if needed. Ho ...

Scroll issue causing CSS not to be applied to a field within a div

Can someone help me with this issue I'm facing in my jsfiddle example? Here is the link: http://jsfiddle.net/AnnaMiroshnichenko/xjyb8/1/. The problem is, when I scroll the div, the field underneath the scroll does not appear to be applying CSS rules p ...

Displaying Dynamic Content in React Table Rows Based on Conditions

I'm populating a table with multiple rows using props. If a returned prop is an empty string "" , I want to exclude that row from rendering. <Table.Body> <Table.Row> <Table.Cell>Producer</Table.Cell> ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

Remove browser data in PhoneGap / Prevent PhoneGap from utilizing cookies

Currently, I am in the process of creating a login system for my mobile application. After logging in to my server, it sends back a JSESSIONID that I can utilize for further authentication. The issue I am encountering is that PhoneGap is automatically st ...

The Autofocus feature in HTML5 is malfunctioning in Internet Explorer 9

I am currently working on a project for IE9, and I am having trouble with the HTML5 autofocus keyword not functioning as expected. Specifically, the autofocus feature that puts the cursor in the specified input field is not working in IE9 (and I am forced ...

Mobile Bootstrap 4 experiencing logo display issue

My .navbar logo disappears when the screen width is under 768px. I've seen a similar post about this issue, but they had set a very high height. I haven't specified a height for my navbar or navbar brand. Any help would be greatly appreciated, th ...

Could not successfully enroll a ServiceWorker in Next.js

After creating a sample Next.js project using the command: npx create-next-app, I then installed next-pwa. Following that, I configured next.config, created manifest.json, and _document.js in the project directory. This is my next.config.js: const withPWA ...

What is the best way to adjust the vertical distance between a Material UI FormLabel and Slider element?

I am currently developing a map that includes an image overlay with adjustable opacity. Below is the code for this component: import React from 'react' import PropTypes from 'prop-types' import { MapWithGroundOverlay } from './Map ...

Executing various SQL commands to extract information from a MySql database using PHP

My task involves retrieving and displaying data from multiple tables in an HTML table format. Currently, I am faced with the challenge of executing two separate SQL queries to fetch all the necessary information. The limitation I am encountering is that ...

Issue with querying and ordering products in Django using Python when passing values through the GET request

I have been working on a project where I need to filter products and sort them by price in ascending and descending order. Here is the code snippet from my view: def is_valid_queryparam(param): return param != '' and param is not None def f ...

Is autocomplete="off" disregarded by IE 11?

Currently, I am working on an established ASP.NET/C# application that has been in existence for about three years. Recently, for various reasons, I decided to start using the beta version of Internet Explorer 11. However, upon launching the application in ...

Choose the initial p tag that includes an image, based on the content of another div

I am trying to figure out how to manipulate the code on my website: <div class="the-post-thumbnail"> <img src="" alt="" width="" height="" /> </div> <div class="post-body"> <p><img src="" alt="" width="" height="" ...

Is the code for uploading multiple images not functioning as expected?

My Photo Table is Column Name Data Type Constraint PhotoID Int Primary key,auto increment PhotoName Varchar(100) ExtName Varchar(100) PhotoType Varchar(100) PhotoSize Int TempleID Int Foreign key with templ ...

Implementing conditional logic in AngularJS using if/else statements

<div class="company_name" ng-controller="CompanyName"> <h1 class="left"> {{data.company_name}} </h1> </div> Is there a way to display a placeholder "Company name" if data.company_name has not been set using an input field in ...