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>