gpt4 book ai didi

html - 如何在 AngularJS 自定义指令中对 Angular 移动父

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:58 26 4
gpt4 key购买 nike

以下代码示例工作正常:动态生成的 ellipse 元素的颜色遍历数组中的颜色。

作为一个变体,我尝试在自定义指令中动态更新父 div 元素的 style 属性,以便 div 通过将 'position' 设置为 absolute 并将 lefttop 属性设置为相应 div 元素的 id 值。

因为 id 的值可以在compile 中访问,所以它似乎是更新父级 div 的一个方便位置,但是 tElem 在这里未定义:

如何访问父元素以更新其样式相关的属性?

<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title>Custom SVG Directive in AngularJS</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 a 'position:absolute;' property for <div>
// and also shift the <div> element 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>

最佳答案

您目前的做法是正确的,但是当您想要更改元素的 style 时,您需要通过执行 tElem[0] 使用该元素的实际 DOM它将具有该 div 元素的 DOM。

代码

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

Using Style Plunkr

更好的方法

最好将所有 css 属性添加到 jQLite 的 .css 方法中,它会接受 json 格式的所有属性及其值。

代码

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

Demo Plunkr

关于html - 如何在 AngularJS 自定义指令中对 Angular 移动父 <div>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30962328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com