gpt4 book ai didi

javascript - 如何让 AngularJS 在 svg 模板中填充初始标签值?

转载 作者:行者123 更新时间:2023-11-30 00:26:56 25 4
gpt4 key购买 nike

我正在尝试获取 AngularJS 指令以在 svg 标记中设置各种属性。

angular.module("complexNumbers")
.directive("cartesianPlane", function() {
return {
restrict: "E",
scope: { },
templateUrl: "shared/cartesianPlane/cartesianPlaneView.html",
controller: function($scope) {
$scope.viewBox = {
x : -20,
y : -20,
width : 40,
height : 40,

value : function() {
return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height;
}
};
},
link: function($scope, $elem) {
// Then adjust for aspect ratio
var aspectRatio = $elem.height() / elem.width();
$scope.viewBox.height = $scope.viewBox.width * aspectRatio;
}
};
});
<!-- cartesianPlaneView.html -->

<svg width='100%' height='100%' viewBox='{{viewBox.value()}}' style='position:relative; top:0px; left:0px; float:left;'>
<line class='axis' x1='{{viewBox.x}}' y1='0' x2='{{viewBox.x + viewBox.width}}' y2='0'></line>
<line class='axis' x1='0' y1='{{viewBox.y}}' x2='0' y2='{{viewBox.y + viewBox.height}}'></line>

这种方法有两个问题:

1) AngularJS 似乎从 templateUrl 渲染标签,但最初没有插入值。因此浏览器提示:

Error: Invalid value for <svg> attribute viewBox="{{viewBox.value()}}"
Error: Invalid value for <line> attribute y1="{{viewBox.y}}"
Error: Invalid value for <line> attribute y2="{{viewBox.y + viewBox.height}}"
Error: Invalid value for <line> attribute x1="{{viewBox.x}}"
Error: Invalid value for <line> attribute x2="{{viewBox.x + viewBox.width}}"

我会想到当模板被渲染时,$scope 的初始值会立即被插入?相反,模板 {{}} 标签按原样进入。

2) 链接函数的 $elem 参数没有 width() 和 height() 属性。这些何时可用?我如何计算和设置 aspectRatio?

Error: TypeError: $elem.height() is not a function

最佳答案

我相信对于问题 #1,您会想要使用 ng-attr。因此,在您的指令中,您将使用 ng-attr-viewBoxng-attr-x 等...

至于你的第二个问题,.height() 应该在那里可用并且应该由 JQLite 提供

关于javascript - 如何让 AngularJS 在 svg 模板中填充初始标签值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31082258/

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