SVG rendering via Angular ng-bind-html

In a recent question ( Angular Link Binding from javascript ) I asked how to link the generated SVG to a specific div. I have two good answers that I have dealt with since then.

I am trying to display an SVG image that is created based on certain properties.

Basically, I have a small Angular script that includes a number of functions for generating svg code, for example:

.controller('ctlr',['$scope','$sce', function($scope,$sce) { $scope.buildSvg(width, height, obj){ var img = ...call a lot of svg-functions return $sce.trustAsHtml(img); } 

I intend to include this in a webpage via:

 <div ng-bind-html="buildSvg(60,140,item)">svg should go here</div> 

However, it’s hard for me to get this to work, at least with javascript-generated SVG tags, it works if I copy the img code to another $ scope variable (and add a lot of screens) and then enable it via ng-bind-html.

Since the code is available in Plunker here: Example

I get the following error:

 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 

Do I need to tell $ sce somehow to avoid string literals in SVG tags?

+5
source share
1 answer

I think your problem is more related to how you bind an object in html. I mean, the reason you are returning an object through a function may be the cause of the problem. Moreover, if you see angular logs, they complain about "digest" and "apply", that is, the life cycle of the whole binding in Angular.

So basically you can decide what $ sce.trustAsHtml (SVGSTRING) is doing just like you, but save it before in a variable like $ scope.svg.

SCRIPT.js

 $scope.svg = $sce.trustAsHtml(SVGSTRING); 

And in html should be as simple as

HTML

 <div ng-bind-html="svg"></div> 

It should work, I put you in a plunker in which you can see how it even works with extracting data from the request

http://embed.plnkr.co/gQ2Rrn/

Hope this helps

+11
source

All Articles