Guide on moving the parent <div> at an angle within an AngularJS custom directive

The code snippet below demonstrates the functionality of dynamically generated ellipse elements as they change color based on an array.

I have been experimenting with updating the style property of the parent div element within a custom directive. This involves shifting the position of the div elements downwards and to the right by changing 'position' to absolute, along with adjusting the left and top properties according to the id value of each corresponding div.

Although the id value can be accessed in the compile function, I encountered the issue of tElem being undefined here:

How can I access the parent element to modify its style-related properties?

<!DOCTYPE html>
<html ng-app="app">
 <head>
  <meta charset="utf-8>
  <title>Custom AngularJS Directive for SVG Elements</title>

  <style>
    div { width:80px; height: 40px; }
  </style>

  <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.js">
  </script>

  <script>
   var app = angular.module("app", []);

   app.directive('div', function() {
       var colors = ["red", "green", "orange", "blue", "#fcc"];
       var color  = colors[0];
       var shape  = '<ellipse cx=40 cy=40 rx=30 ry=15 fill="'+color+'">';
       var mydir  = {};
       mydir.restrict = 'E'; 
       mydir.template = '<svg>'+shape+'</svg>';

       mydir.compile = function(tElem, tAttrs){
                         var id = tAttrs['id'];
                         color = colors[id % colors.length];
                         var shape = 
                           '<ellipse cx=40 cy=40 rx=30 ry=15 fill="'+color+'">';
                         mydir.template = '<svg>'+shape+'</svg>';


                       //==============================================
                       // Set 'position:absolute;' property for <div ;element and shift it diagonally:
                       // var left = id*80, top = id*40;
                       // tElem.style.left = left+"px";
                       // tElem.style.top  = top+"px";
                       // tElem.style.position = "absolute";
                       //==============================================
       };

       return mydir;
   })

   app.controller("MyController", function() {}); 
  </script>
 </head>

 <body ng-controller="MyController as mc" >
  <div id="1"></div>
  <div id="2"></div>
  <div id="3"></div>
  <div id="4"></div>
  <div id="5"></div>
  <div id="6"></div>
 </body>
</html>

Answer №1

Your current method is correct, but when you need to change the style of an element, you should access the actual DOM of that element by using tElem[0], which will give you the DOM of the specific div element.

Code

tElem[0].style.left = left+"px";
tElem[0].style.top  = top+"px";
tElem[0].style.position = "absolute";

See Style Plinkr Example

A Better Approach

It would be better to apply all the CSS properties using the .css method of jQLite, which accepts the properties in JSON format along with their values.

Code

tElem.css({
  'left': left + "px",
  top: top  + "px",
  position: 'absolute'
});

View Demo Plunkr

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

Creating flexbox items with equal height

I have a flexbox parent with flex-direction set to row. Within this parent, I have two children that I want to have the same height! Both of these children contain dynamic content with varying heights. The issue I'm facing is that when I add text t ...

Issue with Angular form not triggering ng-submit functionI am facing a problem where

Issue with angular submission: I've been trying to implement a simple submission feature using angular, but the $scope.account_create.submit function isn't getting called upon submission. I have added the name attribute to the form and ensured th ...

Retrieving Table Cell Values Using Jquery: A Step-by-Step Guide

<table class="table" align="center" id="tblMain"> <tr> <td>Status</td> <td><b><span name="current" value="Dispatch">Dispatch</span></b></td> </tr> </table> JS $(&apos ...

Enable scrolling exclusively for the content within a tab, without affecting the tab label in Clarity Tabs

I have a tab with lengthy content in my project (check out the StackBlitz reference here). This causes the appearance of a scroll. https://i.sstatic.net/ZcNKM.png The corresponding code snippet is provided below: <div class="content-container&qu ...

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Issue with AngularJS UI Bootstrap Datepicker not opening again after clicking away

I've integrated Angular UI bootstrap with my AngularJS project, utilizing version 0.11.0. While implementing various directives from the library, I encountered an issue when trying to incorporate the date picker. There are instances where multiple da ...

I am eager to display this JSON data using AngularJS tables

I have JSON file with content about categories, departments, and digital marketing: { "categories":[ { "dept_id":"123", "category_name":"database", "category_discription":"list of database", "current time ...

Is it possible to incorporate pre-written HTML code into ASP.NET?

Is there a method to transform an HTML template into ASP.NET? I am attempting to convert a website template, which includes Javascript and CSS files, from HTML to ASP.NET in order to establish a connection with a SQL Server database. I have minimal coding ...

What is the best way to arrange my crimson blocks to sit next to each other?

Is there a way to align the red boxes side by side with some space in between them for separation, and how can I ensure that the signin/signup button appears against the blue background of the header? I attempted using float but encountered issues. The d ...

How to toggle a specific element in Bootstrap 4 with a single click, without affecting other elements

I've been struggling with a frustrating issue: I have 3 elements next to each other at the bottom of the fixed page. I tried using Bootstrap4 toggles to display only text when a user clicks on an image, but it ends up toggling all the images instead o ...

Adaptable Collection of 4 Images

I am facing a challenge in replicating eBay's 'Today' featured seller layout with 4 square images creating one box (refer to the image). I am using Bootstrap for this task, and I am finding it difficult to comprehend how to achieve this. I h ...

Developing an object that displays animated effects when modifying its properties, such as visibility, and more

Exploring the realm of animations in JavaScript and AngularJS has led me to the idea of creating a unique JavaScript object. Imagine having the ability to define an object where setting an attribute like obj.visible = true Would automatically make the ...

Using PHP to output HTML tags as text

How can I display an HTML tag as text on screen, rather than in code format? I want readers to be able to easily read the tag itself. What is considered the best practice for achieving this? print htmlspecialchars('<meta name="copyright" conten ...

How to resolve the unusual spacing issue caused by Bootstrap?

I am encountering an issue with positioning two images on my website. I want one image to float all the way to the left of the viewport and the other to the right. However, there seems to be a strange space created on the right side of the right image. I a ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

What is the reason for Firefox and Opera disregarding the max-width property when used within display: table-cell?

When viewing the code below, you may notice that it displays correctly in Chrome or IE with the image set to be 200px wide. However, in Firefox and Opera, the max-width style seems to be completely ignored. Is there a reason for this inconsistency across b ...

How can a table row be connected to a different frame?

I am currently incorporating jQuery into my project and I would like to have the table row link redirect to a different target frame. Here is the HTML for the table row: <tr data-href="home.html" target="content"><td><h3><center>H ...

Executing a JavaScript function within a PHP echo statement

I am completely new to working with AJAX and PHP echo variables or arrays. However, I have managed to successfully display images on my website by passing variables from AJAX to PHP and back. The only problem I am encountering is when I try to call a Javas ...

Creating a Background Cutout Effect with CSS Using Elements instead of Images

I'm working on creating a unique visual effect that simulates a "window" where the div placed above all other elements acts like a window, allowing the background color to show through. Take a look at this example for reference. My goal is to make th ...

Having trouble with implementing a lightbox form data onto an HTML page using the load() function? Let me help

In my project, I have set up a lightbox containing a form where user inputs are used to populate an HTML file loaded and appended to the main HTML page with the load() function. While I can successfully load the data onto the page, I am facing challenges i ...