I am new to AngularJS and just started learning it. How can I load the JSON file into the script.js file without directly adding the entire data.
Here is the code of the program:
<!DOCTYPE html>
<html ng-app="quizApp">
<head>
<meta charset="utf-8" />
<title>QuizApp</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<h1 class="title">QuizApp</h1>
<quiz/>
</div>
</body>
Plunkr.
You need to correct the json pasted in ques.json (by using quotes "") otherwise if you will invoke $http.get() then you will get exception due to invalid json.
Once you will correct the json content in ques.json then just use $http and assign the result to questions variable.
E.g.
app.factory('quizFactory', function($http) {
var questions = [];
$http.get('ques.json').success(function(data) {
questions = data;
})
return {
getQuestion: function(id) {
if(id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});
Here is the demo
$http.get('ques.json')
.then(function(result){
$scope.questions = result.data;
});
Related
I want to download this file and print its contents to the console using an in-browser IPFS node. The following html file should do the job:
<!doctype html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<script type='text/javascript' src='https://unpkg.com/ipfs#0.55.1/dist/index.min.js'></script>
<script type="text/javascript">
var ifile = 'Qmc3zqKcwzbbvw3MQm3hXdg8BQoFjGdZiGdAfXAyAGGdLi';
(async () => {
const inode = await Ipfs.create({
config: {
Addresses: {
Swarm: [
// These webrtc-star servers are for testing only
'/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star',
'/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star'
]
},
Bootstrap: []
}
})
window.inode = inode; //For poking
for await (const chunk of inode.cat(ifile)) {
console.log(chunk.toString());
}
})();
</script>
Testing IPFS file fetch
</body></html>
But it doesn't print anything. What am I missing?
You don't have any bootstrap nodes, so it can't find the CID. If you add my node for example, it works fine:
<!doctype html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<script type='text/javascript' src='https://unpkg.com/ipfs#0.55.1/dist/index.min.js'></script>
<script type="text/javascript">
var ifile = 'Qmc3zqKcwzbbvw3MQm3hXdg8BQoFjGdZiGdAfXAyAGGdLi';
(async () => {
const inode = await Ipfs.create({
config: {
Addresses: {
Swarm: [
// These webrtc-star servers are for testing only
'/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star',
'/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star'
]
},
Bootstrap: []
}
})
window.inode = inode; //For poking
await inode.swarm.connect("/dns6/ipfs.thedisco.zone/tcp/4430/wss/p2p/12D3KooWChhhfGdB9GJy1GbhghAAKCUR99oCymMEVS4eUcEy67nt");
for await (const chunk of inode.cat(ifile)) {
console.log(chunk.toString());
}
})();
</script>
Testing IPFS file fetch
</body></html>
Given the following html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<h2>Header</h2>
<figure>
<oembed url="https://www.youtube.com/watch?v=7km4EHgkQiw&list=RDQK-Z1K67uaA&index=9"></oembed>
</figure>
</body>
</html>
Why the page is not showing the youtube video?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<h2>Header</h2>
<figure>
<oembed url="https://www.youtube.com/watch?v=7km4EHgkQiw&list=RDQK-Z1K67uaA&index=9"></oembed>
</figure>
</body>
</html>
The body code was generated by CKEditor (I just removed the class "media" from the figure tag). You can see my original post here link
Solution tested for CKeditor 5
Save the exact view showing in CKeditor into DB use the below code
mediaEmbed: {
previewsInData:true
},
Full JS Code
var KTCkeditorDocument = function () {
// Private functions
var demo = function () {
ClassicEditor
.create( document.querySelector( '#kt-editor' ),{
mediaEmbed: {
previewsInData:true
},
}
)
.then( editor => {
// console.log( editor );
} )
.catch( error => {
// console.error( error );
Swal.fire("Info !", error, "error");
} );
}
return {
// public functions
init: function() {
demo();
}
};
}();
jQuery(document).ready(function() {
KTCkeditorDocument.init();
});
For more details you can check this link: https://ckeditor.com/docs/ckeditor5/latest/features/media-embed.html
The figure and oembed tags are not going to work to show a preview. In order to make it work I had to convert the youtube links to embeddable links and add them with an iframe.
To do so I used the solution proposed in this thread: link
function getId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return 'error';
}
}
var videoId = getId('http://www.youtube.com/watch?v=zbYf5_S7oJo');
var iframeMarkup = '<iframe width="560" height="315" src="//www.youtube.com/embed/'
+ videoId + '" frameborder="0" allowfullscreen></iframe>';
Im using Google charts API to load a pie chart from json file data
Here is where the chart is created (The HTML File) :
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "read.jsp",
dataType: "json"
});
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" ></div>aa
</body>
</html>
And here is the Read.jsp Used in url (ajax) :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.io.*, java.net.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Reading Text File</title>
</head>
<body>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data+"<br>");
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
</body>
</html>
And as a result I get this Error "Table has no columns" :
enter image description here
Anyone Know why please ? and thank you
by default, $.ajax is asynchronous,
need to wait on the done callback...
see following snippet...
function drawChart() {
$.ajax({
url: "read.jsp",
dataType: "json"
}).done(function (jsonData) {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
});
}
EDIT
also, remove all the html from the jsp file,
this should be all you need...
<%# page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8" import="java.io.*, java.net.*"%>
<%
String fileName = "/WEB-INF/json/test.json";
InputStream ins = application.getResourceAsStream(fileName);
try
{
if(ins == null)
{
response.setStatus(response.SC_NOT_FOUND);
}
else
{
BufferedReader br = new BufferedReader((new InputStreamReader(ins)));
String data;
while((data= br.readLine())!= null)
{
out.println(data);
}
}
}
catch(IOException e)
{
out.println(e.getMessage());
}
%>
I want to add a sort function to my factory controller in Angular JS.
I have got as far as what I have below:
var albumsApp = angular.module ('albumsApp',[])
albumsApp.factory('albumFactory',function($http) {
return {
getAlbumsAsync: function(callback,$scope){
$http.get('albums.json').success(callback);
},
};
});
albumsApp.controller ('albumController', function ($scope,albumFactory) {
albumFactory.getAlbumsAsync(function(results){
console.log('albumController async returned value');
$scope.albums = results.albums;
});
albumFactory.changeSorting(function(results){
console.log('changeSorting called');
});
});
I get an error "TypeError: albumFactory.changeSorting is not a function" (this refers to the albumFactory.changeSorting) as I have not added it to the factory. I don't know how to do this.
The html code I am using is below: I want to call the function to sort what is in the JSON file alphabetically
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="js/angular.js"></script>
<script src="js/angular-route.js"></script>
<script type="text/javascript" src="modules/app.js" ></script>
</script>
<title>
</title>
</head>
<body ng-app="albumsApp">
<div data-ng-controller="albumController">
<!-- <ul data-ng-repeat="album in albums| orderBy:'title'"> -->
<ul data-ng-repeat="album in albums">
<li>
Artist is "{{album.artist}}" and title is "{{album.title}}"
</li>
</ul>
<button data-ng-click="changeSorting()">Description</button>
</div>
</body>
</html>
The JSON list is below:
{
"albums":[
{
"artist": "Arctic Monkeys",
"title": "AM"
},
{
"artist": "Nirvana",
"title": "Nevermind"
},
{
"artist": "Buck 65",
"title": "Man Overboard"
}
]
}
Your view is not directly connected to the Angular service—all methods called from the view should be in your controller. You should have a method on your controller and not in your factory. Try moving that function to your controller:
albumsApp.controller ('albumController', function ($scope,albumFactory) {
albumFactory.getAlbumsAsync(function(results){
console.log('albumController async returned value');
$scope.albums = results.albums;
});
$scope.changeSorting = function (){
// your logic goes here
console.log('changeSorting called');
});
});
You can keep your logic in your controller. You can use orderBy in Angular's $filter module to help you sort:
$filter('orderBy')(array, expression, reverse)
I am trying to bind Json result to MVC 4.0 UI (cshtml) but looks like I am missing something...
Below are my controller and CSHtml page code snippet...
Could you please give me some pointers? as what I am missing or doing wrong ?
Please note that I am able to view the Json result (all rows) when I run the application... only thing is that it is not getting displayed per formatting mentioned below.
Sample of Json on UI that is getting displayed.
{"SomeCollection":[{"SequenceID":1,"Name":"test","LastName":"test2","SomeCollection":[]}
Controller
public JsonResult ShowJsonResult()
{
return Json(new { objSrv.SomeCollection }, JsonRequestBehavior.AllowGet);
}
CSHtml page
#model IEnumerable<Models.SmName>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ShowJsonResult</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//$('#btnGetPersons').click(function ()//{
$.getJSON("/Server/ShowJsonResult", null, function (data) {
var div = $('#ajaxDiv');
div.html("<br/> " + " testing: " + "<br/>");
$.each(data, function (i, item) {
printPerson(div, item);
});
});
//});
});
function printPerson(div, item) {
div.append("<br/>" + "Name: " + item.Name);
$.each(item.Addresses, function (i, addr) {
printAddress(div, addr);
});
}
function printAddress(div, item) {
div.append("<br/>" + " " + "Line1: " + item.Name);
}
</script>
</head>
<body>
<div>
<div id="ajaxDiv"></div>
</div>
</body>
</html>
The problem is with JSON object.The JSON that you have given cannot be parsed properly or not in correct format.Please recheck and try.