parse html within ng-repeat - html

I've been searching for hours now and I can't seem to find how to parse HTML code when retrieving using ng-repeat. I checked out $sce.trustAsHtml but I don't know how to apply it in my code.
html file:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<h2>My Links</h2>
<table class="table table-bordered">
<thead>
<tr>
<td>Name</td>
<td>URL</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="stuff in myStuff()">
<td>{{stuff.name}}</td>
<td>{{stuff.url}}</td>
</tr>
</tbody>
</table>
</div>
javascript
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.myStuff = function() {
return [
{
'name':'Google',
'url':'Google'
},
{
'name':'Yahoo',
'url':'Yahoo'
},
{
'name':'Microsoft',
'url':'Microsoft'
}
];
};
});
It's displaying the HTML source but I want it compile the code. Is my JS approach wrong? I'll be applying it to a json file using $http directive once I figure this out. Can anyone shed some light? I have my code at http://jsfiddle.net/s2ykvy8n/
Thanks.

Include ng-sanitize script and in your module add dependency.
var myApp = angular.module('myApp', ['ngSanitize']);
and just use ng-bind-html
<td ng-bind-html="stuff.url"></td>
and you are good to go:-
Plnkr
With what you are doing, the html in the binding will be displayed as textcontent in the element while processed by interpolation directive.

My first inclination (since from your example, you are just returning links) is to advise you to remove the html from your returned json and just return the url as a string.
Format:
{
'name': 'Google',
'url': 'http://google.com'
}
Then your HTML looks like this,
<tbody>
<tr ng-repeat="stuff in myStuff()">
<td>{{stuff.name}}</td>
<td>{{stuff.name}}</td>
</tr>
</tbody>
But, if you MUST have HTML strings in your json file, I would take a look at $compile. There are examples towards the bottom that can help you on how you can create a directive to compile your 'url' string to HTML

Related

Extract a value from a HTML response with Cheerio using Postman

I'm trying to get a value from request, that returns a HTML response, using Postman. I'm using Cheerio inside the script section.
The response looks like this:
<table class="etlsessions-table" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th class="someclass1">
<div>
<span>info1</span>
</div>
</th>
<th class="someclass2">
<div>
<span>info2</span>
</div>
</th>
<th class="someclass3">
<div>
<span>info3</span>
</div>
</th>
<th class="someclass2">
<div>
<span>info4</span>
</div>
</th>
</tr>
</thead>
<tbody>
<tr class="someclass5">
<td class="someclass">
<nobr>info5</nobr>
</td>
<td class="someclass6">
<nobr>info6</nobr>
</td>
<td class="someclass3">info7</td>
<td class="someclass7">
someurl1
</td>
</tr>
</tbody>
</table>
How I can get the info6 value from the someclass6 class?
As Cheerio is built-in to the Postman sandbox environment, you can use it to get the value of the element.
I'm not sure of your complete use-case but you could add something basic like this to the Tests script and print the value to the console:
const $ = cheerio.load(pm.response.text()),
elementValue = $('.someclass6 nobr').text();
console.log(elementValue)
To emphasis Danny was saying
Use the jQuery selector API to get different elements on the page reading dom
const $ = cheerio.load(pm.response.text());
console.log $('.someclass6 nobr').text(); //derive any element from class
which has value someclass6
Or you can write it like this
console.log($("td[class$='someclass6'] nobr").text()); //derive any text value within the td tag from the class which has the value someclass6
console.log($("td").attr('class')) //to fetch values from the attribute(s) of tag td
To store it as a collection variable in postman for useage in other api calls
const $ = cheerio.load(pm.response.text());
var storesomeclass6 = $('.someclass6 nobr').text();
pm.collectionVariables.set("someclass6", storesomeclass6 );
Postman is a software that will allow you to make calls to API endpoints, so basically your program will be written in node.js and you will call the endpoint with postman.
In this case and using cheerio, the code will look like something like this :
function getResponse() {
return fetch(`${YOUR API END POINT URL}`)
.then(response => response.text())
.then(body => {
const $ = cheerio.load(body);
const $info6= $('.someclass6 td );
const info6= $info6.first().contents().filter(function() {
return this.type === 'text';
}).text().trim();
const response= {
info6,
};
return response;
});
}
Best of luck !

Load JSON in gist into table using query

I'm attempting to load a series of json results on GitHub into a table. The gist can be found here. I've had a look at this question which helps with the population of the table. However, I'm having trouble retrieving the data from the gist.
I've modified the data section of the question as below
<script type="text/javascript">
var $table = $('#table');
$.getJSON('https://gist.githubusercontent.com/TheMightyLlama/9f4f1b4c2c078a6080c9212aba6beb59/raw/092fc02afcbd11ea26e7a08541b8dfae4748218a/News%2520Summary%2520Sample', function(mydata) {
});
$(function () {
$('#table').bootstrapTable({
data: mydata
});
});
</script>
And the table as below:
<div class="container">
<table id="table" data-height="460">
<thead>
<tr>
<th data-field="title">Title</th>
<th data-field="date">Date</th>
<th data-field="category">Category</th>
</tr>
</thead>
</table>
</div>
The variable mydata you used in getJSON function is local variable and that was just created at the time when that function called and can only usable within that function. Write the load table code inside getJSON
Here is JSFiddle Working Link
var $table = $('#table');
$.getJSON('https://gist.githubusercontent.com/TheMightyLlama/9f4f1b4c2c078a6080c9212aba6beb59/raw/092fc02afcbd11ea26e7a08541b8dfae4748218a/News%2520Summary%2520Sample', function(mydata) {
$('#table').bootstrapTable({
data: mydata
});
});

JQuery Datatable not loading Json data from MVC Controller

I have an Asp.Net MVC 5 web application. I am using JQuery Datatables v1.10.16 to display tabular data within one of the razor views. The data being returned to the datatable is via an ajax call and returning Json.
This is my razor view
<table id="data_table" class="display" style="width:100%">
<thead>
<tr>
<td>Evaluation ID</td>
<td>Applicant Name</td>
</tr>
</thead>
<tfoot>
<tr>
<td>Evaluation ID</td>
<td>Applicant Name</td>
</tr>
</tfoot>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#data_table').DataTable({
"ajax": '/EvalDashboard/GetEvaluationData',
"dataSrc": 'evaluations',
"columns": [
{ data: 'evaluationID' },
{ data: 'applicantName' }
]
});
});
</script>
This is my method which is called inside the controller EvalDashboard
public JsonResult GetEvaluationData()
{
var evaluations = _evalService.GetAllCecEvaluations(null, null)
.Take(20).Select(x => new
{
evaluationID = x.EvaluationID,
applicantName = x.tblcourseapplicant.FullName
}).ToList();
return Json(evaluations, JsonRequestBehavior.AllowGet);
}
When I run the app, I can see that the method GetEvaluationData() is being called, however, no data is returned to the datatable in the view, I only get a message saying Loading...
I'm not sure if the problem is because I'm returning an annonymous type inside my method.
Could someone please help?
Thanks.
The problem was that I had not included the keyword data inside the Json return statement like so:
return Json(new { data = evaluations }, JsonRequestBehavior.AllowGet);
This fixed the problem I was having.

