<html ng-app="vg">
<body>
<justsvg width="100" height="25"></justsvg>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var app = angular.module('vg', []);
app
.directive("justsvg", function(){
return {
restrict:"AE",
scope:{
width: "@",
height: "@"
},
template: "<svg width='{{width}}' height='{{height}}'></svg>"
}
})
</script>
</body>
</html>
所有:
我对 Angular 还很陌生,当我尝试在指令中渲染 SVG 时,它总是给我错误,例如:
<svg> attribute width: Expected length, "{{width}}".
我的代码非常简单:
.directive("justsvg", function(d3){
return {
restrict:"AE",
scope:{
width: "@",
height: "@"
},
template: "<svg width='{{width}}' height='{{height}}'></svg>"
}
})
我的使用方式是:
<justsvg data=data width="100" height="25"></justsvg>
我想知道为什么即使这样简单的用法仍然会出错?另外,谁能告诉我如何调试这种错误?
有趣的是:即使我遇到了这个错误,SVG 仍然可以正确渲染
最佳答案
将 =
更改为 @
。
=
- 是双向绑定(bind)。您必须传递一个变量
@
- 是一种单向绑定(bind)。您向其传递文本。
并将宽度和高度值放入'
中。
第一个版本
您需要使用ng-width
和ng-height
template: "<svg ng-width='{{width}}' ng-height='{{height}}'></svg>"
第二版
.directive("justsvg", function(d3){
return {
restrict:"AE",
scope:{
data: "=",
width: "@",
height: "@"
},
template: "<svg></svg>",
link: function ($scope, $element) {
$element.attr('width', $scope.width);
$element.attr('height', $scope.height);
}
}
})
并且在函数中您有一个名为d3
的参数。如果它不是您定义的服务,请将其删除。它也可能会出错。
关于javascript - 为什么 Angular 中的 SVG 元素的模板渲染出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951146/