Tips for shifting focus to a new field immediately upon its appearance in Angular 1.4

In this particular scenario, a new field is introduced by including a blank row to $scope when the last field loses focus, provided it is not empty. However, there seems to be an issue where the newly added field is not included in the DOM in time to receive focus.

Is there a method to identify when Angular has completed appending the new field to the DOM so that focus can be directed towards it?

Please refrain from utilizing "timer" solutions; as the duration for DOM changes varies, I require this switch of focus to occur swiftly. There must be a more efficient approach!

JSFiddle

HTML

<div ng-app='a' ng-controller='b'>
    <input type="text" ng-repeat="row in rows" ng-model="row.word" ng-model-options="{'updateOn': 'blur'}">
</div>

JS

angular.module('a', []).controller('b', function ($scope) {
    $scope.rows = [{'word': ''}];

    $scope.$watch('rows', function (n, o) {
        var last = $scope.rows[$scope.rows.length - 1];

        last.word && $scope.rows.push({'word': ''});        
    }, true);
});

Answer №1

To address this issue related to View-concern, it is recommended to utilize directives.

An effective approach is to develop a directive that seizes the focus when it is linked:

.directive("focus", function(){
  return {

    link: function(scope, element){
      element[0].focus();
    }

  }
});

Subsequently, you can apply it in the following manner:

<input type="text" 
       ng-repeat="row in rows" 
       ng-model="row.word"
       focus>

Demo

Answer №2

Utilize $timeout without setting a specific duration in milliseconds. By default, it will execute after the DOM has loaded, as explained in response to this query.

angular.module('a', []).controller('b', function($scope, $timeout) {
  $scope.rows = [{
    'word': ''
  }];

  $scope.addRow = function() {
    $scope.rows.push({
      'word': ''
    });
    $timeout(function() {
      //DOM has completed rendering
      var inputs = document.querySelectorAll('input[type="text"]');
      inputs[inputs.length - 1].focus();
    });
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='a' ng-controller='b'>
  <div ng-repeat="row in rows">
    <input type="text" ng-model="row.word" ng-model-options="{'updateOn': 'blur'}"><br>
  </div>
  <input type="button" ng-click="addRow()" value="Add Row">
</div>

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

Is it possible for Yarn to fail to include both ESM and CJS versions of a package during publishing or adding?

Our application is equipped with Parcel and utilizes a UI library consisting of react components. This UI library is built with Rollup and is privately published on NPM. I've been attempting to transition our application to Parcel 2, but I'm fac ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

Repetitive process in JavaScript

I am struggling to write certain attributes to HTML using a recursive loop and I can't seem to get the code to work properly. The JSON data consists of an array of hashes with the following attributes: serno (serial number), parent_serno (serial numb ...

Leveraging Firebase Dynamic Links through JavaScript

Currently exploring options for implementing Dynamic Links. Firebase Dynamic Links seem promising, but the lack of support for Cordova/ ionic apps is concerning. Is there any plan to add this in the future? Are there any other alternatives that you would ...

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

How to use jQuery to update the href attribute of a parent link

Can someone help me figure out why I am having trouble changing the 'href' of the parent link to a header logo? Thank you in advance! Here is the HTML code snippet: <a href="https://URL.IWANTO.CHANGE"> <img id="partner_logo" src="/ ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...

Exploring the Angular Scope Within an HTML Document

While attempting to access my angular scope, I keep encountering the common issue of "$digest already in progress". I am unable to use $timeout as a solution because I need to perform this task within the script section of my html due to Kendo UI Grid requ ...

Setting a header with the Axios module and Vue.js in Nuxt: A step-by-step guide

I've been attempting to set up an "Accept-Language" header for my SPA using vue.js (along with nuxt). Here's the approach I took, but unfortunately, it's not functioning properly. I specified that I am utilizing the axios module for nuxt. ...

A JavaScript function in moment that converts a given number of seconds into a readable format such as "5 hours and 10 minutes"

Is there a built-in function in moment.js that can convert seconds into a human-readable duration? For example, given 3720 seconds, it would display 1 Hour and 2 minutes. I am aware this could be achieved with basic math operations like using % and /, but ...

Exploring a json array of objects with the help of jQuery

Even though some may find this basic, I am struggling to loop through a json object. I have tried various examples with no luck and even consulted the jQuery documentation but couldn't find a solution for my specific json structure. In my example, wh ...

I encountered an issue with Material UI tabs showing the error message: "Failed prop type: The prop `children` is not supported. Please remove it."

Recently, I started using Material UI tabs in my project for the first time. Everything seems to be working fine except for one issue that keeps showing up in the console while running the project: Failed prop type: The prop `children` is not supported. Pl ...

How can Puppeteer be configured to replicate the exact layout of an HTML document for PDF generation, including page breaks?

Currently, I am utilizing Puppeteer in order to create PDF files by using static HTML as the primary source: const page = await browser.newPage(); await page.setContent(html); //the HTML content is retrieved from the file system const pdf = await page.pdf ...

Creating gifs from an array of base64 strings with gifshot doesn't seem to function properly on Firefox browsers

I am currently attempting to utilize the gifshot library from here in order to generate gifs from a canvas. The process involves capturing the canvas using canvas.toDataURL(), then storing these results in an array, which is subsequently passed to the gifs ...

Removing the outer array of objects can be achieved by using a variety of

My goal was to eliminate the outer array of objects. I attempted to achieve this by using the code below: export class AppComponent implements OnInit { name = 'Angular'; EmployeeData=[ {"name": [{ "grade": &quo ...

What is the process for converting a string into a JSON object?

There is a string that looks like this: //string " { "1" => "one stuff\n print 'hi'.. ", "2" => "two stuff\n print 'by' "} " What steps should be taken to convert it into a JSON object in order to access its ...

What is the best way to manage iPhone popups without requiring any action from the user?

I'm currently developing a tool that aims to streamline the automation of browser-based products. One specific scenario I need to address is how to manage popups that appear either within an application or in Safari. Ideally, I'd like to create a ...

Renaming form elements using JQuery's .load method

This is a page named A.html <form name=form> <input type=text id = txtA> </form> When I use jQuery to load it into B.html, it loads multiple times. <form name=form> <input type=text id = txtA> </form> <form name=f ...

What could be the reason for the absence of the image prop in JSON data within [gatsby-plugin-image

Purpose: Retrieve and display JSON data containing image paths, titles, descriptions, and alt attributes using GraphQL. While title, description, and alt attributes are successfully rendered, there is an issue with displaying images. The console log indica ...