Storing images into an array - javascript

I am trying to create a searchable array in JS. I want the arrays to work as only the images show, then using 'tags' to filter and search this array.
If I were to have something along the lines of this:
function NotebookListCtrl($scope) {
$scope.notebooks = [
{"name": "Lenovo",
"processor": "Intel i5",
"age": 2011},
//more notebooks...
{"name": "Toshiba",
"processor": "Intel i7",
"age": 2010},
];
$scope.orderList = "name";
}
Is there a way I can use something along the lines of...
notebooks[0] = new Image();
notebooks[0].src = 'images/img/image1.jpg';
So when notebooks item [0] is displayed, it will show the image along with it?
Relatively new to JS and am trying to piece something together. Thanks for the help!

My advice would be avoid using Image object, unless you need to pre-load your images in your JS code, and only store the img src path for each product in your array like in:
$scope.notebooks = [
{"name": "Lenovo",
"processor": "Intel i5",
"age": 2011
"img": "images/img/image1.jpg"
},
// ...
Then in your img tag you can just point to the source of each product accordingly.
You can configure your web server to tell the browser to cache the images so it would enhance img loading time.

No need to create a new image. This has more to do with html and displaying of the image than anything else:
function NotebookListCtrl($scope) {
$scope.notebooks = [
{"name": "Lenovo",
"processor": "Intel i5",
"age": 2011,
"src": 'images/img/image1.jpg'
},
//more notebooks...
{"name": "Toshiba",
"processor": "Intel i7",
"age": 2010,
"src": 'images/img/image2.jpg'
},
];
$scope.orderList = "name";
}
<div
ng-repeat="notebook in notebooks | orderby: orderList">
<p>name: {{notebook.name}}</p>
<p>processor: {{notebook.processor}}</p>
<p>age: {{notebook.age}}</p>
<img
ng-if="notebook.src"
ng-src="{{notebook.src}}">
</div>
Just set the image source and use the ng-src attribute in html to set the image source.

Related

Tabulator: load data from a JSON file

I want Tabulator to automatically load data from a JSON file.
I have made it work with a button.
I have read the q & a here
Load table data from text file
I have also read the documentation here.
http://tabulator.info/docs/4.4/data#array-initial
(By the way, I was expecting the ajaxURL documentation to show a URL ending with a FILE name rather than "/now"... something like $("#div1").load("demo_test.txt"); )
I'm not a professional developer so please be gentle with me.
Here is the content of the JSON file (called "test_Array.txt" and in the same directory as the HTML).
[
{"name": "Oli Bob", "age": "12", "col": "red", "dob": "14/05/1982"},
{"name": "Mary May", "age": "1", "col": "blue", "dob": "14/05/1982"},
{"name": "Christine Lobowski", "age": "42", "col": "green", "dob": "22/05/1982"},
{"name": "Brendon Philips", "age": "125", "col": "orange", "dob": "01/08/1980"},
{"name": "Margret Marmajuke", "age": "16", "col": "yellow", "dob": "31/01/1999"}
]
It passes validation at
https://jsonlint.com/
Here is the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/tabulator-tables#5.1.3/dist/css/tabulator_site.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#5.1.3/dist/js/tabulator.min.js"></script>
<meta charset="utf-8" />
<title>tabulator3</title>
</head>
<body>
<div id="example-table"></div>
<script>
//create Tabulator on DOM element with id "example-table"
var table = new Tabulator("#example-table", {
height:205,
// set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
//layout:"fitDataFill",//fit columns to fit data and width of table (optional)
//data:tableData, //set initial table data
columns:[ //Define Table Columns
{title:"Name", field:"name", width:150},
{title:"Age", field:"age", align:"left", formatter:"progress"},
{title:"Favourite Color", field:"col"},
{title:"Date Of Birth", field:"dob", sorter:"date", align:"center"},
]
});
//load sample data into the table
table.setData("test_Array.txt")
</script>
</body>
</html>
What am I doing wrong?
Thank you.
To start off I would say you have posted a link to the v4.4 documentation, but using version 5.1 of Tabulator. It is defo worth reading the correct docs to get started :)
Following on from that the issue that you are experiencing is because as of version 5.0 Tabulator now has an async start up process that means you cant just call setData straight after instantiating the table, you must wait for the tableBuilt event:
table.on("tableBuilt", function(){
table.setData("./test_Array.txt");
});
More importantly if you are just loading data straight from the file then there is no need to set data after the table has been built, you can use the ajaxURL setup option to load the data into the table while it is being built:
var table = new Tabulator("#example-table", {
ajaxURL:"./test_Array.txt",
... other table options
});
As a complete aside if the text file just contains JSON data, then the convention is to end the file with .json instead of .txt
For any other novices/amateurs out there....following Oli's advice I have a working solution as follows:
Create a JSON file called text_Array.json with the following content:
[
{"name": "Oli Bob", "age": "12", "col": "red", "dob": "14/05/1982"},
{"name": "Mary May", "age": "1", "col": "blue", "dob": "14/05/1982"},
{"name": "Christine Lobowski", "age": "42", "col": "green", "dob": "22/05/1982"},
{"name": "Brendon Philips", "age": "125", "col": "orange", "dob": "01/08/1980"},
{"name": "Margret Marmajuke", "age": "16", "col": "yellow", "dob": "31/01/1999"}
]
Create an html file called tabulator3.html with the following content. Put the JSON file in the same folder as the HTML file and it will work :
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://unpkg.com/tabulator-tables#5.1.3/dist/css/tabulator_site.min.css" rel="stylesheet">
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#5.1.3/dist/js/tabulator.min.js"></script>
<!-- the line below is necessary for the Date sorter to work - it is buried in the v5.1 documentation here
http://tabulator.info/docs/5.1/sort#func-builtin -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.3.1/luxon.min.js"></script>
<meta charset="utf-8" />
<title>tabulator3</title>
</head>
<body>
<div id="example-table"></div>
<script>
//create Tabulator on DOM element with id "example-table"
var table = new Tabulator("#example-table", {
ajaxURL:"test_Array.json", //load sample data into the table
height:205,
columns:[ //Define Table Columns
{title:"Name", field:"name", width:150},
{title:"Age", field:"age", hozAlign:"left", formatter:"progress"},
{title:"Favourite Color", field:"col"},
{title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
]
});
</script>
</body>
</html>
Thanks, Oli!

AngularJS Carousel Menu

Got a question regarding AngularJS and a carousel menu. I've made an array and I have trouble inserting the data in my View.
Controller:
gameApp.controller('homeController', function($scope) {
// Gamemodelist is static. Put all the corresponding gamemodes in an array
$scope.gameModeList = [
{"name": "Waterworld", "contents": [
{"name": "Classic", "contents": [
{"name": "Level 1", "contents": [{"name": "beginner"}, {"name": "easy"},{"name": "intermediate"}, {"name": "ultimate"}]},
{"name": "Level 2", "contents": [{"name": "easy"}]}
]},
{"name": "Firemode", "contents": [
{"name": "Level 3", "contents": [{"name": "beginner"}]}
]},
{"name": "Watermode", "contents":[
{"name": "Level 4", "contents": [{"name": "introduction"}]}
]}
]},
{"name": "Fireworld", "contents": [
{"name": "Classic", "contents": [
{"name": "Level 1", "contents": [{"name": "Intro"}, {"name": "Beginner"}, {"name": "Intermediate"}]},
{"name": "Level 2", "contents": [{"name": "Beginner"}, {"name":"Intermediate"}]}
]},
{"name": "Fireworld", "contents": [
{"name": "Level 3", "contents": [{"name": "Beginner"}, {"name": "Intermediate"}]}
]}
]},
{"name": "Tutorial", "contents": [
{"name": "Basic Tutorial"}, {"name": "Battle Training"}
]}];
}
This array is basicly the menu itself. You see the first items in the array are the first items in the menu. And every array in the contents is the submenu and if there is a subsubmenu.
This is my controller. Now I'm new to Angular, and I've already mate routing and templating work. Got different controllers for the login screen and the options screen. But now I'm working on the homescreen, which features a menu and I'm quite uncertain what's my best step here. I've already decided that I don't want to use different pages like I'm doing with my login and options screen, because I feel that an array is more convenient, because it already features the ordering of the items and it's (imo) a bit more managable.
To the view then. I've already checked and I think I need to use ng-if to check if there are submenu's in the array and if so use ng-repeat to display the menu. But. I come from jQuery background, so my instinct was to display the list and make it work with CSS and jQuery to manipulate the DOM so the items are shown which I want them to show, I know (for sure) that thats how things work in Angular. I guess I need to check with the controller which items need to display?
<ul>
<li class="animate-repeat" ng-repeat="mode in gameModeList">
{{ mode.name }}
</li>
</ul>
Now I only get the first items in the list obviously. I guess I now have to get the contents of the item I click in the view?

D3.js JSON parse error

While parsing inline JSON object with d3.json(obj, function(error, root), its working properly when I'm running it locally, but when I run on tomcat server I'm getting an XMLHttpparse error. I searched over the Internet. Answer that I found was CORS. But there was no clarity how to achieve this. Could you please help me?
var obj = {
"name": "vis",
"children": [
{
"name": "Votes",
"children": [
{"name": "200", "size": 200,"url":"1"},
{"name": "500", "size": 500,"url":"2"},
{"name": "300", "size": 300,"url":"3"},
{"name": "400", "size": 400,"url":"4"}
]
},
{
"name": "Reputation",
"children": [
{"name": "200", "size": 200},
{"name": "500", "size": 500},
{"name": "300", "size": 300},
{"name": "400", "size": 400}
]
},
{
"name": "Accepted Answer",
"children": [
{
"name": "encoder",
"children": [
{"name": "Accepted Answer", "size": 500}
]
}
]
}
]
};
d3.json(obj, function(error, root) {
alert('error '+error);
alert('root: '+root);
if (error) return console.log(error);
}
First, make sure you are passing in a URL as the first argument to d3.json().
Second, you need to configure Tomcat to support CORS. In version 7.0.41+, Tomcat includes a CORS filter. Add the filter to your web.xml file.
Here's the minimum configuration you need:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
See the documentation for more information and additional configuration options: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter
And here's a flowchart of request processing for this filter that may help you with setting up any additional parameters:
You are misunderstanding what d3.json is used for. d3.json makes an actual AJAX request (hence why in the documentation names the chapter as Requests) so it is literally trying to fetch that obj but can't because it doesn't need to. If you really want to use d3.json, you can move that JSON object into its own file and then reference it by doing d3.json(data.json, function(err, root)).
The result d3.json would return is literally the object you have declared. You can simply assign it to the variable name root.
Related question: d3 js - loading json without a http get

Generate layout histogram with specified parent values

I am new to D3, so my project of D3 is a rough problem to me and I really do need some help, I have been search solutions for days.
The problem is, I want to draw a Hierarchical Bar Chart, every time one clicks a bar, the sub layout of that bar is shown, just like this one http://bl.ocks.org/mbostock/1283663, however, the value of parent node is the sum value of its children node. I want to set the parent value by myself and keep the layout. The json file is:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
{"name": "HierarchicalCluster", "size": 6714},
{"name": "MergeEdge", "size": 743}
]
},
I want to edit the parent value, so I edit the file as :
{
"name": "flare",
"children": [
{
"name": "analytics",size:555555 //I want to set value by myself rather than the sum of children value
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
{"name": "HierarchicalCluster", "size": 6714},
{"name": "MergeEdge", "size": 743}
]
},
However, it does not work. Does anyone knows how to set parent's value? I searched for days and got nothing, hope you can help me, and I am appreciate your help!
Is your issue with using the parent element sizes to draw the bars? If so, you should scale everything (to say 0 to 100) and then multiply this by a constant to get the appropriate parent value. After all, if you edit each parent value, they won't necessarily be proportional.
Here's an example of a scale:
edit: (fixed the domain)
var myscale = d3.scale.linear()
.domain([0, maxParentWidth])
.range([0,y]); // .range([0,1]) is the default range
This will scale all the "parents" on the domain 0 to the largest parent value to a range of [0,y], where y is whatever you want (i.e., 100). Let's say you want the largest parent bar to be 300px. Now, all you have to do is multiply this scaled value by a constant, in this case, 3.

D3 javascript color from JSON attribute

Using D3 Javascript and JSON, I need to create something very similar to:
http://bl.ocks.org/mbostock/4063550
The JSON file (copied from website) looks something like:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "size": 3938},
{"name": "CommunityStructure", "size": 3812},
{"name": "HierarchicalCluster", "size": 6714},
{"name": "MergeEdge", "size": 743}
]
},
Now instead of the "size" in the code above, I have "score" (i.e. "score": 3).
What I want to achieve is the diagram similar to the website, but the difference is that is the score is over a certain threshold (e.g >5), I want the small blue circle to be of a certain color (i.e. red).
I know this needs to be updated in the index.html file, but I just don't know how to get around to doing that. Any pointers would be appreciated!
Thanks!
All you need to do this is to slightly modify the code that appends the circles. You need to change the snippet
node.append("circle")
.attr("r", 4.5);
to
node.append("circle")
.style("stroke", function(d) { return d.score > 5 ? "red" : "steelblue"; })
.attr("r", 4.5);
You can obviously apply something like this to e.g. the fill colour in the same way. If you have a larger number of different colours and thresholds, it might be worth investigating using a scale instead of a conditional statement.
Change your JSON like so:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{"name": "AgglomerativeCluster", "score": 3938},
{"name": "CommunityStructure", "score": 3812},
{"name": "HierarchicalCluster", "score": 6714},
{"name": "MergeEdge", "score": 743}
]
},
Now use a function to check for the condition in the data and set the style for the circle:
node.append("circle")
.attr("r", 4.5)
.style("fill",function(d){
return ((d.score > 5)?"red":"blue");
});

Categories