AngularJS rendering from deeply nested jsonp - javascript

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??

You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

Related

How to generate a jstree using AJAX?

I have been having problems generating a JsTree using data from my server. I have tried different formats and appending an existing tree, no dice. The only thing that happens is that it the jstree div gets replaced by
<div id="jstree" class="jstree jstree-1 jstree-default jstree-leaf" role="tree" aria-multiselectable="true" tabindex="0" aria-activedescendant="j1_loading" aria-busy="false"><ul class="jstree-container-ul jstree-children" role="group"></ul></div>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsTree test</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
</head>
<body>
<div id="jstree">
</div>
<script>
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/treeTest2",
dataType : "json",
success : function(json) {
// alert(JSON.stringify((json)));
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#jstree").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) {
alert(e);
});
}
</script>
</body>
</html>
Heres what the alert(JSON.stringify((json))); returns
[
{
"a_attr": {
"id": 1
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 3
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 5
},
"text": "lvl3",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 4
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 2
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
The metadata tag is needed for data that will be needed later. Everything will be otganised into folders and snipplets. And the id tag will be used in hyperlinks.
I believe id="jstree" conflicts with the global variable jstree.
Indeed, If you give an ID to an element, this element is directly available in JS, without doing anything :
myGreatDiv.innerHTML = "It works"
<div id="myGreatDiv"></div>
So, you include the JsTree library, which defines window.jstree.
Then, you create a div with id="jstree", which automatically overwrites window.jstree.
Solution (I guess) : call your div something else, like
<div id="jstree_div">
Here's the solution.
function createJSTrees(jsonData) {
$("#kautkas").jstree({
'core' : {
'data' : jsonData
}
});
}

Surveyjs choicesOrder random except some value

I have a problem with choices order in surveyjs, I want to make random choices order except 1 value (example: camel) always at bottom.
var json = {
"elements": [{
"type": "imagepicker",
"name": "Picture",
"title": "What animal would you like to see first ?",
"choices": [
{
"value": "lion",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/lion.jpg"
}, {
"value": "giraffe",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/giraffe.jpg"
}, {
"value": "panda",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/panda.jpg"
}, {
"value": "camel",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/camel.jpg"
}]
}]};
window.survey = new Survey.Model(json);
var q = survey.getQuestionByName('Picture');
q.choicesOrder = "random";
q.showLabel = "true";
I've created an example with your code and latest SurveyJS. It looks ok for me.
Could you please try to update SurveyJS version to the latest. Thanks.
Survey
.StylesManager
.applyTheme("default");
var json = {
"elements": [{
"type": "imagepicker",
"name": "Picture",
"title": "What animal would you like to see first ?",
"choices": [
{
"value": "lion",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/lion.jpg"
}, {
"value": "giraffe",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/giraffe.jpg"
}, {
"value": "panda",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/panda.jpg"
}, {
"value": "camel",
"imageLink": "https://surveyjs.io/Content/Images/examples/image-picker/camel.jpg"
}]
}]};
window.survey = new Survey.Model(json);
var q = survey.getQuestionByName('Picture');
q.choicesOrder = "random";
q.showLabel = "true";
$("#surveyElement").Survey({model: survey});
<!DOCTYPE html>
<html>
<head>
<title>One choice - Radio Group question, jQuery Survey Library Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/jquery"></script>
<script src="https://surveyjs.azureedge.net/1.0.53/survey.jquery.js"></script>
<link href="https://surveyjs.azureedge.net/1.0.53/survey.css" type="text/css" rel="stylesheet"/>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div id="surveyElement"></div>
<div id="surveyResult"></div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>

get value of angular js expression in window.alert in angularJs

Hi I am trying to alert the value of an expression in angularJs
I am quite new to angular and am just trying to work out how grab the value of the expression in an alert or in the console.
I am using AngularJs with json, below is my code
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="menu in menus" id="{{menu.id}}" class="{{menu.cssClass}}">
<a ng-href="{{menu.content}}" ng-click="doGreeting(greeting)">{{menu.description}}</a>
<ul>
<li ng-repeat="submenu in menu.menu" id="{{submenu.id}}" class="{{submenu.cssClass}}">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert()">{{submenu.description}}</a>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
JAVASCRIPT
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope", "$http", "$window",
function($scope, $http, $window) {
$http.get('menu.json')
.then(function(response) {
$scope.menus = response.data.menus; // response data
$scope.greeting = 'Hello, World!';
$scope.ShowAlert = function () {
$window.alert("{{menu.content}}");
}
});
}
]);
JSON
{
"menus":[
{
"id":"contact",
"leaf":true,
"description":"Contact Us",
"link":"",
"content":"contactUs.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"rules",
"leaf":false,
"description":"Sports Betting Rules",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"types",
"leaf":true,
"description":"Wager Types",
"link":"",
"content":"wagerTypes.html",
"cssClass":"static-content wager-types",
"menu":null
},
{
"id":"odds",
"leaf":true,
"description":"Odds & Lines",
"link":"",
"content":"oddsAndLines.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"policies",
"leaf":true,
"description":"Rules & Policies",
"link":"",
"content":"rulesAndPolicies.html",
"cssClass":"static-content rules-policies",
"menu":null
},
{
"id":"bonuses",
"leaf":true,
"description":"Sports Bonuses",
"link":"",
"content":"sportsBonuses.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"conditions",
"leaf":false,
"description":"Terms & Conditions",
"link":"",
"content":"",
"cssClass":"",
"menu":[
{
"id":"termsOfService",
"leaf":true,
"description":"Terms of Service",
"link":"",
"content":"termsOfService.html",
"cssClass":"static-content",
"menu":null
},
{
"id":"privacy",
"leaf":true,
"description":"Privacy Policy",
"link":"",
"content":"privacy.html",
"cssClass":"static-content",
"menu":null
}
]
},
{
"id":"view",
"leaf":true,
"description":"View in: Mobile | Full Site",
"link":"",
"content":"view.html",
"cssClass":"static-content",
"menu":null
}
]
}
Pass the model variable to the function and then print it,
<li ng-repeat="submenu in menu.menu" id="{{submenu.id}}" class="{{submenu.cssClass}}">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert(submenu)">{{submenu.description}}</a>
</li>
Controller.js
$scope.ShowAlert = function (val) {
$window.alert(val);
}
Demo
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.ShowAlert = function (val) {
alert(val.content);
}
$scope.menus =
[{
"id": "contact",
"leaf": true,
"description": "Contact Us",
"link": "",
"content": "contactUs.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "rules",
"leaf": false,
"description": "Sports Betting Rules",
"link": "",
"content": "",
"cssClass": "",
"menu": [{
"id": "types",
"leaf": true,
"description": "Wager Types",
"link": "",
"content": "wagerTypes.html",
"cssClass": "static-content wager-types",
"menu": null
}, {
"id": "odds",
"leaf": true,
"description": "Odds & Lines",
"link": "",
"content": "oddsAndLines.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "policies",
"leaf": true,
"description": "Rules & Policies",
"link": "",
"content": "rulesAndPolicies.html",
"cssClass": "static-content rules-policies",
"menu": null
}, {
"id": "bonuses",
"leaf": true,
"description": "Sports Bonuses",
"link": "",
"content": "sportsBonuses.html",
"cssClass": "static-content",
"menu": null
}]
}, {
"id": "conditions",
"leaf": false,
"description": "Terms & Conditions",
"link": "",
"content": "",
"cssClass": "",
"menu": [{
"id": "termsOfService",
"leaf": true,
"description": "Terms of Service",
"link": "",
"content": "termsOfService.html",
"cssClass": "static-content",
"menu": null
}, {
"id": "privacy",
"leaf": true,
"description": "Privacy Policy",
"link": "",
"content": "privacy.html",
"cssClass": "static-content",
"menu": null
}]
}, {
"id": "view",
"leaf": true,
"description": "View in: Mobile | Full Site",
"link": "",
"content": "view.html",
"cssClass": "static-content",
"menu": null
}]
; // response data
}
]);
<!DOCTYPE html>
<html>
<head>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.5/cosmo/bootstrap.min.css" />
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
<script data-require="jquery#1.11.3" data-semver="1.11.3" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script data-require="bootstrap#3.3.5" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script data-require="angular.js#1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="menu in menus" id="{{artist.id}}">
<a ng-href="{{menu.content}}">{{menu.description}}</a>
<ul>
<li ng-repeat="submenu in menu.menu">
<a ng-href="{{submenu.content}}" ng-click="ShowAlert(submenu)">{{submenu.description}}</a>
</ul>
</li>
</ul>
</div>
</body>
</html>
Concerning $window.alert("{{menu.content}}");, Angular does not auto-magically evaluate expressions in all of JavaScript - it'll only evaluate expressions passed to it in templates. These get passed to something like $compile, which actually compiles the expression.
You can do something like this using $scope.$eval (which is not as evil as it sounds). That might look something like this:
var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope", "$http", "$window",
function($scope, $http, $window) {
$http.get('menu.json')
.then(function(response) {
$scope.menus = response.data.menus; // response data
$scope.greeting = 'Hello, World!';
$scope.ShowAlert = function () {
var alert = $scope.$eval('menu.content')
$window.alert(alert);
}
});
}
]);
Alternatively, you could evaluate the expression inside of the HTML (which is what I would suggest, and what #Sajeetharan posted above, so I won't replicate it here).
Note that Angular 1.5+ discourages the use of controllers in this manner because they do not exist in this form in Angular 2.0. I'd highly recommend porting this code to use components instead. You'd have a few components; one for the ListCtrl, one for each menu, and one for each submenu.

ng-repeat with key and value then use the key to be a directive value for ng-model

It is possible to have the key for a scope variable to be used in a ng-model directive?
What I wanted is not to manually put the keys for each ng-model directive, I just wanted to use the ng-repeat and get the key for a scope variable and put it on the ng-model inside the ng-repeat directive.
I'm just a newbie on this framework. Any help would be greatly appreciated
Markup snippet
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing.key">
</div>
HTML
<html ng-app>
<head>
<title>Demo</title>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/controllers/app.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-responsive.min.css">
</head>
<body>
<div classs="container" ng-controller="UserProfile">
<ul>
<li ng-repeat="user in users">{{user.id}} - {{user.fname}} </li>
</ul>
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing.key">
</div>
</div>
</body>
</html>
Javascript
function UserProfile ($scope) {
$scope.users = {
"ID01": {
"id": "ID01",
"fname": "Vincent",
"lname": "Panugaling",
"gender": "male",
"age": "21",
},
"ID02": {
"id": "ID02",
"fname": "Adrian",
"lname": "Santos",
"gender": "male",
"age": "22"
},
"ID03": {
"id": "ID03",
"fname": "Incognito",
"lname": "Mode",
"gender": "female",
"age": "21"
}
};
$scope.editProfile = function (id) {
$scope.editing = $scope.users[id];
};
}
Is this view you are expecting please have a look, yes it is possible to use key as ng-model.
Hey dude you are using angular 1.0.1 version thats why you can edit once and focus is getting out use latest version check out the same demo
updated fiddle
html code
<div classs="container" ng-app="app" ng-controller="UserProfile">
<ul>
<li ng-repeat="user in users">{{user.id}} - {{user.fname}} </li>
</ul>
<div ng-show="editing">
<input ng-repeat="(key, value) in editing" ng-model="editing[key]">
</div>
</div>
angular.js
var app = angular.module('app', []);
function UserProfile ($scope) {
$scope.users = {
"ID01": {
"id": "ID01",
"fname": "Vincent",
"lname": "Panugaling",
"gender": "male",
"age": "21",
},
"ID02": {
"id": "ID02",
"fname": "Adrian",
"lname": "Santos",
"gender": "male",
"age": "22"
},
"ID03": {
"id": "ID03",
"fname": "Incognito",
"lname": "Mode",
"gender": "female",
"age": "21"
}
};
$scope.editProfile = function (id) {
$scope.editing = $scope.users[id];
};
}

separate a JSON array [duplicate]

This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I have this JSON array with a lot of person data every one with a type like "hr" or "accounting".
the JSON array looks like this:
{
"0": {
"id": "2",
"name": "blabla",
"type": "hr"
},
"1": {
"id": "3",
"name": "bub",
"type": "hr"
},
"2": {
"id": "4",
"name": "ula",
"type": "accounting"
},
"3": {
...
}
}
I want to display them in an ul like this:
<ul>
<li><p>hr</p>name: blabla<p></li>
<li><p>hr</p>name: bub<p></li>
<li><p>hr</p>......</li>
</ul>
<ul>
<li><p>accounting</p>name: ula<p></li>
<li><p>accounting</p>......</li>
</ul>
but i have no clue how to separate the JSON array or how to properly loop through it to display it like that.
Try this:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div class="container"></div>
<script>
var json={
"0": {
"id": "2",
"name": "blabla",
"type": "hr"
},
"1": {
"id": "3",
"name": "bub",
"type": "hr"
},
"2": {
"id": "4",
"name": "ula",
"type": "accounting"
}
};
var previous_type=json[0].type;
var _html="<ul>";
$.each(json, function(index,key) {
if (previous_type!=key.type) {
_html+="</ul><ul>";
}
previous_type=key.type;
_html+="<li><p>"+key.type+"</p><p>name: "+key.name+"</p></li>";
});
_html+="</ul>";
$('.container').html(_html);
</script>
</body>
</html>
It creates a new ul for every different type.
Output of container:
<div class="container">
<ul>
<li>
<p>hr</p>
<p>name: blabla</p>
</li>
<li>
<p>hr</p>
<p>name: bub</p>
</li>
</ul>
<ul>
<li>
<p>accounting</p>
<p>name: ula</p>
</li>
</ul>
</div>
this will basically do what you want for one department. You can use it for each department by putting an if in the each loop and checking it against value.type
var new_html = "<ul>";
$.each('name_of_json_array', function(key, value){
new_html+="<li><p>"+value.type+"</p><p>name: "+value.name+"</p></li>";
});
new_html+="</ul>";
$('#some_container_element').append(new_html);

Categories