I have a JSON file which contains multiple <br /> tags. The file is parsed using JSON.parse(json) into an object. Because I bind the data with AngularJS and ng-repeat I don't want that the strings have any HTML tags and replace it with a new line \n. How can I replace all tags? It seems to me that replace() only works with strings.
Thanks for your help!
JSON example
{
"title": "Title",
"description": "This<br />is<br />a<br />description."
}
JavaScript
var retrievedObject = JSON.parse(json);
$scope.data = retrievedObject;
HTML
<div ng-repeat="item in data">
{{item.description}}
{{item.description}}
</div>
You could just replace it before you parse the string
var retrievedObject = JSON.parse(json.replace(/\<br \/\>/g, ''));
A better option would be to parse the strings as HTML and extract the text without the tags, not using a regex before you insert them in the DOM
There's two ways to do what you're looking for. One with css where you replace the br's with
\n and then in your css file give the element the white-space property of pre-wrap.
The other is angularish. Take a read of data-ng-bind-html. You'd be able to actualy have the br's outputted. https://docs.angularjs.org/api/ng/directive/ngBindHtml You would have to run it through a filter of $sce so that it's trusted but your code would be as simple as:
<div ng-repeat="item in data">
<span data-ng-bind-html="item.description | trusted"></span>
<span data-ng-bind-html="item.description | trusted"></span>
</div>
your filter for trusted would be this:
.filter("trusted", function($sce){
return function(input){
return $sce.trustAsHtml(input);
}
});
ngBindHtml will let you keep keep the <br>s and render newlines in your HTML. It will automatically sanitize your input using ngSanitize to strip out any tags are aren't in its whitelist (you have to bring ngSanitize in as a dependency)...
var app = angular.module("app", ["ngSanitize"]);
The view is as simple as...
<div ng-bind-html="item.description"></div>
JsBin
You can also use $sce.trustAsHtml() to tell ngBindHtml to blindly trust the HTML without sanitizing, but only do that if you can completely trust its content (i.e., not for things like user submitted comments, etc).
Related
I have some values as amount like 1000, 2000, <b>3000</b>, <4000>, <b>5000</b> inside JSON as an API response. I want to render this response inside a table. So I tried ng-bind-html. BUT it is showing only the value which are having tags like 3000,5000. I want to show all values , 1000,2000,4000 as a plain string and 3000,5000 in BOLD/or any other HTML tag.
angular.forEach($scope.arr2.test,function(item)
$scope.res=$sce.trustAsHtml(item.amount);
return $scope.res;
});
On HTML side, I have something like this
<td id="price" class="edit" ng-repeat="pro in d.procedure" ng-bind-html="valueCheck(d._id,pro._id,hos._id)"></td>
You can use ng-bind-html and ng-bind-html-unsafe for this. But please be mindful of the security concerns here.
You can find more details here
Do make sure you sanitize your strings, to prevent security vulnerabilities
First of all you need to download the ng-sanitize js
https://docs.angularjs.org/api/ngSanitize
and then inject ng-sanitize to angular module.
then you can use ng-bind-html and ng-bind-html-unsafe
you can use ng-sanitize module for the same - see here
var app = angular.module("myApp", ['ngSanitize']);
I want to use handlebars to display a series of data in an unordered list, split between "title" and "articles." However, some of the articles will contain different HTML tags, be it <a> tags for link. If you take a look at my code below, when the data is appended to the DOM, rather than showing a link like 'You can read more about it here', it says the actual HTML anchor tags. Does anyone know a way around this?
<div id="myDiv"></div>
Consider the following template:
<script id="my-template" type="text/x-handlebars-template">
<div style='margin: 20px'>
<ul style='list-style-type: none; width:500px'>
<h4 style='padding:10px; overflow: auto'>General Credit</h4>
{{#each this}}
<li style='padding:10px; overflow: auto'>
<h3>{{title}}</h3>
<p>{{article}}</p>
</li>
{{/each}}
</ul>
</div>
</script>
My javascript looks like this:
//Data for Articles
var articleData = [
{
title: "My title here",
article: "You can learn more about it <a href='https://www.google.com'>here</a>"
}
];
//Get Template From Script Tag
var source1 = $("#my-template").html();
//Compile Template
var template1 = Handlebars.compile(source1);
$("#myDiv").append(template1(articleData));
You should use triple curly braces:
<li style='padding:10px; overflow: auto'>
<h3>{{{title}}}</h3>
<p>{{{article}}}</p>
</li>
So that handlebars doesn't escape the HTML code within your string.
Here the reference.
Cheers
You can use triple brackets to escape html.
Try {{{article}}}
Simple you {} {} helper call is a simple identifier, followed by zero or more parameters (separated by space). Each parameter is a Handlebars expression.
{{{link story}}}
In this case, link is the name of a Handlebars helper, and story is a parameter to the helper. Handlebars evaluates parameters in exactly the same way described above in "Basic Usage".
Reread the documentation more carefully. Simply put {{{}}} instead of {{}} around the article in my template, and the HTML tags render fine now.
Handlebars documentation: http://handlebarsjs.com/expressions.html
I have a problem using ng-style with ng-repeat.
This is my code:
<div style="display:table-row" ng-repeat="row in Data.Communications" id="{{row.Guid}}">
<div style="display:table-cell;">
<img ng-src="{{row.Path}}" ng-show="row.Path" ng-style="row.Style" />
<i class="{{row.Icon}}" ng-show="row.Icon" ng-style="row.Style"></i>
</div>
</div>
This is the JSON (Loaded server-side from a DB):
$scope.Data: {"LastUpdate":"23/03/2016 11:45","Communications":[{"Guid":"2","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"1","Path":null,"Icon":"fa fa-warning","Style":"{'color':'#ffff00'}"},{"Guid":"3","Path":"/images/blink_yellow.gif","Icon":null,"Style":"{'width':'15px', 'height':'15px'}"}]}
The "Style" is not applied to my elements. Could someone help me to solve this problem?
Basically you have strigified JSON, do parse it before assign it to ng-style
ng-style="doParseToJson(row.Style)"
Code
$scope.doParseToJson = function(style){
return JSON.parse(style);
}
Also make sure response should be wrap with " double qoutes instead of single quotes like '{"color":"#ffff00"}' to keep it valid for parsing the JSON.
I am trying to decode html entities from a string using and Angular JS filter.
I have a view that looks like the following:
<div class="roboto medium-gray">
<span class="item-description">{{item.description | plaintext}}</span>
</div>
As of right now I am applying a filter that strips tags:
.filter('plaintext', function() {
return function(text) {
return text ? String(text).replace(/<[^>]+>/gm, '') : '';
};
})
I am trying to determine a way where i can decode any html enties that are in there.
item.description is "A large house with wrap around porch & pool"
right now after item.description gets passed through the plaintext filter it comes out as:
A large house with wrap around porch & pool
I want it to replace the & with &
Thank you for help in advance.
You can use ng-bind-html, like so:
<div class="roboto medium-gray">
<span class="item-description" ng-bind-html="item.description | plaintext"></span>
</div>
For more information see official API Reference.
I have some html code rendered on the server side. This is passed to a jsp which renders a javascript-call with this html:
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", "${content}");
</script>
content is like
"
This is a <p class="xyz">test</p>
"
My problem is that - according to the quotes in 'content' - the javascript-call is wrong as it is rendered to
<script type="text/javascript">
window.parent.${param.popup_return}("ybc", "This is a <p class="xyz">test</p>");
</script>
Does anyone know how I can solve this (besides manually replacing all quotes)?
Use a JSON encoder to create the encoded strings.
But you'll also have to ensure that the output doesn't contain the sequence </ in string literals, which is invalid in a <script> block (</script is the version that will also break browsers).
Many JSON encoders either by default or optionally will encode to <\/ or \u003C/ to avoid this problem.
I use this:
<div id="result" style="display:none">
${content}
</div>
<script type="text/javascript">
window.parent.${param.popup_return}("${helpId}", dojo.byId("result").innerHTML);
</script>
This seems to work perfectly
You aren't using JSTL here (you originally tagged the question with only JSTL). You are using EL in template text. It get printed plain as-is. You'd like to use JSTL core <c:out> to escape predefined XML entities (which also works for HTML in this particular case, quotes is among the escaped XML entities).
window.parent.${param.popup_return}("<c:out value="${helpId}" />", "<c:out value="${content}" />");
An alternative (if you hate that the JSP syntax highlighter or validator bugs/jerks about nested tags/quotes) is the JSTL function fn:escapeXml():
window.parent.${param.popup_return}("${fn:escapeXml(helpId)}", "${fn:escapeXml(content)}");
Have you tried using single quotes instead of double quotes? i.e. changing "${content}" to '${content}'