javascript - 为什么 Angular 中的 SVG 元素的模板渲染出现错误

标签 javascript angularjs svg

<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-widthng-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的参数。如果它不是您定义的服务,请将其删除。它也可能会出错。

更多信息请参见此处: https://docs.angularjs.org/guide/interpolation

关于javascript - 为什么 Angular 中的 SVG 元素的模板渲染出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37951146/

相关文章:

javascript - 是否可以使用 javascript 和/或 css 修改背景 svg 图像?

AngularJS 复制到剪贴板

javascript - 创建允许用户添加或删除项目的服务

angularjs - 获取 gs://example.appspot.com/images net::ERR_UNKNOWN_URL_SCHEME

html - LESS 和 IE9 过滤器 :none for svg gradient compatibility?

javascript - 如何在预先输入的 Angular 输入搜索框中分离两组数据?

javascript - 在 req.body 中包含表

Javascript-从函数返回一个对象

javascript - 如何在聊天时追踪好友的IP地址

javascript - 如何在一个 html 页面上应用两个 svg?