Json response via http not working - javascript

Currently working on angularjs I am trying to get the data from JSON file and I am showing the result in Ul format. when I searched in SO I found this link I am trying to do the same but still I am not getting
This is what I am trying here in controller
'use strict';
var app = angular.module('myApp', []);
app.controller('MyController', function($scope, $http){
$http.get('sample.json').then(function (response){
$scope.items = response.data.countries;
});
});
HTML Code
<body ng-app="myApp">
<div ng-controller="MyController">
<ul>
<li ng-repeat="(key, value) in items" {{key}}>
</li>
</ul>
</div>
</body>
Here is my plunker kindly help me what i am doing wrong here

One other problem: your JSON is incorrect:
{
"countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
]
}
}
Here is an alternative:
{
"countries": [
{ "USA": [
{"State": "California"},
{"State": "Nevada"} ]},
{ "India": [
{"State": "TamilNadu"},
{"State": "Karnataka"} ]}
] }

There are three issues,
(i)You do not need to declare the module twice , once in script.js and other one
in controller.js.
(ii) You were refering to angular 2.0 version ,and coded using angular 1.4 version.
(iii)If you want to show all states from json, it should not have a duplicate key, which you could see from the plunker itself
{ "countries": {
"State": [
"TamilNadu"
],
"State": [ <-- Error: duplicate key!
"Karnataka"
] } }
Here is the working Application

Related

interate through nested json file using ng-repeat not working

So I have a json file with nested elements. This is my json file:
[
{
"qid": "1",
"contester": "0",
"answer": "0",
"question": "What are you most likely to do after getting into an argument? ",
"images": [
{
"qid": "1",
"imageid": "AB100",
"imgname": "doghug_q1",
"imgpath": "Images\/Q1\/doghug_q1.jpg"
},
{
"qid": "1",
"imageid": "AB101",
"imgname": "eq_q1.jpg",
"imgpath": "Images\/Q1\/eat_q1.jpg"
},
{
"qid": "1",
"imageid": "AB102",
"imgname": "headache_q1",
"imgpath": "Images\/Q1\/headache_q1.jpg"
},
{
"qid": "1",
"imageid": "AB106",
"imgname": "scream_q1.jpg",
"imgpath": "Images\/Q1\/scream_q1.jpg"
},
{
"qid": "1",
"imageid": "AB107",
"imgname": "shopping_q1",
"imgpath": "Images\/Q1\/shopping_q1.jpg"
},
{
"qid": "1",
"imageid": "AB108",
"imgname": "walkAlone_q1",
"imgpath": "Images\/Q1\/walkAlone_q1.jpg"
}
]
},
{
"qid": "2",
"contester": "0",
"answer": "0",
"question": "Which game would you rather play?",
"images": [
{
"qid": "2",
"imageid": "AB105",
"imgname": "charades_q2.jpg",
"imgpath": "Images\/Q2\/charades_q2.jpg"
},
{
"qid": "2",
"imageid": "AB109",
"imgname": "playingCards_q2.jpg",
"imgpath": "Images\/Q2\/playingCards_q2.jpg"
},
{
"qid": "2",
"imageid": "AB110",
"imgname": "chess_q2",
"imgpath": "Images\/Q2\/chess_q2.jpg"
},
{
"qid": "2",
"imageid": "AB111",
"imgname": "twister_q2",
"imgpath": "Images\/Q2\/twister_q2.jpg"
}
]
}
]
And this is my controller that i used to access the json :
var app= angular.module('myApp', []);
app.controller('ListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('results.json').success(function(data) {
$scope.questions = data; // get data from json
angular.forEach($scope.questions, function(item){
console.log(item.images);
})
});
});
}
]);
And then my html code to display the questions and each questions list of images using the ng-repeat :
<body ng-app="myApp" >
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="question in questions"> {{question.qid}} </li>
</ul>
</div>
</body>
As of now iam trying to display the questions id from the json file as a list however the output im getting is a:
{{question.qid}}
as the output in my html page.. Can someone please help me. I dont know what im doing wrong.
your code has some missing things.
Here is working example of your code
http://plnkr.co/edit/FvD26TYZ9v8TbgUBUzN2?p=preview
firstly,
var app = angular.module('myApp', []); //variable app is missing.
secondly, data you mention has missing closing square brace.
First define app
var app = angular.module('myApp', []);
Then initiate your $scope.questions on your controller like
$scope.questions = [];
Also you might need to parse your data with
$scope.questions = JSON.parse(data);
You haven's define the app so you should change the first line of your code to this and check your closing tags on your js code...:
var app = angular.module('myApp', []);
app.controller('ListCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.questions = [];
$http.get('results.json').success(function(data) {
$scope.questions = data; // get data from json
angular.forEach($scope.questions, function(item){
console.log(item.images);
})
});
}
]);
Complete working code for your case :
HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="question in questions"> {{question.qid}} </li>
</ul>
</div>
</body>
</html>
JS
var app = angular.module('plunker',[]);
app.controller('ListCtrl',function ($scope,$http) {
$http.get('data.json').success(function(data) {
$scope.questions = data; // get data from json
});
});
Working Plunker
It is working !! Try once !!

Accessing grandparent ng-repeat object when the parent ng-repeat is another object

