Connecting two fields with a line on click in AngularJS

In the top section, there are 10 fields and in the bottom section, there are another 10 fields. I want to be able to connect two fields with a line when they are clicked (one from the top section and one from the bottom section). This connection should apply to all pairs of fields using AngularJS.

I would like all top fields to be connected to their corresponding bottom fields by a connecting line. By clicking on a field in the top section and its counterpart in the bottom section, a line will be drawn between them. This functionality should be present for all fields and triggered by a click event in AngularJS.

Answer №1

var myApp = angular.module("plunk", []);

myApp.controller("MainController", function ($scope) {
  $scope.top_section = [
    {
      name: "apple",
    },
    {
      name: "banana",
    },
    {
      name: "orange",
    },
    {
      name: "grapes",
    },
    {
      name: "melon",
    },
  ];

  $scope.bottom_section = [
    {
      name: "kiwi",
    },
    {
      name: "mango",
    },
    {
      name: "pear",
    },
    {
      name: "peach",
    },
    {
      name: "strawberry",
    },
  ];

  $scope.lines = [];
  $scope.unlink = {};
  
  $scope.getTopPosition = function ($index) {
    let elem = document.getElementById(`1_${$index}`);
    elem.style.transform = "scale(0.8)";
    let x = elem.offsetLeft;
    let y = elem.offsetTop;
    
    if ($scope.unlink["from"]) {
      return (
        ($scope.unlink["to"] = { x: x + 15, y: y + 30 }), $scope.clearLine()
      );
    } else {
      $scope.unlink["from"] = { x: x + 15, y: y + 30 };
    }
  };

  $scope.getBottomPosition = function ($index) {
    let elem = document.getElementById(`2_${$index}`);
    elem.style.transform = "scale(0.8)";
    let x = elem.offsetLeft;
    let y = elem.offsetTop;

    if ($scope.unlink["from"]) {
    	$scope.unlink["to"] = { x: x + 15, y: y };
    } else {
     return ($scope.unlink["from"] = { x: x + 15, y: y });
    }
    
    $scope.clearLine();
  };

  $scope.clearLine = function () {
    $scope.lines.push($scope.unlink);
    $scope.unlink = {};
  };
});
.container section {
  display: flex;
  margin-bottom: 100px;
  justify-content: space-between;
}
.container section.bottom {
  display: flex;
  justify-content: space-between;
}
.top-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.bottom-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.line {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  z-index: -1;
}
.line svg {
  width: 100%;
  height: 100%;
}
<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJs Demo</title>
    <link rel="stylesheet" href="style.css" />
    <script
      data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3f3039332a37346521283b7c27123135">[email protected]</a>"
      src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"
    ></script>
    <script src="app.js"></script>
  </head>
  <body ng-controller="MainCtrl">
   <div class="container section">
      <div class="top-section" ng-repeat="t in top_section">
        <span id="1_{{t.name}}" ng-click="getTopPosition(t.name)"
          ><svg fill="#000000" height="30px" width="30px" viewBox="0 0 490 490">
            <path
              d="M0,0v490h490V0H0z M430.1,332.9h-87.5v50.9h-33.1v50.9H180.4v-50.6h-33.1v-51.3H59.9v-278h46.7v66.5h38.5V54.8h40.8v66.5
         h38.5V54.8h40.8v66.5h38.5V54.8h40.8v66.5H383V54.8h46.7v278.1L430.1,332.9L430.1,332.9z"
            /></svg
        ></span>
        {{t.name}}
      </div>
    </div>

    <div class="container section bottom">
      <div class="bottom-section" ng-repeat="b in bottom_section">
        <span id="2_{{b.name}}" ng-click="getBottomPosition(b.name)"
          ><svg fill="#000000" height="30px" width="30px" viewBox="0 0 490 490">
            <path
              d="M0,0v490h490V0H0z M430.1,332.9h-87.5v50.9h-33.1v50.9H180.4v-50.6h-33.1v-51.3H59.9v-278h46.7v66.5h38.5V54.8h40.8v66.5
       h38.5V54.8h40.8v66.5h38.5V54.8h40.8v66.5H383V54.8h46.7v278.1L430.1,332.9L430.1,332.9z"
            /></svg
        ></span>
        {{b.name}}
      </div>
    </div>
    <span class="line">
      <svg>
        <line
          ng-repeat="line in lines"
          x1="{{line.from.x}}"
          y1="{{line.from.y}}"
          x2="{{line.to.x}}"
          y2="{{line.to.y}}"
          style="stroke: rgb(255, 0, 0); stroke-width: 2"
        />
      </svg>
    </span>
  </body>
</html>

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

