How can I set focus to text fields within a custom directive that is utilized within the 'editableCellTemplate'?

When I have a custom directive in the editableCellTemplate, selecting the text in the cell or pressing "F2" brings up the custom directive, but the textfield inside it does not gain focus. How can I ensure that the textfield inside the custom directive gains focus?

For an example of this issue, observe the 'Gender' column in this fiddle. The sequence of 'TAB' and 'SHIFT + TAB' is not functioning correctly, resulting in inconsistencies in focusing on the text field under the 'Gender' column.

Answer №1

Here is a solution you can give a try:

function setElementFocus(id: string): any {
    var element = document.getElementById(id);
    setTimeout(function () {
        if(element) {
            element.focus();
            element.select();
        }
    }, 100);
}

Answer №2

By utilizing event handlers like focus and blur, I managed to resolve this issue.

To view the solution, please check here.

myApp.directive('customFocus', ['uiGridConstants', 'uiGridEditConstants',
  function(uiGridConstants, uiGridEditConstants) {
    return {
      require: ['?^uiGrid', '?^uiGridRenderContainer'],
      scope: true,
      restrict: 'E',
      template: '<div><div>Some text</div><input type="text"></div>',
      link: function($scope, element, attrs, controllers) {
        console.log(element);
        console.log(arguments);
        setTimeout(function() {
          angular.element($(element).children().children()[1])[0].focus();
          angular.element($(element).children().children()[1])[0].select();
        }, 10);

        var uiGridCtrl = controllers[0];
        var renderContainerCtrl = controllers[1];

        // Set focus at the beginning of edit
        $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function() {
          var thisEle = angular.element($(element).children().children()[1])[0];
          thisEle.focus();
          thisEle.select();
          thisEle.style.width = (thisEle.parentElement.offsetWidth - 1) + 'px';
          element.on('blur', function(evt) {
            console.log("blur - element");
            $scope.stopEdit(evt);
          });
        });


        $scope.stopEdit = function(evt) {
          $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
        };

        element.on('keydown', function(evt) {
          switch (evt.keyCode) {
            case uiGridConstants.keymap.ESC:
              evt.stopPropagation();
              $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
              break;
          }
          if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
            evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
            if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
              $scope.stopEdit(evt);
            }
          } else {
            switch (evt.keyCode) {
              case uiGridConstants.keymap.ENTER: 
              case uiGridConstants.keymap.TAB:
                evt.stopPropagation();
                evt.preventDefault();
                $scope.stopEdit(evt);
                break;
            }
          }
          return true;
        });
      }
    }
  }
]);

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

Mongoose - facing issues with $and operator, looking for a way to locate an array containing both items

I'm currently developing a chat-based application that involves private messaging between individuals. Essentially, a Chat model in my application consists of the following schema: let schema = new Schema({ members: [{ type: ObjectId, ref: models.u ...

Incorrect Date Returned by Sequelize (-1 Day Difference)

My issue revolves around the birthdate field in one of my tables, which has a Data Type of Date. However, when attempting to export the data through an Express app, the date is transformed into a day earlier than it should be. For instance, a birthdate of ...

Encountered an unanticipated symbol at column 2 while using the Angular Google Recaptcha

I have integrated the Angular Google Recaptcha directive into my application from https://github.com/VividCortex/angular-recaptcha. However, upon running my application, I encountered an error stating that I am using my public key instead of my private key ...

Utilizing PHP and JavaScript to showcase images within a div element

Disclaimer: This message pertains to an academic task. I am seeking clarification on the required steps for completion, rather than direct code solutions. My aim is to enhance my understanding of the fundamental components involved. Currently, I am engage ...

Duplicating entries in IndexedDB

Every time I try to insert data into my database, it seems to be inserting the same data twice. Creating Table var options = { keyPath: account.primaryKey, autoIncrement: true }; var store = dbHandle.createObjectStore(account.tableName, options); ...

Troubleshooting problem with local storage: JSON/JQuery items not appearing on display

My goal is to retrieve and organize all the items in localStorage and display them on an HTML page. Here is my approach: <script> function ShoppingCart() { var totalPrice = 0; var output; var productName; var productAlbum; var ...

Leverage Angular's directives to incorporate HTML elements into your project

I am trying to integrate the HTML code from a file called protocol-modal.html into my main HTML file as a directive: <div class="modal-content"> <form class="form-horizontal" role="form" name="questionForm"> <div class="modal-heade ...

Creating a grid UI in AngularJS using Typescript: utilizing functions as column values

I am working on an AngularJS app that includes the following UI grid: this.resultGrid = { enableRowSelection: true, enableRowHeaderSelection: false, enableHorizontalScrollbar: 0, enableSorting: true, columnDefs: [ { name: &apos ...

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

Combining a table to create a JSON object with an array attribute

I am currently working with two SQL tables that have a one-to-many relationship. The query for this data is being requested by my node.JS server and I need to parse the information into a specific JSON format. For each repeated row, I want to insert the da ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

Implementing a method for JQuery event handlers to access variables within a module pattern

var MODULE = (function() { var app = { hi: "hi dad", // How can I retrieve this value? onSubmitClick: function() { $('button').click(function() { console.log(hi); // Is there a way to access ...

Validation errors are returned by express-validator duplicated

I am working on validating the request object using Express-Validator. Suppose I have two routes: a GET /users/:id route (fetchUserById) and a POST /users route (createUser). this.router = express.Router(); this.router.route('/').post(this.userR ...

The invalid `autoComplete` prop with a type of `boolean` was passed to `ForwardRef(InputBase)` instead of the expected `string`

Can anyone help me understand why a warning is being thrown when I have an autocomplete feature on this textfield? <TextField type="text" id="standard1" label="Email" ...

Create a personalized attribute for division automation

Is it possible to automatically divide a dynamically populated ListView in jQuery-mobile into two groups based on the attribute values (Downloaded/Not downloaded)? Some listitems have the attribute status="true" while others have status="false". Here is t ...

Storing various duplicates of items in local storage

Looking for help with storage settings in HTML/JavaScript as I work on a mobile not taking app using Phonegap. My goal is to allow users to input a note name and content, save them into a jquery mobile list, and see them on the home screen. However, I&apos ...

What is the method for converting data-bind tags to {{}} style bindings in KnockoutJS?

Is it possible to use AngularJS syntax for declaring bindings while using the KnockoutJS library? For example: Today's message is: <span data-bind="visible:true,text:myMessage"></span> I wish to utilize {{}} notation, similar to Angula ...

Vue.js - Launching Modal for Editing Data Entry

I have a list of records with corresponding buttons on the right side, as shown in this image: https://i.sstatic.net/uevzR.jpg Whenever I click on one of these buttons, I want a dialog box to appear containing various input fields such as text inputs, dro ...

What is causing the issue of the page overflowing in both the x and y axis while also failing to center vertically?

I've been trying to align the <H4> styled component to the center of the page using flex-box, but it's not working as expected. I also attempted using margin:0 auto, but that only aligned the H4 horizontally. Additionally, I'm investi ...

The presence of foreign collections does not appear to be reflected in the combined data

I am developing a basic forum and I'm looking to connect two databases so I can show information about the user who created a post on that post: User.js: _id:60ccb13a21d65f0c7c4c0690 username: testuser name: test And Createpost.js _id:60d80b1305dcc5 ...