I want to access the grandparent object of a ng-repeat item in angular.
I am struggling to make this happen.
As you can see from below I want to display the text of the parent object.
This is a watered down version, I am looking for a way to make it work like the top example or a reason as to why it will not work.
Here is the DOM.
<div ng-app ng-controller="MyCtrl">
<!-- this is the one i cannot get working -->
<div>
<div class="copyData" ng-repeat="copy in copyDatabase">
<div ng-repeat="header in masterHeaders">
<div ng-repeat="test in copy.Translations">
set 1: {{test.LanguageAbreviation}}
</div>
</div>
<div>
<!-- this one does work but i need the item from the masterHeaders -->
<div class="copyData" ng-repeat="copy in copyDatabase">
<!-- <div ng-repeat="header in masterHeaders"> -->
<div ng-repeat="test in copy.Translations">
set 2 : {{test.LanguageAbreviation}}
</div>
<!--</div>-->
</div>
</div>
Here is the JSON Object
function MyCtrl($scope) {
$scope.copyDatabase = {
"data": {
"Language": "English",
"Translations": [{
"LanguageID": 308,
"LanguageName": "Arabic - Libya",
"LanguageAbreviation": "ar-LY",
"AvailableLanguages": [{
"ID": 308,
"Name": "Arabic - Libya"
}]
}, {
"LanguageID": 307,
"LanguageName": "Arabic - Egypt",
"LanguageAbreviation": "ar-EG",
"AvailableLanguages": [{
"ID": 307,
"Name": "Arabic - Egypt"
}]
}]
}
}
}
I have also made a JS fiddle for you guys.
http://jsfiddle.net/u7hk0qvj/5/
Seeing your jsfiddle, you have a base mistake, Angular is not finding your MyCtrl. You need to declare as an angular component.
You are creating a global funcion MyCtrl, but this isn't inside the angular context, for example:
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
You can see more info here
Need to have the :
$scope.masterHeaders = {
"home": "home",
"contact": "contact"
}
Object also in the control, If angular does not find the object it will not load any of the DOM elements In the ng-repeat.
Working fiddle
http://jsfiddle.net/u7hk0qvj/8/

Using AngularJS to consume REST

I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?
Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.

Import JSON data for AngularJS Web App

I have been following the Angular tutorials, and I am trying to get my JSON data to appear, yet I know I am doing something wrong, but can't figure out the proper method.
I know that somewhere in my app.js my scope is messed up.
How can I display the Family Name of each product?
Here is the layout I have:
app.js
var eloApp = angular.module('eloMicrosite', []);
eloApp.controller('homeListController', ['$scope', '$http',
function($scope, $http) {
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
$scope.products = data;
});
}]);
eloApp.controller('HomeController', function(){
this.products = $scope.products;
});
HTML
<div ng-controller="HomeController as home">
{{home.products[o]["Family Name"]}}
</div>
JSON Layout
{
"products": [
{
"Family Name": "3201L",
"Type": "IDS",
"Size (inches)": 32,
"Aspect Ratio": "16:9",
"Part Number": "E415988",
"Product Description": "ET3201L-8UWA-0-MT-GY-G",
"Marketing Description": "3201L 32-inch wide LCD Monitor",
"Advance Unit Replacement": "",
"Elo Elite": "",
"Package Quantity": 1,
"Minimum Order Quantity": 1,
"List Price": 1800
},
.
.
.
],
"families": [
{
category: "Category1"
},
{
category: "Category2"
}
],
"accessories": [
{
category: "Category1"
},
{
category: "Category2"
}
]
}
You should add homeListController on your page instead of HomeController, Also need to use this instead of using $scope as you wanted to follow controllerAs syntax, 2nd controller is useless in this scenario, you could remove that from app.js.
Markup
<div ng-controller="homeListController as home">
{{home.products[0]["Family Name"]}}
</div>
Controller
eloApp.controller('homeListController', ['$http',
function($http) {
var home = this;
$http.get('/Elo/eloMS.min.json')
.success(function(data) {
home.products = data.products; //products should mapped here
});
}]);
Demo Plunkr

http json file retrieving with IONIC and AngularJS

I am working on an product reviewing app based on ionic framework.
The app will consume REST service in JSON format.
Because Im not able to retireve data directly from the locally deployed website, i created a json demo file:
[{
"index": 0,
"marque": "labore",
"estAutorise": 0,
"name": "Jennifer Simmons"
},
{
"index": 1,
"marque": "duis",
"estAutorise": 0,
"name": "Beatriz Hale"
},
{
"index": 2,
"marque": "pariatur",
"estAutorise": 1,
"name": "Richmond Garner"
}
]
here is my services.js:
angular.module('starter.services', [])
.factory('Recettes', function($http) {
var recettes = [];
var produits = [];
$http.get('test.json').success(function(data) {
alert("success"); //to check the seccess responce
produits= data;
});
return {
...
produits: function() {
return produits;
},
....
Before this, I implemented products and recettes directly and it works just fine. And now, I recieve the success alert but the data seems to be invalid.
My controller:
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, Recettes) {
$scope.produits = Recettes.produits();
})
...
So my question is how can i fix the data binding problem ?
And If it works with .json file should it work for rest services as well (Content-Type: application/json )?
Thank you.

Categories

Resources