Tips for Creating a Responsive Homepage

I'm new to CSS and trying to create a responsive design for mobile IE. Currently, the page appears blank on IE but works fine on Google Chrome and other browsers :-) Here are the code snippets I have used: HTML: <div class="main"> <div ...

The callback function for ajax completion fails to execute

My current framework of choice is Django. I find myself faced with the following code snippet: var done_cancel_order = function(res, status) { alert("xpto"); }; var cancel_order = function() { data = {}; var args = { type:"GET", url:"/exch ...

What benefits are there to converting a jQuery application to Angular?

If I have a basic landing page with jQuery effects that I want to upgrade by "angularizing" it with AngularJS, how could I do so? For example, when using AngularJS for a contact form, it's known to be simple to implement. When considering DOM effects ...

Obtaining Text within <span>Tag</span> with Selenium in C#

I am encountering an issue when trying to retrieve the Subject title of an email from Unread emails using Selenium Webdriver with C#. Below is the HTML code provided : <div class="ae4 UI UJ" gh="tl"> <div class="Cp"> <div> <ta ...

AJAX Response: No data available

I am currently attempting to retrieve data from a SQL server and showcase it on a webpage using [WebMethod] by following this tutorial. However, I have customized the data and logic for my own use. Objective - To display the count of incidents based on Pr ...

Use jQuery to create a price filter that dynamically sets slide values based on the filter object

I'm currently utilizing the jQuery slide filter to sort products based on price. The filtering value is set within the script, but I am interested in dynamically setting it based on the highest/lowest number found on my page using a data attribute. D ...

Creating a custom request for the Upload component in Ant Design Vue requires a specific set of steps and

I attempted to implement the solution provided in How should customRequest be set in the Ant Design Upload component to work with an XMLHttpRequest? but it doesn't seem to be working for me in Ant Design Vue. Could someone provide an example, please? ...

What is the process of querying both a collection and a subcollection in Firebase using AngularFire?

I have a structure in my firebase database that looks like this: /profiles/{uid}/displayName /email /otherAttribues /roles/{roleName}/someAttribute /someOtherAttribute The reason ...

Using React-Router v6 to pass parameters with React

My App.js file contains all the Routes declarations: function App() { return ( <div className="App"> <Routes> <Route path="/"> <Route index element={<Homepage />} /> ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. const data = b64image.split(',&ap ...

The `chrome.windows` API is not defined for this particular Chrome

I'm currently in the process of developing a Chrome extension that will allow users to effectively manage open tabs within a specific application's website. Here is the current manifest file: { "manifest_version": 2, "name": "AT Tabs", ...

Building a table in Quasar by utilizing nested objects

I am currently facing an issue while using Quasar to create Q-Tables. I am struggling with incorporating nested objects with dynamic key names. Below is the content of my table: data: [ { 'FrozenYogurt' : { &a ...

What are the steps to configure an option date for Yesterday, Today, and Tomorrow?

I have been working on setting options for dates like yesterday, today, and tomorrow. I have implemented the following code which is functioning properly, but it is not displaying yesterday's date. I want today's date to be selected and also disp ...

A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script ...

Connecting a Database with NestJS and TypeORM: A step-by-step guide to establish a connection with TypeORM and ensure easy access to

Could someone please explain how to create a DB instance using TypeORM? I want it to be accessible like this service, but the Connection class is deprecated. import { Inject, Injectable } from '@nestjs/common'; import { Connection, Repository } ...

How to create a clickable link that functions as a file upload button

I am working on a project where I need to create a link that acts as a file input when clicked. Here is the code for the link: <a id="upload-file">Upload your photo</a> Is there a way to make this link function as a browse file input? Any ...

How to Delete Elements from an ngList Array in Angular

I encountered an issue while utilizing ngList in a text box to exchange data with my server. The problem arises when I attempt to delete items from the generated array directly, as it does not reflect the changes in the input field. The main concern is th ...

Using jQuery to create animated effects for hidden input fields

The struggle to smoothly animate and fade in a hidden text field can be witnessed in this example. The goal is to seamlessly move all elements around the text field and button while fading in/out the hidden element. However, it appears that towards the en ...

The HTML code appears to be functioning correctly in all web browsers except for Safari

There appears to be an issue with submitting the form in Safari browser. The form functions correctly in all browsers except for Safari. <form action="/commonDashboard" name="loginForm" method="post" autocomplete="off" id="loginForm"> <div&g ...

utilizing parent scope in a jQuery function callback

Currently, I am facing an issue concerning a jQuery callback working on a variable that is outside of its scope. To illustrate this problem, consider the code snippet below: $('#myBtn').on('click', function(e) { var num = 1; / ...