Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below:

<textarea rows="3" maxlength="144" ng-maxlength="144" type="text"
          name="testPost" id="testPost_{{item.id}}"
          ng-init="focusText('testPost', item.id)"
          ng-model="item.testPost">
</textarea>

Accompanied by the following function:

$scope.focusText = function (columnSelected, id){
    if(columnSelected == "testPost"){
        var textId = "testPost_" + id;
        document.getElementById(textId).focus();
        document.getElementById(textId).setSelectionRange(0,0);
    } 
}

The issue I'm facing is that document.getElementById(textId) is showing up as null since the function is executed before the textarea is fully loaded. How can I ensure that the function runs only after the textarea has been completely loaded?

Answer №1

One issue that arises is when document.getElementById(textId) returns as null

To solve this problem, a custom directive can be created:

app.directive("myInit", function() {
   return {
       link: postLink
   };
   function postLink(scope, element, attrs)
       scope.$eval(attrs.myInit, {$element: element})
   }
})

Then pass the local variable $element to the function:

<textarea rows="3" maxlength="144" ng-maxlength="144" type="text"
          name="testPost" id="testPost_{{item.id}}"
          my-init="focusText('testPost', item.id, $element)"
          ng-model="item.testPost">
</textarea>

Utilize the $element parameter within the focusText function:

$scope.focusText = function (columnSelected, id, $element){
    if(columnSelected == "testPost"){
        $element[0].focus();
        $element[0].setSelectionRange(0,0);
    } 
}

This approach eliminates the need for using document.getElementById and eliminates the associated error.

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

Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context. I discovered some issues in the A ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

How can I display and utilize the selected value from a Rails select form before submitting it?

Currently, I am in the process of developing a multi-step form for placing orders. This form includes two dropdown selectors - one for shipping countries and another for shipping services. Once a country is selected, all available shipping services for tha ...

Tips for modifying the color or personalizing the header arrow for the expandableRow within Mui Datatable

My MUI data table has the expandable rows option, along with an ExpandAll button in the header row. The arrow displayed in the title row is confusing for users as it's similar to the arrows in all other rows. I want to change the color of the header a ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

Preventing the (click) function from being activated during dragging in Angular 10

My div contains an openlayers map setup as shown below: <div id="map" (click)="getInfo($event)" class="map"></div> Whenever I drag my mouse to move around the map, the getInfo function is triggered. Is there a way to make it trigger only when ...

Exploring the OAuth 2.0 integration with OpenID Connect, Loopback, and Keycloak

I'm having trouble establishing a connection to Keycloak from Loopback. I've been experimenting with the keycloak-connect library available at: https://github.com/keycloak/keycloak-nodejs-connect This snippet shows my current implementation in ...

The visibility of JavaScript script to Tomcat is obscured

Working on a web project using servlets and JSP in IntelliJ. One of the JSP files manages graphics and user forms with graphics.js handling graphics and form validation done by validator.js. The issue I'm facing is that while Tomcat can locate graphi ...

Notification not appearing in PHP

When working with a specific php file, I am encountering an issue where the alert box I have placed before the header is being ignored and the header is executed directly. Can anyone assist me in resolving this issue? Any help would be greatly appreciate ...

Motion of the atoms

I recently came across an interesting effect on the IconArchive website, but I am unsure how to implement it. If anyone could help me understand the concept with a small example, that would be greatly appreciated. You can see the effect in action by visi ...

Utilizing ng-model to control the visibility of a label or anchor tag

Here is the code snippet I am working with: <div class="tabs DeliveryRightDiv"> <label class="selected"><a>One</a></label> <label> <a>Two</a> </label> <label> ...

Cloud Firestore trigger fails to activate Cloud function

I am facing an issue with triggering a Cloud Function using the Cloud Firestore trigger. The function is supposed to perform a full export of my sub collection 'reviews' every time a new document is added to it. Despite deploying the function suc ...

Angular: Intercept Drag and Drop Actions

I am utilizing angular-ui to create a sortable list using "drag and drop" functionality, and it is functioning perfectly. Here is an example of how it works: index.html <ul ui-sortable ng-model="list"> <li ng-repeat="item in list" class="it ...

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

Negative vibes with for/in loop

My script is short and simple: hideElements = arguments.shift().split(','); for (iterator in hideElements) { console.log('--> hiding ' + hideElements[iterator]); lg_transitions({kind:"slide-up"}, {target: hideElements[iterat ...

Using a template literal as a prop is causing rendering issues

I have a functional component const CustomParagraph = forwardRef((ref: any) => { return ( <div> <p dangerouslySetInnerHTML={{ __html: props.text }}></p> </div> ); }); Whenever I use this component, I am unable ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

"Clicking on the dropdown menu will consistently result in it collapsing

When it comes to a DropDown menu, the typical expectation is that when an option is selected, the menu will collapse. However, in my situation, I do not want the dropdown menu to collapse if the user is attempting to log in and clicks on the Username and P ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

The fuse-sidebar elements are not being properly highlighted by Introjs

I have recently developed an angular project that utilizes the fuse-sidebar component. Additionally, I am incorporating introjs into the project. While introjs is functioning properly, it does not highlight elements contained within the fuse-sidebar. The ...