I want to display the SVG using dangerouslySetInnerHTML.
<div dangerouslySetInnerHTML={{__html:props.SVG_Thumbnail__c}} />
However, the SVG data I got is an escaped HTML string.
I though this is a common case in Frontend. However, I did a google search none of built-in method could handle all the escaped chars perfectly.
The escape method doesn't work.
What's a common way to handle this string?
Write the replace methods every time?
var escaped = str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
<svg width="100%" height="100%&q%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Primary Content</text></svg><svg x="10%" y="64%" width="90%" height="26%"><rect x="0" y="0" width="100%" height="100%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Secondary Content</text></svg></svg>
One thing you can do is assign the escaped value to an HTML element's innerHTML property, and then use the textContent property to get it back in unescaped form.
function unescapeHtml(value) {
var div = document.createElement('div');
div.innerHTML = value;
return div.textContent;
}
var escapedValue = '<svg width="100%" height="100%&q%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Primary Content</text></svg><svg x="10%" y="64%" width="90%" height="26%"><rect x="0" y="0" width="100%" height="100%" fill="#ffffff"/><text x="5%" y="50%" font-family="Lato" font-size="8px" alignment-baseline="middle" fill="#37444e">Secondary Content</text></svg></svg>';
var unescapedValue = unescapeHtml(escapedValue);
console.log(unescapedValue);
Related
I have this code where I need to display multiple small rectangles inside a big rectangle and I need to do this entire process multiple times.
here is my data:
"data": {
"rect1": {
"a":[10,20],
"b":[35,10]
},
"rect2": {
"y":[25,10],
"z":[55,20]
}
}
This data should make two rectangles rect1 and rect2 and two rectangles inside each of them a,b and y,z respectively. each small rectangle has start position x and width of that small rectangle for example a starts at x 10 and width=20.
<ul>
<li ng-repeat="(rect,coords) in data">
<svg>
<rect x=1 y=1 width=1000 height=50 style="fill:grey;" />
<span ng-repeat="coord in coords">
<rect x={{coord[0]}} y=1 width={{coord[1]}} height=50 style="fill:blue;" />
enter code here
But this code is not working as I have added ng-repeat line between the two tags.
image of what the final result should look like
I made this image in powerpoint so ignore the background.
You were pretty close. You can't use <span> inside an SVG. But most of the rest was correct.
Also it is better to use ng-attr-x="{{value}} instead of x="{{value}}. Otherwise the SVG parser will throw errors because it doesn't understand the string "{{value}}".
Here is a working example.
var app = angular.module('myApp', [])
app.controller("AppCtrl", ["$scope", function($scope) {
$scope.data = {
"rect1": {
"a":[10,20],
"b":[35,10]
},
"rect2": {
"y":[25,10],
"z":[55,20]
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<ul ng-controller="AppCtrl">
<li ng-repeat="(rectName, coords) in data">
<svg id="{{rectName}}" width="100%" height="50">
<rect x="1" y="1" width="1000" height="50"
style="fill: lightgrey;" />
<rect ng-repeat="(label, coord) in coords"
ng-attr-x="{{coord[0]}}" y="1"
ng-attr-width="{{coord[1]}}" height="50"
style="fill: blue;" />
<text ng-repeat="(label, coord) in coords"
ng-attr-x="{{coord[0]}}" y="25"
style="fill: white;">{{label}}</text>
</svg>
</li>
</ul>
</div>
This is an example:
<svg>
<g ng-repeat="rect in rectList">
<rect ng-attr-fill="rect.fill"
ng-attr-x="rect.x"
ng-attr-y="rect.y"
ng-attr-width="rect.width"
ng-attr-height="rect.height"></rect>
</g>
</svg>
I want to add a <md-tooltip> to each of these rects. Can I do it somehow? I am talking about the Angular Material Tooltip specifically, not any other tooltip implementation from other libraries.
Try to wrap it in a div and apply the md-tooltip
<div ng-repeat="status in statuses">
<md-tooltip md-direction="right">
{{status.description}}
</md-tooltip>
<svg >
<rect width="300" height="100" >
</rect>
</svg>
</div>
Here is the working Sample
I want to add svg element line at runtime with ng-attr-x1={{some scope varaible}}.
I tried 2 ways:
In 1 way I tried with $compile:
var g=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "g"));
var line=$compile('<line ng-attr-x1={{$scope.array[array.length-1].x1}} ng-attr-y1={{$scope.array[array.length-1].y1}} ng-attr-x1={{$scope.array[array.length-1].x2}} ng-attr-x1={{$scope.array[array.length-1].y2}} style="with mandatory styling for line">')($scope);
g.append(line);
parentg.append(g);
In this method line is not showing and g is showing with 0px height and width.
In a 2 way I treid like :
var line=angular.element(document.createElementNS("http://www.w3.org/2000/svg", "line"));
line.attr('ng-attr-x1','scopeVariable');
line.attr('ng-attr-x2','scopeVariable');
line.attr('ng-attr-y1','scopeVariable');
line.attr('ng-attr-Y2','scopeVariable');
In this ng-attr attributes does not resolved to x and y. In DOM it shows as
This is possibly coming in way too late to help you, but I was stuck for a little while on the same question.
Turns out that $compile can take an element created with document.createElementNS() - like this:
var actApp = angular.module('actApp', []);
actApp.controller('shapeController', ['$scope', '$compile',
function shapeController($scope, $compile) {
$scope.color = 'green';
var svgEle = $(document.getElementById('mySvgElement'));
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', '0');
line.setAttribute('x2', '0');
line.setAttribute('x2', '20');
line.setAttribute('y2', '20');
line.setAttribute('style', 'stroke: {{color}};');
svgEle.append($compile(line)($scope));
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="actApp">
<div ng-controller="shapeController">
<input type="button" ng-click="color='blue'" value="To blue" />
<br />
<svg id="mySvgElement" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0" y="0" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
</svg>
</div>
</div>
Hope this saves someone a little bit of time in the future.
I came accross a strange behaviour when using SVG with AngularJS. I'm using the $routeProvider service to configure my routes. When I put this simple SVG in my templates, everything is fine:
<div id="my-template">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect fill="red" height="200" width="300" />
</svg>
// ...
</div>
But when I add a filter, with this code for instance:
<div id="my-template">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<filter id="blurred">
<feGaussianBlur stdDeviation="5"/>
</filter>
</defs>
<rect style="filter:url(#blurred)" fill="red" height="200" width="300" />
</svg>
</div>
Then:
It works on my homepage.
With Firefox, the SVG isn't visible anymore on the other pages, but it still leaves space where it would have been. With Chrome, the SVG is visible, but not blurred at all.
The SVG is visible again when I remove manually (with Firebug) the filter style.
Here is the routes configuration:
$routeProvider
.when('/site/other-page/', {
templateUrl : 'view/Site/OtherPage.html',
controller : 'Site.OtherPage'
})
.when('/', {
templateUrl : 'view/Site/Home.html',
controller : 'Site.Home'
})
.otherwise({
redirectTo : '/'
})
;
Fiddle
Please notice that I've failed to reproduce the problem with Chrome in a Fiddle, although it "works" with Firefox.
I've tried to no avail to create my whole SVG with document.createElementNS().
Does someone has an idea of what is happening?
The problem
The problem is that there is a <base> tag in my HTML page. Therefore, the IRI used to identify the filter is not anymore relative to the current page, but to the URL indicated in the <base> tag.
This URL was also the URL of my home page, http://example.com/my-folder/ for instance.
For the pages other than the home page, http://example.com/my-folder/site/other-page/ for example, #blurred was computed to the absolute URL http://example.com/my-folder/#blurred. But for a simple GET request, without JavaScript, and therefore without AngularJS, this is simply my base page, with no template loaded. Thus, the #blurred filter doesn't exist on this pages.
In such cases, Firefox doesn't render the <rect> (which is the normal behaviour, see the W3C recommandation). Chrome simply doesn't apply the filter.
For the home page, #blurred is also computed to the absolute URL http://example.com/my-folder/#blurred. But this time, this is also the current URL. There is no need to send a GET request, and thus the #blurred filter exists.
I should have seen the additional request to http://example.com/my-folder/, but in my defense, it was lost in a plethora of other requests to JavaScript files.
The solution
If the <base> tag is mandatory, the solution is to use an absolute IRI to identify the filter. With the help of AngularJS, this is pretty simple. In the controller or in the directive that is linked to the SVG, inject the $location service and use the absUrl() getter:
$scope.absUrl = $location.absUrl();
Now, in the SVG, just use this property:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<filter id="blurred">
<feGaussianBlur stdDeviation="5"/>
</filter>
</defs>
<rect style="filter:url({{absUrl}}#blurred)" fill="red" height="200" width="300" />
</svg>
Related: SVG Gradient turns black when there is a BASE tag in HTML page?
It looks like a behaviour I observed before. The root cause is that you end up having multiple elements (filters) with the same id (blurred). Different browsers handle it differently...
Here is what I did to reproduce your case: http://jsfiddle.net/z5cwZ/
It has two svg and one is hidden, firefox shows none.
There are two possibilities to avoid conflicting ids. First you can generate unique ids from your template (I can't help in doing it with angularjs tough). Here is an example: http://jsfiddle.net/KbCLB/1/
Second possibility, and it may be easier with angularjs, is to put the filter outside of the individual svgs (http://jsfiddle.net/zAbgr/1/):
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="0" height="0">
<defs>
<filter id="blurred">
<feGaussianBlur stdDeviation="10" />
</filter>
</defs>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" style="display:none">
<rect style="filter:url(#blurred)" fill="red" height="200" width="300" />
</svg>
<br/>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect style="filter:url(#blurred)" fill="red" height="200" width="300" />
</svg>
Just ran into this problem. Expanding from #Blackhole's answer, my solution was to add a directive that changes the value of every fill attribute.
angular.module('myApp').directive('fill', function(
$location
) { 'use strict';
var absUrl = 'url(' + $location.absUrl() + '#';
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
$attrs.$set('fill', $attrs.fill.replace(/url\(#/g, absUrl));
}
};
});
I recently ran into this issue myself, if the svg is used on different routes you will have to add the $location to each path.
A better way to implement this is to just use a window.location.href instead of the $location service.
Also had issues with svg link:hrefs, and yes the problem is because of the <base> - I had errors being thrown when concatenating the absolute url because of the Strict Contextual Escaping restrictions.
My solution was to write a filter that added the absolute url and also trusted the concatenation.
angular.module('myApp').filter('absUrl', ['$location', '$sce', function ($location, $sce) {
return function (id) {
return $sce.trustAsResourceUrl($location.absUrl() + id);
};
}]);
And then use it like this: {{'#SVGID_67_' | absUrl}
Result : http://www.example.com/deep/url/to/page#SVGID_67_ and no $sce errors
I am new both to AngularJS and SVG so if i am doing something terribly wrong i apologize.
I am trying to create an SVG pattern with AngularJS:
Code fiddle:
http://jsfiddle.net/WFxF3/
Template:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="grid" width="{{cubeWidth}}" height="{{cubeHeight}}" patternUnits="userSpaceOnUse">
<path d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<path d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>-->
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)"/>
</svg>
Controller:
'use strict';
angular.module('gridifyApp')
.controller('MainCtrl', function ($scope) {
var docWidth = document.width;
var columns = 12;
var cubeWidth = docWidth / columns;
var cubeHeight = 44;
$scope.cubeWidth = cubeWidth;
$scope.cubeHeight = cubeHeight;
});
It seems to work and yet I get a console error:
Any ideas why?
The problem is svg is being parsed before angular is able to do anything so the value with double curly braces is invalid before angular gets to it. Angular's team has added a way to define some kind of "delayed binding". You can use it by prefixing desired attribute with ng-attr-. It waits untill the binding evaluation is valid and adds real attribute with proper value.
In your case it would be:
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="grid" ng-attr-width="{{cubeWidth}}" ng-attr-height="{{cubeHeight}}" patternUnits="userSpaceOnUse">
<path ng-attr-d="M 0 0 L 0 {{cubeHeight}}" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<path ng-attr-d="M 0 0 L {{cubeWidth}} 0" fill="none" stroke="gray" stroke-width="1" stroke-opacity="0.5"/>
<!--<rect width="80" height="80" stroke="red" stroke-width="20" stroke-opacity="0.5" fill="white"/>-->
</pattern>
</defs>
<rect width="100%" height="100%" fill="url(#grid)"/>
</svg>
There should be no errors anymore. Remember to update your angular version.
SVG parsing happens before AngularJS can set any variable. You might try to create the SVG programmatically:
SVGSVGElement reference on MDN
Programmatically creating an SVG image element with JavaScript