Assign an Angular model to an input in a dynamic manner

Currently, I am working on developing a compact spreadsheet feature for my angular application. My goal is to replicate a common functionality found in spreadsheets where users can click on a cell and then modify its value using a larger input field at the top of the sheet. However, I am facing a challenge in dynamically assigning the model of a cell to the large input when a user clicks on the cell.

There are various details to consider regarding the blur and focus of the cells. Additionally, the example I provided is a simplified version, as the actual spreadsheet can have any number of rows and columns. My main query revolves around how to dynamically link a cell's model to the large input so that it can function as a proxy input for the cell. If this approach is not feasible or practical, I am open to alternative suggestions on how to tackle this issue.

At this stage, I have made some progress, but I am uncertain if my current approach within this directive is viable. I would appreciate any insights or ideas on how to improve this functionality.

Explore the code example here

index.html

<table ng-controller="SpreadsheetCtrl" custom-spreadsheet>
  <thead>
    <tr>
      <th colspan="3">
        <input type="text" style="width: 100%" />
      </th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="row in rows">
      <td>
        <input ng-model="row.A" type="text" />
      </td>
      <td>
        <input ng-model="row.B" type="text" />
      </td>
      <td>
        <input ng-model="row.C" type="text" />
      </td>
    </tr>
  </tbody>
</table>

script.js

var app = angular.module('app', []);

app.controller('SpreadsheetCtrl', function($scope) {
  $scope.rows = [
    {A: 'a', B: 'b', C: 'c'},
    {A: 'a', B: 'b', C: 'c'},
    {A: 'a', B: 'b', C: 'c'}
  ];
}); 

app.directive('customSpreadsheet', function () {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var primary = element.find('thead input');
      element.on('focus', 'tbody input', function () {
        primary.attr('ng-model', $(this).attr('ng-model'));
      });
    }
  };
})

Answer №1

Instead of using the directive, I recommend using ng-click. Check out this working PLUNKER for reference.

Keep in mind

<input ng-model="row.A" type="text" ng-click="choose(row, 'A')"/>

Also

<input type="text" ng-model="selected[attr]" style="width: 100%" />

Include

$scope.choose = function(row, attr) {
    $scope.selected = row;
    $scope.attr = attr;
}

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

A Step-by-Step Guide to Clearing JSON Cache

I'm currently utilizing jQuery to read a JSON file. However, I've encountered an issue where the old values are still being retrieved by the .get() function even after updating the file. As I continuously write and read from this file every secon ...

React Error: "SharedArrayBuffer is not defined" Firefox encountered a problem

I am encountering an issue with my React app that was created using 'create-react-app' along with the jsdom NPM package. Strangely, the application is throwing an error upon loading exclusively in Firefox, as it works perfectly fine in Chrome and ...

Using `ngRepeat` on a different array of values for repetition

Working with AngularJS. Here is an example of a JSON object: "skills": { "Charisma": {}, "Dexterity": { "Sk3": [ [ true, true, true, true, false ], 44 ] }, ... And the corresponding HTML: <div class="pan ...

Expansive full screen image proportions

Is there a way to showcase an image on the entire screen without distorting it, while maintaining its aspect ratio in either HTML or Javascript? The desired outcome is for the image to be centered and: - Have a height of 100% and a width of x% (where "x" ...

Creating a versatile function to verify the presence of empty values

Looking to validate fields for emptiness in a router, with potential use in other routers as well. How can I create a single function to handle this task? To see how it operates: , Desiring something similar to: , ...

"Execute asynchronous tasks in Javascript and receive the returned

Currently, I am utilizing JSF ajax within my application and unfortunately, we are unable to make any changes to that. In the process of waiting for user action, I find it necessary to prompt the user before executing the ajax method. Specifically, I need ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Is there a way to access an object within another object without the need to use a function

Having trouble accessing an object? Let's solve this mystery together. I'm trying to access 'ctx', but base.ctx keeps returning null (is there a closure involved?). window.base = function () { var c = null, ctx = null; ...

Assistance needed in obtaining the ID of a specific table row using jQuery

Currently, I am working on an AJAX request using Jquery and PHP. The task involves looping through an array to generate a table. During each iteration, a new ID is assigned to the table row. When users click on the "read me" link, additional content is f ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

JavaScript Multiplicative Persistence Problem Resolved by Implementing Efficient Solution that Executes in a Timely

I am currently facing an issue with the following problem: Your task is to create a function called persistence, which takes a positive parameter num and calculates its multiplicative persistence. Multiplicative persistence refers to the number of times y ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Handling events with ReactJS can be made even more powerful by passing parameters to

Just dipping my toes into the world of ReactJs and I've put together a component to display a list of buses. My goal is to enable edit and delete functionality for each bus, but I'm struggling to pass the corresponding busId to my edit/delete met ...

The leaflet popup fails to open for the second time

I used a for loop to create markers on the map. When I click on a marker, a popup opens. However, after clicking on the same marker a second time, the popup does not open. My $scope.resSearchAnnouncement contains JSON data. How can I resolve this issue? ...

AngularJS 1 - CSS glitch occurs when navigating between tabs

Upon loading my homepage, it appears as follows: https://i.sstatic.net/CTlj1.png Initially, certain rows were filled with a blue background color using ng-class, specifically "row-answered-call" as shown below: <tr ng-repeat="item in list" ng-class=" ...

Preserving scroll position during page navigation in Next.js

Currently, I am working on a website using the Next.js boilerplate. Here is the routing code that I am using: import Link from 'next/link' <Link href={{ pathname: '/some-url', query: { param: something } }}> <div> ...

Changing the CSS of ng-view when triggering CSS in ng-include: A step-by-step guide

Incorporating my left-hand, vertical navbar into the page using ng-include, I've managed to make it expand right on hover. Each page is enclosed within a <div class="wrapper">. My goal is to adjust the margin of each wrapper as the navbar expan ...

Anchor element not displaying Bootstrap popover upon focus trigger

I'm exploring ways to implement bootstrap popovers that respond to both click and hover events without relying on jQuery. I have a variety of controls on my page and I want to bind popovers to them using JavaScript. While testing with buttons and anc ...

io.emit is unable to send messages to all connected clients

Struggling to implement a feature in a socket.io game where players can leave the game, I'm facing an issue with io.emit only notifying the departing player. Here's the snippet from my socket.js: io.on("connection", sock => { sock.on(&ap ...

Tips for avoiding a form reload on onSubmit during unit testing with jasmine

I'm currently working on a unit test to ensure that a user can't submit a form until all fields have been filled out. The test itself is functioning correctly and passes, but the problem arises when the default behavior of form submission causes ...