In a recent question (Reference Angular binding from javascript) I asked how to bind a generated SVG to a specific div. I got two good answers which I've been tinkering with since.
I'm trying to display a SVG image which gets built based on specific properties.
Basically I have a tiny Angular script which includes a number of functions for generating svg code, e.g.:
.controller('ctlr',['$scope','$sce', function($scope,$sce) {
$scope.buildSvg(width, height, obj){
var img = ...call a lot of svg-functions
return $sce.trustAsHtml(img);
}
My intention is to include this on the web page via:
<div ng-bind-html="buildSvg(60,140,item)">svg should go here</div>
However, I have a hard time getting this to work, at least with the javascript generated SVG tags, it works if I copy paste the img code into another $scope variable (and add a lot of escaping) and then include it via ng-bind-html.
As the code is available on 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 somehow inform $sce to escape string literals in the SVG tags?
I think your problem is more regarding to how you are binding the object in html. I mean, the fact that you are returning the object through a function can be the cause of the problem. Moreover, if you see angular logs, they are complaining about "digest" and "apply", that is the life cycle of all the binding in Angular.
So basically, you will be able to solve that doing $sce.trustAsHtml(SVGSTRING) as you did, but saving it before in a variable like $scope.svg.
SCRIPT.js
$scope.svg = $sce.trustAsHtml(SVGSTRING);
And in the html should be as simple as that
HTML
<div ng-bind-html="svg"></div>
It should work, I am putting you a plunker in which you can see how it even works retrieving data from a request
http://embed.plnkr.co/gQ2Rrn/
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With