在最近的一个问题(来自javascript的Reference Angular binding)中,我问如何将生成的SVG绑定到特定的div.我得到了两个很好的答案,自那以后我一直在修修补补.
我正在尝试显示基于特定属性构建的SVG图像.
基本上我有一个很小的Angular脚本,其中包含许多用于生成svg代码的函数,例如:
.controller('ctlr',['$scope','$sce', function($scope,$sce) {
$scope.buildSvg(width, height, obj){
var img = ...call a lot of svg-functions
return $sce.trustAsHtml(img);
}
Run Code Online (Sandbox Code Playgroud)
我的意图是通过以下方式将其包括在网页中:
<div ng-bind-html="buildSvg(60,140,item)">svg should go here</div>
Run Code Online (Sandbox Code Playgroud)
但是,我很难让它工作,至少使用javascript生成的SVG标签,如果我将img代码粘贴到另一个$ scope变量(并添加大量转义)然后通过ng-包含它,它就可以工作结合-HTML.
由于代码在Plunker上可用: 示例
我收到以下错误:
Error: [$sce:itype] http://errors.angularjs.org/1.4.0/$sce/itype?p0=html
at Error (native)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:6:416
at $get.trustAs (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:140:269)
at Object.$get.d.(anonymous function) [as trustAsHtml] (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:142:444)
at m.$scope.buildSvg (file:///C:/Dropbox/workspace/famview/public/javascripts/svgController.js:37:16)
at fn (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:210:400), <anonymous>:2:301)
at Object.get (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:115:108)
at m.$get.m.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:131:221)
at m.$get.m.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:134:361)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js:19:362
Run Code Online (Sandbox Code Playgroud)
我是否需要以某种方式告知$ sce以逃避SVG标记中的字符串文字?
ack*_*ser 12
我认为你的问题更多的是关于如何在html中绑定对象.我的意思是,你通过函数返回对象的事实可能是问题的原因.此外,如果你看到角度日志,他们抱怨"摘要"和"应用",这是Angular中所有绑定的生命周期.
所以基本上,你将能够像你一样解决那个做$ sce.trustAsHtml(SVGSTRING)的事情,但是之前将它保存在像$ scope.svg这样的变量中.
的script.js
$scope.svg = $sce.trustAsHtml(SVGSTRING);
Run Code Online (Sandbox Code Playgroud)
并且在HTML中应该就这么简单
HTML
<div ng-bind-html="svg"></div>
Run Code Online (Sandbox Code Playgroud)
它应该工作,我给你一个plunker,你可以看到它甚至可以从请求中检索数据
希望这可以帮助