How to add span element to json data? - javascript

I have a problem with JSON data. I want to add a span element inside a string, but it doesn't work. How to ''escape'' string? Below is an example.
{
"text": "Copyright©2020 <span class="test">Gamepix</span> All Rights Reserved."
}

If you're using Typescript you can use in your HTML file [innerHTML].
Example:
<div [innerHTML]="text"></div>
in your typescript file:
text: string = "some text here <span class='yellow'>six pieces</span>, and here";
and in your .scss file:
::ng-deep .yellow {
color: #f5dc27;
}

I know I'm a bit late to this question but I just worked this out for myself! The "render" function takes my data in the JSON key "data" and returns the data in "dataname" as well as my desired html tag (span). Hope this helps!
{
"data": "dataname", render: function (data) {
return data + '<span></span>';
}
},
"Other data keys to follow"
{
},

Related

How to apply json content for html attribute

I am trying to add json object for html arrtibute content but not working.I have tried many ways but I do not know how to set that.if any one know about that please help to resolve this issue.
javascript:
var validatorValue='{
"picker":{
"allow":
{
"message": "Content loram ipsom"
},
"past":
{
"message": "lorem issom"
}
}
}' ;
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html("<div input="true" validator='+validatorValue+' date-restrict='+daterestrictValue+' my-input='+myinputValue+'></div>");
The main issue with your code (aside from line-breaks in string literals) it the mis-matched quotes in the HTML string you build. However, even after correcting those you will have issues placing serialised JSON within attributes as it too contains double quotes which will break the HTML syntax.
Also note that you're creating non-standard attributes in the HTML you create which may cause unexpected issues in your UI and JS.
An alternative way to approach this is to work with the values as objects (instead of strings). You can use jQuery to set the data of the element using those objects, like this:
var validatorValue = { "picker": { "allow": { "message": "Content loram ipsom" }, "past": { "message": "lorem issom" } } }
var daterestrictValue = { 'range': { 'start': '2019-10-30', 'end': '2019-12-30' } }
var myinputValue = { 'date': 'tomorrow' };
var $newDiv = $('<div data-input="true">Click me</div>').appendTo('#mydiv');
$newDiv.data({
"validator": validatorValue,
"date-restrict": daterestrictValue,
"my-input": myinputValue
});
// for testing
$('#mydiv div').on('click', function() {
console.log($(this).data('validator'));
console.log($(this).data('date-restrict'));
console.log($(this).data('my-input'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
this code save object in html element.
good luck
var validatorValue="{ 'picker':{'allow':{'message': 'Content loram ipsom'},'past':{'message': 'lorem issom'}}}";
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html(`
<div input='true' validator="${validatorValue}" date-restrict="${daterestrictValue}" my-input="${myinputValue}">ggg</div>`);

How can I access array element value in json

I'm not able to access _sValues in my html page, however i can able to console.log the interested _sValues array element in console.
JSON
[
{
"_this":{
"_isEvent":false,
"_sNames":[
"name",
"tag",
"notes",
"input",
"type",
"action"
],
"_sValues":[
"Testing01",
"#13",
"1504013826",
"No details",
"cType",
"NA"
],
"_cName":"namesList",
"_dName":"TEST",
"_id":"12345",
}
}
]
HTML
<th class="col-md-5 col-xs-5" data-field="_this._sValues[1]" data-sortable="true">S-VALUES</th>
I would like to see #13 displayed on the page instead i don't see any values or console error. However i can display all values by doing _this.sValues
SCRIPT
var data;
$(function () {
$.getJSON("http://localhost:8080/services/webapi/getAllData", function(json){
data = json;
$('#table').bootstrapTable({
data: data
});
});
});
DEV TOOL
data[0]._this._sValues[1]
"#13"
In your case,
i assume you only have one row.
$(".col-md-5").attr("data-field",data[0]._this._sValues[1]);
It will inject the data to html.
If you have multi row, you can use for loop.
I believe you have a silent error. It has to do with the trailing comma in your data object.
"_id":"12345",
// should be
"_id":"12345"
That's all I noticed. I Courbet wrong but I know trailing commas mess with some browsers.

PolymerJS POST JSON formatting

I am trying to POST using PolymerJS ajax-forms and I encounter a weird JSON format error. Can someone tell me why the quotes are missing around the keys? The only workaround I can think of is manually constructing the body with the quotes around the keys.
Code Snippet :
How I receive the values (rest are the same with the ids changed):
<div>
<paper-input label="Title" id="course-title" floatingLabel value="{{item.title}}"></paper-input>
</div>
<access-core-ajax
auto = "false"
url="domain/courses"
response="{{response}}"
method="post"
id="postCourse"
contentType="application/json"
headers='{"Accept": "application/json", "Content-Type":"application/json"}',
body = "{{item}}">
<template id="get-response-template" repeat="{{item in response.entries}}">
<p>Errors</p>
</template>
</access-core-ajax>
Polymer('create-new-course-page',{
domReady: function() {
console.log("Log: create-new-courses-page - Looks like we are domReady");
},
created: function() {
console.log("Item initialized");
this.item = {};
this.data={};
},
createNewCourse: function(event) {
console.log("HERE IS BODY", this.item);
this.$.postCourse.go();
}
And the JSON is see on the log:
{
title: "WRU",
// rest of key & values, where the keys are without the ""
}
You need to turn the body into a JSON string first. JSON.stringify can help.
...
createNewCourse: function(e) {
this.$.postCourse.body = JSON.stringify(this.item);
this.$.postCourse.go();
}
You may need to remove the body attribute here. You can also remove that auto attribute since by default it is false.

How to use function in Kendo Grid Column Template with AngularJS

I have a column in a Kendo grid that I want to perform some specific logic for when rendering, and am using Angular. I have the grid columns set up using the k-columns directive.
After looking at the documentation, it seemed simple: I could add the template option to my column, define the function to perform my logic, and pass the dataItem value in. What I have looks something like this:
k-columns='[{ field: "Name", title: "Name",
template: function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}
}]'
However, running this causes a syntax error complaining about the character '{' that forms the opening of the block in my function.
I have seen several examples of defining a template function in this format. Is there something else that needs to be done for this to work? Am I doing something incorrectly? Is there another way of defining the template as a function and passing the column data to it? (I tried making a function on my $scope, which worked, except I couldn't figure out how to get data passed into the function.)
Thank you for your help.
It appears that defining a column template in this fashion isn't supported when using AngularJS and Kendo. This approach works for projects that do not use Angular (standard MVVM), but fails with its inclusion.
The workaround that a colleague of mine discovered is to build the template using ng-bind to specify a templating function on the $scope, all inside of a span:
template: "<span ng-bind=templateFunction(dataItem.Name)>#: data.Name# </span>"
This is the default column templating approach that is implemented by Telerik in their Kendo-Angular source code. I don't know yet if the data.Name value is required or not, but this works for us.
Warning: Don't have access to Kendo to test the code at the moment, but this should be very close
In your case, you are assigning a a string to the value of k-columns and that string contains the the word function and your curly brace {
You need to make sure the function gets executed ... something like this:
k-columns=[
{
field: "Name",
title: "Name",
template: (function (dataItem){
// Perform logic on value with dataItem.Name
// Return a string
}())
}
];
Note the difference:
We create an object -- a real honest-to-goodness object, and we use an IIFE to populate the template property.
Maybe, it will be useful for someone - this code works for me too:
columns: [
{
field: "processed",
title:"Processed",
width: "100px",
template: '<input type="checkbox" ng-model="dataItem.processed" />'
},
and you get the two-way binding with something like this:
<div class="col-md-2">
<label class="checkbox-inline">
<input type="checkbox" ng-model="vm.selectedInvoice.processed">
processed
</label>
</div>
This can be done via the columns.template parameter by supplying a callback function whose parameter is an object representing the row. If you give the row a field named name, this will be the property of the object you reference:
$("#grid").kendoGrid({
columns: [ {
field: "name",
title: "Name",
template: function(data) {
return data.name + "has my respect."
}
}],
dataSource: [ { name: "Jane Doe" }, { name: "John Doe" } ]
});
More information is available on Kendo's columns.template reference page.
After hours of searching. Here is the conclusion that worked:
access your grid data as {{dataItem.masterNoteId}} and your $scope data as simply the property name or function.
Example
template: '<i class="fa fa-edit"></i>',
I really hope this safes somebody life :)
just use like my example:
}, {
field: "TrackingNumber",
title: "#T("Admin.Orders.Shipments.TrackingNumber")",
//template: '<a class="k-link" href="#Url.Content("~/Admin/Shipment/ShipmentDetails/")#=Id#">#=kendo.htmlEncode(TrackingNumber)#</a>'
}, {
field: "ShippingMethodName",
title: "#T("Admin.Orders.Shipments.ShippingMethodName")",
template:function(dataItem) {
var template;
var ShippingMethodPluginName = dataItem.ShippingMethodPluginName;
var IsReferanceActive = dataItem.IsReferanceActive;
var ShippingMethodName = dataItem.ShippingMethodName;
var CargoReferanceNo = dataItem.CargoReferanceNo;
var ShipmentStatusId = dataItem.ShipmentStatusId;
if (ShipmentStatusId == 7) {
return "<div align='center'><label class='label-control'><b style='color:red'>Sipariş İptal Edildi<b></label></div>";
} else {
if (ShippingMethodPluginName == "Shipping.ArasCargo" || ShippingMethodPluginName == "Shipping.ArasCargoMP") {
template =
"<div align='center'><img src = '/content/images/aras-kargo-logo.png' width = '80' height = '40'/> <label class='label-control'><b>Delopi Aras Kargo Kodu<b></label>";
if (IsReferanceActive) {
template =
template +
"<label class='label-control'><b style='color:red; font-size:20px'>"+CargoReferanceNo+"<b></label></div>";
}
return template;
}

Convert JSON Array to HTML wrapped String - Angular Service

I'm trying to use a wysiwyg in my angular app. What I want to happen is, I query an end point for an array of objects. Then based on the property name the data inside it gets wrapped into a different html tag. Then all the data is concatenated into a string which gets displayed on a wysiwyg in my app.
So JSON that looks like
[
{
"name": "steve",
"age": 33,
"profile": "http://www.profile.com/steve",
"location": "New York"
},{
"name": "john",
"age": 25,
"profile": "http://www.profile.com/john",
"location": "LA"
},
]
Spits out:
"<b>Steve - New York</b>
<br>
<a href='http://www.profile.com/steve'>Url</a>
<br>
<span>33</span>
<br>
<br>
<b>John - LA</b>
<br>
<a href='http://www.profile.com/john'>Url</a>
<br>
<span>25</span>
<br>
<br>"
While this part isn't Angular specific. I think I need to add this code into a service so that it can be reused whenever I would need it an an app.
I'm not sure what this code would look like. Any ideas?
EDIT: For clarification the reason why I'm doing this is because the page has a WYSIWYG on it. A non-technical user needs to be able to edit the data in the WYSIWYG then click a button and the app exports a PDF. The WYSIWYG requires a single string with HTML tags as does the backend of the app which generates the PDF file.
It seems to me that there's really no reason to reinvent the wheel here... why can't you just use a fully supported WYSIWYG editor like TinyMCE? It's got an angular extension through the Angular-UI project here:
https://github.com/angular-ui/ui-tinymce
Then you could write this in your html:
<textarea ui-tinymce="tinyMceOptions" ng-model="parsedResponse"></textarea>
<button ng-click="convertToPdf()">Y U NO DOWNLOAD PDF?</button>
In your controller (or directive):
$scope.tinyMceOptions = {/*Customize here*/};
$scope.parseMyResponse = function(data) {
// do something with data and return as html string
return data;
};
$http.get('/your/resource/url').success(function(result) {
$scope.parsedResponse = $scope.parseMyResponse(result);
});
$scope.convertToPdf = function() {
// do something with $scope.parsedResponse here to get a PDF
};
Edit:
I guess I didn't get what you were asking exactly at first? If you want it in a service all you have to do is something like:
angular.module('app')
.service('Util', function() {
return {
wrapInTag: function(tagName, value) {
return '<' + tagName + '>' + value + '<' + tagName + '/>';
},
parseMyResource: function(response) {
htmlString = '';
angular.each(response, function(item) {
htmlString += this.wrapInTag('h1', item.title);
htmlString += this.wrapInTag('b', item.id);
// Other manipulation...
});
return htmlString;
}
};
});
Then in your controller:
angular.module('app')
.controller('MyCtrl', function(Util){
// Use Util functions here...
});
I've given you some example code for parsing JSON into HTML strings, but I'm afraid I couldn't be more specific as to how to write it. The logic if your parsing function really depends on what you're trying to accomplish as well as what your data model looks like. There's really no straight-forward way to convert JSON to HTML.

Categories

Resources