Inserting HTML code when passing values to templates for given conditions

I have a table I am creating that looks like this:
<table>
<thead>
<tr>
<th>Value1</th>
<th>Value2</th>
<th>Value3</th>
<th>Value4</th>
</tr>
</thead>
<tbody>
{{#each []}}
<tr>
<td>{{this.val1}}</td>
<td>{{this.val2}}</td>
<td>{{this.val3}}</td>
<td>{{this.val4}}</td>
</tr>
{{/each}}
</tbody>
I want it to be the case that if val1, for instance, is greater than some value X, it will appear red.
How can I pass HTML into the template once some pre-defined condition - like the above example - is satisfied?
Ideally you should be driving this functionality using your models.
You could achieve the desired functionality using Marionette CollectionView. Each model in the collection should look something like:
var Model = Backbone.Model.extend({
initialize: function(){
/* On initialize, we call our method to set additional computed properties */
this.setProperty();
}
setProperty: function() {
if (this.get("someProperty") > x) {
this.set("className", "css-class")
}
}
});
Then from within your ItemView template you should be able to set the class on your table row item
<tr class="{{this.className}}">
<td>{{this.val1}}</td>
<td>{{this.val2}}</td>
<td>{{this.val3}}</td>
<td>{{this.val4}}</td>
</tr>

send data from two models of Mongoose inside Express.js to display in view list data

I have a Shopping Website I want to be able to display two model names "jeans" and "shirt" in a view
I need to pass data from two models I know how to access data from two models in one controller but I do not know how to send data from that controller
Controller:
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Shirt = mongoose.model('Shirt'),
Jeans = mongoose.model('Jeans');
exports.list = function(req, res) {
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Ajean = jeans;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
Ashirt = shirts;
});
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(all) {
// res.jsonp(Ashirt);
// res.jsonp(Ajean);
});
};
View:
<div class="list-group">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Color</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="item in items">
<td data-ng-bind="item.name"></td>
<td data-ng-bind="item.color"></td>
</tr>
</tbody>
</table>
</div>
I know that I cannot use "res.jsonp();" more than once .
when I use "Ajean" it give me data for "jeans" and
when I use "Ashirt" it give me data from "shirts" model
But I want to be able to show both data from both "shirt" model and "jean" model
How Can I do That?
Do I need to merge two Json?
How should I change my view to see that data?
Thanks!
You could try nesting the queries and then merge the resulting arrays with Array.concat:
Jeans.find().sort('-created').populate('user', 'displayName').exec(function(err, jeans) {
Shirt.find().sort('-created').populate('user', 'displayName').exec(function(err, shirts) {
var all = shirts.concat(jeans);
res.jsonp(all);
});
});