这是我的代码:
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
// this directive replaces itself with a <g> tag
app.directive('hexagonReplace', function(){
return {
templateUrl: 'hexagonReplace.html',
restrict: 'E',
replace: true,
scope:{
dx: '=',
dy: '='
}
};
});
// this directive appends a <g> tag with a polygon forming a hexagon
app.directive('hexagonAppend', function(){
return {
templateUrl: 'hexagonAppend.html',
restrict: 'A'
};
});
hexagonReplace.html
<g class='hexagon' ng-attr-transform='translate({{dx}},{{dy}})'>
<polygon points="21.65063509461097,-12.499999999999998 21.65063509461097,12.499999999999998 1.5308084989341915e-15,25 -21.65063509461097,12.499999999999998 -21.65063509461097,-12.499999999999993 -4.592425496802574e-15,-25">
</polygon>
</g>
hexagonAppend.html
<polygon points="21.65063509461097,-12.499999999999998 21.65063509461097,12.499999999999998 1.5308084989341915e-15,25 -21.65063509461097,12.499999999999998 -21.65063509461097,-12.499999999999993 -4.592425496802574e-15,-25">
</polygon>
的index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<svg width=100 height=100>
<!-- This hexagon will not be shown -->
<hexagon-replace dx=50 dy=50></hexagon-replace>
<rect class='outline' width=100 height=100></rect>
</svg>
<svg width=100 height=100>
<!-- This hexagon looks almost the same in the resulting html but is displayed properly -->
<g class='hexagon' transform='translate(50,50)' hexagon-append></g>
<rect class='outline' width=100 height=100></rect>
</svg>
</body>
</html>
的style.css
/* Put your css in here */
.hexagon {
stroke: black;
fill: pink;
}
.outline {
fill: none;
stroke: black;
}
在http://plnkr.co/edit/lzET3CMrth2uHTSfCity
处试试我想创建一个带有几个六边形的svg元素。为了清理代码并减少冗余,我希望有一些'hexagon'元素可以放入svg-node。 不幸的是,它没有按预期工作。
当用我的模板替换六边形节点时,由于某种原因,多边形子节点似乎处于非活动状态。
如果我使用'hexagon'指令将多边形节点添加到现有的g节点,它可以正常工作。然而,这不是我的首选解决方案,因为在这种情况下,我将为每个g节点提供冗余属性。
任何想法?
编辑:我注意到实际上在Firefox中都没有出现。而在铬中,行为如上所述。
第二编辑:
这两个看起来很相关......实际上第一个已经回答了我的问题
那我会寻找一种不同的方法
Including SVG template in Angularjs directive
How to make Chrome redraw SVG dynamically added content?