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

AngularJS: The total is the accumulation of all corresponding objects

In my project, I’m dealing with an array of Requests that each contain an array of tasks. The goal is to update the duration field of each Request based on the sum of durations of its associated tasks and ensure that these changes are responsive to any u ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

JavaScript sorting through nested functions

Having an issue with running a function inside another function for my Bingo game script. The checkBingo() function is defined outside of a .click() function, but I'm facing problems. Ajax is involved, so that might be contributing to the issue. Here& ...

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...

Fetching arrays in Javascript

I am utilizing the Dragsort plugin and aiming to tag IDs in an array for printing. Here is my HTML code: <ul id="list1"> <li class="ss"><div>1</div></li> <li><div>2</div></li> <li>&l ...

Tips for creating boxes with clearly defined edges on shared sides using three.js

When I draw boxes with common sides, I don't see the common edges, but rather perceive them as a single object even though there are 25 boxes: https://i.sstatic.net/gE8FW.png function box(scene, x, y, z, size) { const points = []; ...

Utilizing Angular.js to Retrieve JSON Data Using the HTTP Response Interceptor

When it comes to handling HTTP requests and responses, I have a setup that involves sending requests with a 404 status code while also intercepting them in an Angular Service. res.status(404).send({message: 'O Captain! My Captain!'}); In my Ang ...

Monitor the output of a spawned process that is currently in a state of awaiting user input

In my Swift program, I am logging information to the stdout while waiting for a termination signal of \n. The input is requested immediately upon starting and the info is logged 1~2 seconds later: fetchAndLogDataInBackground(); // will print some dat ...

the proper injection of angular-resource is not being achieved in AMD

I am struggling to get angular.resource.js to work with angular.js. It seems like Angular is loaded but angular.resource is not being recognized. index.html <!doctype html> <html> <head> <script> var require ...

Is there a way to collect multiple optional phone numbers dynamically using DOM manipulation?

I have a piece of code here where I am looking to dynamically add additional phone numbers as an optional field. Can anyone help me figure out how to achieve this? <div class="col-12 row border my-2 py-2"> <di ...

Tips on how to navigate to the end of a div that has been created through ng-repeat in Angular JS with the

Here is the template code I am working with: <div class="chatbox" id="mailBody" > <div class="panel-body" ng-repeat="mail in mails"> <div class="m-b-none" ng-if="mail.inboxMessageType == 1"> <a href class="pull-left ...

The donut chart in Chart.js is stuck in grayscale without any colorization

I just set up a donut chart using chart.js with the following code: <div id="chartContainer" style="height: 320px; width: 320px"> <canvas id="hoursFEContainer"></canvas> </div> To use chart.js, I downlo ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

Modifying the background color and linking it to a different class in Android Studio: A step-by-step guide

Recently, I developed a settings feature for my project that allows users to change the background color. However, I noticed that when I return to the home page, the settings are not saving or syncing properly. Any suggestions on how I can sync this info ...

Tabulating with jQuery Arrays

I am facing an issue when trying to perform calculations with certain numbers. Here is the specific code snippet causing trouble: for (var key in week_total) { $("." + key).html(week_total[key]); } After running this code, I keep getting a value of N ...

Using {angular} import from 'angular' is causing a malfunction in AngularJS version 1.5

React - 17.0 TypeScript - 4.1.2 Babel - 7.13.14 tsconfig.json { "compilerOptions": { "target": "es6", "module": "esnext", "moduleResolution": "node", "jsx": ...

Utilizing Browserify routes and configuring Webstorm

When building my project using gulp and browserify, I made use of path resolution for easier navigation. By following this guide, I configured browserify as shown below: var b = browserify('./app', {paths: ['./node_modules','./src ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

Using JS to switch between text and state in ToneJS

I am facing an issue with the text not displaying in the "play-stop-toggle" element, despite my limited experience with JS. My desired outcome includes: [SOLVED] The text in <div id="play-stop-toggle" onclick="togglePlay()">Play ...