I'm trying to implement a very basic system involving angular.js and JSON, but I can't get it to behave. All I want to do is get the value for a particular field in my JSON file and spit it onto the page. Can anyone see why this isn't working? It finds the database every time, but I can't seem to access the object.
HTML & JS
<html lang="en" ng-app="ngApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script>
var ngApp = angular.module('ngApp', []);
ngApp.controller('ngCtrl', function($scope, $http){
$http.get("db.json").success(function(data){
console.log("Database found");
$scope.data = data;
});
});
</script>
<body ng-controller="ngCtrl">
<div>Data goes here: {{data.field1}}</div>
</body>
</html>
JSON
[
{
"field1":"data1",
"field2":"data2"
}
]
I'm very new to angular, so I wouldn't be surprised if there's something I missed.
Your json response is array of objects. So, you've to use array notation to access the data from it.
See the highlighted changes below:
<div>Data goes here: {{data[0].field1}}</div>
// ^^^
You might want to use ng-repeat to loop over all the data
<body ng-controller="ngCtrl">
<div ng-repeat="item in data">
<span> Field1 : {{item.field1}}</span>
<span> Field2 : {{item.field2}}</span>
</div>
</body>
From first look it seems that json data returned is array of an objects. Try this
data[0].field1
Related
Is something like this possible in Angular, I have tried searching but I don't know the exact terms to search for, so first of all, my apologies.
I am using Angular successfully to access a JSON file.
My JSON file contains a list of over 150 events, each event has some basic information like image, title, price, whether the event is sold out etc.
Each event ALSO contains a URL to JSON file about that event.
This file contains much more in depth information about the individual event such as location, difficulty, wheelchair accessible etc.
How can I loop through the first JSON but still extract the information for the "embedded"? JSON file so that I display all information on one page.
I am stuck with being able to understand how to "call" that second JSON file of information while being in a ng-repeat.
and as a beginner to Angular I struggled to search for the correct terminology to help myself.
thanks
EDITED -----
I have created a plunkr here of part of what I am trying to achieve.
http://plnkr.co/edit/zYAhNKdM18pxuK5roPjj?p=preview
<!DOCTYPE html>
<html>
<head>
<style>
#event-list span{display:block;}
#event-list li{clear:both;}
#event-list ul{list-style: none;}
#event-list img{float:left;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module("exampleApp", []);
app.controller("eventCtrl", function ($scope, $http, $location) {
var eventList = "http://ajax.wiggle.co.uk/api/list/events/?ris=1";
$scope.host = $location.host;
$scope.wiggleEvents = [];
$http({
method: 'JSONP',
url: eventList + '&callback=JSON_CALLBACK'
}).success(function (data, status, headers, config) {
$scope.wiggleEvents = data.Results.Products;
// data contains the response
// status is the HTTP status
// headers is the header getter function
// config is the object that was used to create the HTTP request
}).error(function (data, status, headers, config) {
});
});
</script>
</head>
<body ng-app="exampleApp">
<div ng-controller="eventCtrl">
<div class="row">
<div class="col-md-12" id="event-list">
<ul>
<li ng-repeat="p in wiggleEvents" >
<!-- i need to display a mixture of information from the first JSON file and information from each individual events JSON file -->
<img src="" ng-src="{{p.Image}}?w=125&h=125&a=7" />
<span class='name'>Title: {{p.Title}}</span>
<span>PID: {{p.pid}}</span>
<!--Each of these events has an Apirl which is a JSON file of the information on the event -->
<span>ApiUrl: {{p.ApiUrl}}</span>
<!--AND here i want to add short description of each event. found in the API of each individual event -->
<!--AND here i want to add difficulty rating from API of each individual event -->
<!--AND here i want to add location area of each individual event etc etc etc -->
</li>
</ul>
</div>
</div>
</div>
</body>
</html>
I can successfully get information from the main JSON file, and display the 24 events in the page.
the main JSON file is here:
http://ajax.wiggle.co.uk/api/list/events/?ris=1
each "product" in that JSON has it's own APIUrl to it's own individual JSON file which contains more information about that individual product.
I am trying to output in my html some information from the main JSON and some information from each idividual JSON at the same time.
I am really stuck with how to access each of those individual JSON files, especially as there could be varying amount of "products" contained within the first main file. it happens to be 24 today, but it could be 36 tomorrow etc.
thanks
let's say you have the following json object:
myJsonObj= {
user: {
firstname : "jane",
lastname : "doe"
},
friend: {
firstname: "hancock",
lastname : "john"
}
}
To iterate over properties an object litteral (your json object) using ng-repeat, you must use (key, value) like:
<div ng-repeat="(key,value) in myJsonObj">
<span ng-bind="key"></span> // displays "user" , then "friend"
<span ng-bind="value.firstname"></span> // displays "jane"
<span ng-bind="value.lastname"></span> // displays doe
</div>
read more about iterating over object properties here : ng-repeat .
Edit:
you can also do more stuff by passing some data to a scope function. like
<div ng-repeat="(key,value) in myJsonObj">
// assuming retrieveUrl() is a scope function you wrote
// in order to extract and return the url from the data you passed
// as parameter
<span ng-bind="retrieveUrl(value.url)"></span>
</div>
The best way to fetch json data from a url in the data nested within an ng-repeat would be to write a directive that runs a $http GET. Something like this:
http://plnkr.co/edit/xFCG1p8WwDw9bt6jO49q?p=preview
html
<div ng-repeat="thing in things track by $index">
<get-url-data url="thing"></get-url-data>
</div>
js:
app.directive('getUrlData', function() {
return {
restrict: 'E',
template: '<div>{{vm.jsonData}}</div>',
scope: {
url: '=?'
},
controllerAs: 'vm',
bindToController: true,
controller: function($http) {
vm = this;
$http.get(vm.url).then(function(response) {
vm.jsonData = response;
});
}
};
});
I managed to find an answer for this question.
I followed the chosen answer in this stackoverflow post:
How to bind multiple JSON files in ng-repeat (AngularJS)?
This was written in a way I understood, and it worked for me when I followed it.
I am using "itunes-search" module in nodejs and it is send the sends the search results as Json data. The Json data has a filed named "artistName" which has duplicates element I can see. but I want to print the "artistName" values discarding the duplicates instance. Means one value should be printed only one time. I have only included the
<script type="text/javascript" src="/angular.js"></script>
<script src="js/angular-file-upload.min.js"></script>
I am trying with the bellowed code. But it is not working. Multiple elements of value are also printed.
<ul>
<li data-ng-repeat="data in response | orderBy:'artistName' | unique:'artistName' ">
<b> {{data.artistName}} <b><br/>
</li>
</ul>
I will really appreciate him who will help me.
You'll need to create your filter. Here is an example :
angular.module('app',[]).filter('unique', function() {
return function(list, attribute) {
var result= [];
var keys = [];
// Find duplicates
angular.forEach(list, function(item) {
if(keys.indexOf(item[attribute]) === -1) { // Not already present
keys.push(item[attribute]);
result.push(item);
}
});
return result;
};
The error says you need to have unique filter loaded in your angular app in order to use it. Angular could not find the filter and hence throwing the error.
Here is the way you can fix that.
Save this as unique.js in your scripts and load it in HTML.
Add 'ui.filters' to your dependencies in your app.
I am very new to AngularJS and want to get started retrieving data from a remote source.
My app.js file looks like this:
var app = angular.module('footy', []);
app.controller('ClubController', ['$http', function($http){
var club = this;
club.team = [];
$http.get('http://api.football-data.org/teams/19').success(function(data){
club.team = data;
});
}]);
and my html looks like this:
<!doctype html>
<html ng-app="footy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller = "ClubController as data">
{{data.club.team.name}}
</div>
</body>
</html>
When I view the page in a browser all that is returned is a blank page and in the source I can see "{{data.club.team.name}}" between the div.
When I view the data source Url in a browser I see this:
{
"id": 19,
"name": "Eintracht Frankfurt",
"shortName": "Eintr. Frankfurt",
"crestUrl": "http://upload.wikimedia.org/wikipedia/commons/0/04/Eintracht_Frankfurt_Logo.svg"
}
I have gone through and completed this course: http://campus.codeschool.com/courses/shaping-up-with-angular-js/ and was trying to apply the instructions from chapter 5 about services to this but I am having no luck.
Can someone help? Thanks in advance.
I see two problems here:
http://api.football-data.org/teams/19 doesn't allow CORS. You can't load the data. Update: The OP pointed out that s/he has an API key that allows CORS. This is not the issue then, but might be for other people trying to reproduce this.
{{data.club.team.name}} should be {{data.team.name}} because you said var club = this;. In other words, the controller you aliased data is the same as the club object. The club object is not a property of the controller data, it IS the controller's data.
See this plnkr for a demo. The commented out code doesn't work because of the api key, the locally hosted file does: http://plnkr.co/edit/ItD96Zfk0g1cLyGrrgBy?p=preview
This question is not Django related in any way because my Django view which returns a dummy JSON object works perfectly, just thought I would share the Django view which converts a
Model.objects.all() into pure JSON data then returns this pure data for an Angular controller to read and process through an ng-repeat:
from django.core import serializers
from django.utils import simplejson
def json(request):
all_objects = list(Message.objects.all())
to_json = serializers.serialize('json', all_objects)
return HttpResponse(to_json, mimetype='application/json')
Now on to my question,
I'm not sure if I'm having an Angular issue or pure JavaScript issue. I have an Angular controller called testjson which calls that Django view above which then successfully returns a JSON object like this:
[
{
"pk":1,
"model":"chatfeed.message",
"fields":{
"body":"hey everyone",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:29:27Z"
}
},
{
"pk":2,
"model":"chatfeed.message",
"fields":{
"body":"How's it going?",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:32:05Z"
}
},
{
"pk":3,
"model":"chatfeed.message",
"fields":{
"body":"So what's going on right now",
"chat_feed":"Events",
"likes":0,
"author_obj":1,
"parent_channel":2,
"pub_date":"2014-03-18T23:32:33Z"
}
},
{
"pk":4,
"model":"chatfeed.message",
"fields":{
"body":"Going pretty well actually",
"chat_feed":"Dating",
"likes":0,
"author_obj":1,
"parent_channel":1,
"pub_date":"2014-03-18T23:32:55Z"
}
}
]
And so I would just like to grab the body of a particular chat_feed to be printed in Angular JS using Angular's ng-repeat to get something like this if I wanted all chat messages from chat_feed "Dating":
<div ng-controller="testjson" ng-click="getJSON()">
<ul ng-model="chatfeed">
<li ng-repeat="post in chatfeed">{$ post $}</li>
</ul>
</div>
So in order to get the ng-repeat to work, I believe. I would have to loop through the raw JSON object, grab the 'body' string from each index and store them into an array so that's what I did:
app.controller("testjson", function($scope, $http)
{
$scope.getJSON = function()
{
var JSONObject = $http.get('http://domfa.de/testjson/').success(function(data)
{
$scope.totalfeed = data.length;
chatarray = new Array();
for (var i=0; i < data.length; i++)
{
if (data[i].fields.chat_feed == $scope.currentFeed)
{
chatarray[i] = data[i].fields.chat_feed;
}
}
console.log(chatarray);
$scope.chatfeed = chatarray;
});
}
});
So after all that, my console.log seems to be returning the proper array just fine with the "body"s from the correct chat_feed. Console.log() is doing what I want it to do and the array it prints is properly formatted with perfect syntax, but as for the HTML which calls the ng-repeat="post in chatfeed" angular function it doesn't seem to print anything at all unless I physically copy and past the array console.log() prints out and replace ng-model="chatfeed" with a hardcoded array the console.log() generates for me with no problems using ng-init="['hows it going?', 'hey everyone']".
You are calling getJSON to populate chatfeed when the div is clicked. I wasn't able to trigger getJSON because I couldn't see where to click. So, I added some text to the div:
<div ng-controller="MainCtrl" ng-click="getJSON()">click me!
<ul>
<li ng-repeat="post in chatfeed">{{ post }}</li>
</ul>
</div>
When I clicked the div, I got an error message regarding duplicates in ng-repeat. If currentFeed = 'Dating', then there are 3 matching chat posts with the 'Dating' chat_feed. To allow for the duplicates, I added a tracking expression:
<li ng-repeat="post in chatfeed track by $index">{{ post }}</li>
But then, the list only displayed 'Dating' 3 times. You want the messages to be displayed - not the category. So, I changed the getJSON to add body instead of chat_feed to chatarray:
$scope.chatarray.push($scope.data[i].fields.body)
After making this change, the tracking expression is no long necessary because the body of each chat is unique.
Here is the plunker demo with the final adjustments: http://plnkr.co/edit/J4PtDpeRHO8TVItUnHJw?p=preview
I am writing a website for my school that, among other things will display departmental changes. These changes are already gathered with a script I wrote. To improve workflow I want the impelmentation of the data onto the website to be automated so while the script automatically sens an email to department heads it also saves the information as JSON data and uploads it to the server where I use angularJS' $http.get to save it into the $scope
var integrationFactory = function($http) {
var factory = {};
factory.getNotes = function() {
return $http.get('/ci/json_releasenotes.json');
};
return factory;
};
angular.module('integrationApp').factory('integrationFactory', integrationFactory);
Because the releasenotes is constantly being upgraded the only way I could save it as JSON was if it went something like,
{"0": "this is the first note", "1": "this is the second note", "2": "etc..." }
Because there's no key however, I can't exactly do,
<div ng-repeat key in notes>
{{ key.notes }}
</div>
Is there any other way to do it? Any help would be greatly appreciated.
Use $index! Just do:
<div ng-repeat key in notes>
{{ key[$index] }}
</div>
You could do something like this
<div ng-repeat ="(key,value) in notes"> {{ value}} </div>