【问题标题】:Why template rendering get error for SVG element in ANgular为什么 Angular 中的 SVG 元素的模板渲染会出错
【发布时间】:2016-10-23 09:34:12
【问题描述】:

<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 仍然可以正确渲染

【问题讨论】:

  • 尝试将ng-if="width &amp;&amp; height" 添加到指令的模板中,或查看@Suren 的回答——我认为它们是正确的
  • ng-cloak 添加到模板时会发生什么? "&lt;div ng-cloak&gt;&lt;svg width={{width}} height={{height}}&gt;&lt;/svg&gt;&lt;/div&gt;" ?
  • @AlonEitan 同样的错误
  • 这似乎是由于浏览器实现了 SVG github.com/angular/angular.js/issues/1050

标签: javascript angularjs svg


【解决方案1】:

将您的 = 更改为 @

= - 是双向绑定。您必须传递一个变量
@ - 是一种单向绑定。您将文本传递给它。

并将您的宽度和高度值放入'

第一版

你需要使用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

【讨论】:

  • 我做了,它仍然显示:jquery.min.js:3 错误: 属性宽度:预期长度,“{{width}}”错误: 属性高度:预期长度, "{{height}}"。
  • 抱歉,用在什么地方?
  • 是的,现在没有错误了,非常感谢!但是第一个版本有什么问题(因为如果我必须使用这种方式,这意味着我失去了所有模板功能)?就像我问的那样,如果我遇到这种错误,我该如何调试它?
  • 谢谢,很好。只要保持更新,当我在模板中添加 时,这部分也会出错,似乎我添加的任何属性都会出错,只要它是一个范围变量
  • 是的,没错,我在我的问题中也提到了这一点,如果我不操作控制台,一切都很好,我只是对为什么会出现这个错误感到困惑,这会是一个隐藏的炸弹吗?可能会导致未来的问题
【解决方案2】:

我认为问题在于您没有用引号将 {{}} 括起来,模板应该是:

template: "<svg width='{{width}}' height='{{height}}'></svg>"

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 2017-04-01
    • 2014-10-06
    • 2017-05-03
    • 1970-01-01
    • 2016-04-23
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多