I am in a process of learning angularJS and I am stuck with accessing the values from the objects I want, in JSON file. Now, I searched the internet for answers, but all I got are really simple examples which I cannot apply in this case.
Here are the screenshots of my tries. The only one that worked out is when I accessed an array of objects, but when I wanted to access values from an object that is not in an array, I could not manage to do it properly.
I want to access and display only values from the object "main":
{"temp":293.01,"pressure":1019,"humidity":60,"temp_min":290.15,"temp_max":296.15}
Here's the JSON file:
{
"id": 2643743,
"name": "London",
"cod": 200,
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [{
"id": 800,
"main": "Clear",
"description": "Sky is Clear",
"icon": "01n"
}],
"base": "stations",
"main": {
"temp": 293.01,
"pressure": 1019,
"humidity": 60,
"temp_min": 290.15,
"temp_max": 296.15
},
// etc...
}
The following three examples didn't work:
<div>
<h1 align="center">Customer List</h1>
<div class="forecast">
<div ng-repeat="x in fiveDay">
<div class="first">
<p>{{ x.main.temp }}</p>
<p>{{ x.main.pressure }}</p>
<p>{{ x.main.humidity }}</p>
</div>
</div>
</div>
</div>
<div>
<h1 align="center">Customer List</h1>
<div class="forecast">
<div ng-repeat="x in fiveDay.main">
<div class="first">
<p>{{ x.temp }}</p>
<p>{{ x.pressure }}</p>
<p>{{ x.humidity }}</p>
</div>
</div>
</div>
</div>
<div>
<h1 align="center">Customer List</h1>
<div class="forecast">
<div ng-repeat="x in fiveDay">
<div class="first">
<p>{{ x.temp }}</p>
<p>{{ x.pressure }}</p>
<p>{{ x.humidity }}</p>
</div>
</div>
</div>
</div>
The last one displayed the wanted info in a div, but it rendered 10 empty divs as well, so I guess that counts as a fail as well.
I would highly appreciate some assistance.
Edit:
This is my JavaScript file:
// create the module and name it scotchApp
// also include ngRoute for all our routing needs
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
scotchApp.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/weather?q=London,uk')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', ['$scope', 'forecast', function($scope, forecast) {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
I uploaded the app on the web for the sake of exercise:
http://www.freegamesarmy.com/horoskop/index.html#/about
Is fiveDay truly an array of those ('those' being the JSON message that you included) or is it just one of those. If the latter then you shouldn't be using an ng-repeat. I'm assuming the former though.
I put your JSON message into a formatter online (this one) so you can make sense of it. Here it is...
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "Sky is Clear",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 293.01,
"pressure": 1019,
"humidity": 60,
"temp_min": 290.15,
"temp_max": 296.15
},
"visibility": 10000,
"wind": {
"speed": 4.6,
"deg": 80
},
"clouds": {
"all": 0
},
"dt": 1438976764,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0124,
"country": "GB",
"sunrise": 1438922043,
"sunset": 1438976240
},
"id": 2643743,
"name": "London",
"cod": 200
}
You can see that your first attempt should be the correct one.
One thing you can try is to intercept it in the controller and pick one of the fiveDay values out of the array (using fiveDay[0]) see if it works there in code. If you're using an IDE with debugging, then break and see what you get.
You don't need ngRepeat in your case as the API (http://api.openweathermap.org/data/2.5/weather?q=London,uk) responds with just an object (for current weather I guess). So in your case:
<div>
<h1 align="center">Customer List</h1>
<div class="forecast">
<div>
<div class="first">
<p>{{ fiveDay.main.temp }}</p>
<p>{{ fiveDay.main.pressure }}</p>
<p>{{ fiveDay.main.humidity }}</p>
</div>
</div>
</div>
</div>
Related
I am using this JSON data and I am suppoose to get the output as the first line will contain "EPL-2015". The second as "Match Day 1". The third line as "Date" and the fourth line as "Team1 VS Team2". But I am getting only correct output in line 1 and I am not getting rest of the outputs. Please help me in getting the rest.I think I am doing wrong in looping through the data of JSON.
var myApp = angular.module('futsalApp', []);
myApp.controller('futsalController', function($scope) {
$scope.fixtures =
{
"name": "EPL-2015",
"rounds":
[
{
"name": "Match Day 1",
"matches":
[
{
"date": "2015-08-08",
"team1":
{
"key": "manutd",
"name": "Manchester United",
"code": "MUN"
},
"team2":
{
"key": "tottenham",
"name": "Tottenham Hotspur",
"code": "TOT"
},
"score1": 1,
"score2": 0
},
{
"date": "2015-08-08",
"team1":
{
"key": "bournemouth",
"name": "Bournemouth",
"code": "BOU"
},
"team2":
{
"key": "astonvilla",
"name": "Aston Villa",
"code": "AVL"
},
"score1": 0,
"score2": 1
}
]
}
]
}
})
.
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="fixtures-first" ng-repeat="fix in fixtures">
<a>
<h2 class="match-title"> {{fixtures.name}} </h2>
<p class="match-day"> {{fixtures.rounds.name}} </p>
<p class="match-day"> {{fixtures.rounds.matches.date}} </p>
</a>
</div>
</div>
</div>
Here are the problems. In this line:
<div class="fixtures-first" ng-repeat="fix in fixtures">
...you're not setting your loop correctly. fixtures is a Javascript object, not an array, so you're not looping the way you want. You also never use fix for anything, so I think you've misunderstood how to use ng-repeat.
What you probably mean to do is repeat over your matches array, which is an actual array. Below, note that fixtures.rounds[0] is the first element of your rounds array.
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="fixtures-first" ng-repeat="match in fixtures.rounds[0].matches">
<a>
<h2 class="match-title"> {{fixtures.name}} </h2>
<p class="round-name"> {{fixtures.round[0].name}} </p>
<p class="match-day"> {{match.date}} </p>
</a>
</div>
</div>
</div>
I am new in AngularJS and I am fetching a data from a Rest API, sample data is given below.
{
"error": false,
"videos": [
{
"video_category": "ABC Category",
"title": "Test Video",
"video_links": [
{
"id": 1,
"video_link": "https://www.youtube.com/embed/bNI4Jws68m0"
},
{
"id": 3,
"video_link": "https://www.youtube.com/embed/tB8tACPZ4pc"
}
],
"video_tags": [
{
"id": 1,
"name": "ABC Tag"
},
{
"id": 3,
"name": "DEC Tag"
}
]
},
{
"video_category": "XYZ Category",
"title": "My Test Video",
"video_links": [
{
"id": 2,
"video_link": "https://www.youtube.com/embed/6SS3tK1NMsE"
}
],
"video_tags": [
{
"id": 2,
"name": "GDF Tag"
}
]
}
],
"status_code": 200
}
My AngularJS code is below.
var myApp = angular.module('myApp', []);
myApp.
controller("AppController", function($scope, $http) {
var url = 'http://example.com/api/';
// Get Service for Free Education Page
$http.get(url+'my_api_url').
then(function(response) {
$scope.videos = response.data.videos;
});
});
My HTML Code is below.
<section ng-repeat="video in videos">
<h5>{{ video.video_category }}</h5>
<ul>
<li ng-repeat="links in video.video_links">
<div class="embed-responsive embed-responsive-16by9">
<object
data="{{ links.video_link }}">
<param name="movie" value="{{ links.video_link }}">
<param name="allowFullScreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen" value="true"></param>
</object>
</div>
</li>
</ul>
<ul class="list-inline Tags">
<li ng-repeat="tag in video.video_tags">{{ tag.name }}</li>
</ul>
</section>
Now My Issue is that everything is work fine. but Allowfullscreen did not work. When I click on full screen option it is giving Full Screen is Unavailable I am trying but unfortunately unable to resolve this issue.
Really appreciated if anyone can help.
Thanks
Here is the code
APP.js
.state('app.aboutus', {
url: '/aboutus',
views: {
'mainContent': {
templateUrl: 'templates/aboutus.html',
controller: 'AboutController',
resolve: {
leaders: ['corporateFactory', function(corporateFactory){
return corporateFactory.query();
}]
}
}
}
})
Controller.js
.controller('AboutController', ['$scope', 'leaders', 'baseURL', function($scope, leaders, baseURL) {
$scope.baseURL = baseURL;
$scope.showLeaders = false;
$scope.message="Loading ...";
$scope.leaders = leaders;
console.log($scope.leaders);
}])
Aboutus.html
<ion-view view-title="About Us">
<ion-content>
<div class="card">
<div class="list list-inset">
<div ng-repeat="leaders in leadership" class="item item-avatar item-text-wrap">
<h2>{{leaders.name}}</h2>
<h4>{{leaders.designation}}</h4>
</div>
</div>
</div>
</ion-content>
</ion-view>
db.json
"leadership": [
{
"id": 0,
"name": "Human 1",
"designation": "Chief Executive Officer"
},
{
"id": 1,
"name": "Human 2",
"designation": "Chief Food Officer"
},
{
"id": 2,
"name": "Human 3",
"designation": "Chief Taste Officer"
},
{
"id": 3,
"name": "Human 4",
"designation": "Executive Chef"
}
]
When I checked using inspect element - console tab in Google Chrome, the $resolved: has successfully changed from false into true, and every array contain the information per ID.
But, the data didn't show in the aboutus.html
Did I typed something wrong? or maybe I'm using a wrong method?
Thank you in advance!
Your problem is likely that your ng-repeat syntax is incorrect. Where you have leadership, that should be the object/array you're referencing in your scope. So try changing it to this:
<div ng-repeat="leader in leaders" class="item item-avatar item-text-wrap">
<h2>{{leader.name}}</h2>
<h4>{{leader.designation}}</h4>
</div>
I am learning how to save a JSON file (locally held) to the user's localStorage and then retrieve that information using Angular and use hg-repeat to put each object from the JSON file (consists of multiple objects representing products) into a product box (which shows up as search results)
Here is my Code so far..
AJAX.JS
if(typeof(Storage)!=="undefined")
{
$(document).ready(function () {
$('.searchButton').click(function () {
$.ajax({
timeout: 3000,
url: "data/cars.json",
dataType: "text",
success: function(products) {
alert(products);
var dataToStore = JSON.stringify(products);
localStorage.setItem('userData', dataToStore);
alert(dataToStore);
storedData = JSON.parse(localStorage.getItem('userData'));
alert(storedData);
window.location.href = "results.html";
},
});
});
})
}
else {
alert("Sorry your browser is too old to support this website. Please update.");
}
APP.JS
var app = angular.module('searchFox', []);
app.controller('foxController', ['$scope', function($scope) {
$scope.valueFromLocalStorage = storedData;
}]);
HTML (SEARCH RESULTS PAGE // ANGULAR PART)
<div class="row section">
<div class="three columns" ng-repeat="v in valueFromLocalStorage">
<div class="panel">
<img class="panelImage" src="images/product6.jpg"></img>
<p class="panelTitle">{{v.model}}</p>
<p class="panelPrice">{{v.price}}</p>
</div>
<img class="mFireOne" src="images/fire.png">
<p class="mViewOne">9318</p>
<img class="mFireTwo" src="images/heart.png">
<p class="mViewTwo">172</p>
</div>
</div>
JSON FILE EXAMPLE
{
"make": "honda",
"model": "accord",
"year": "1989",
"mileage": "25000",
"color": "black",
"transmission": "automatic",
"cylinders": "4",
"type": "sedan",
"title": "clean",
"price": "$15,000",
"img_url": "http://img.modifiedcartrader.com/uploaded/XL/2006/12/6584_Honda_Accord_1222200613708PM1.JPG"
},
{
"make": "acura",
"model": "integra",
"year": "2001",
"mileage": "108800",
"color": "red",
"transmission": "manual",
"cylinders": "4",
"type": "coupe",
"title": "clean",
"img_url": "http://carphotos.cardomain.com/ride_images/2/3951/4101/22377050003_large.jpg"
},
{
"make": "ford",
"model": "mustang",
"year": "2015",
"mileage": "1003",
"color": "blue",
"transmission": "manual",
"cylinders": "8",
"type": "coupe",
"title": "clean",
"img_url": "http://s1.cdn.autoevolution.com/images/news/gallery/2015-ford-mustang-rendered-with-slightly-different-face-rear-photo-gallery_6.jpg"
},
{
"make": "volkswagen",
"model": "golf",
"year": "2002",
"mileage": "86000",
"color": "green",
"transmission": "automatic",
"cylinders": "4",
"type": "hatchback",
"title": "clean",
"img_url": "http://zombdrive.com/images/2002_volkswagen_gti_2dr-hatchback_18t_s_oem_1_500.jpg"
},
{
"make": "bmw",
"model": "335i",
"year": "2010",
"mileage": "24664",
"color": "red",
"transmission": "manual",
"cylinders": "6",
"type": "sedan",
"title": "clean",
"img_url": "http://foodcourtlunch.com/wp-content/uploads/2010/03/bmw_335i_30.jpg"
}
]
So so far i'v managed to use AJAX to grab the locally help JSON file and save it to the user's localStorage. But now I cannot figure out how to correctly and cleanly send it over to the Angular Page (search results) and then to use hg-repeat to make a product container for every product object in the JSON file...
You need get your object from localstorage. You can use https://github.com/grevory/angular-local-storage this library as well.
example:
```
var app = angular.module('searchFox', ['LocalStorageModule']);
app.controller('foxController', ['$scope, LocalStorageModule', function($scope, LocalStorageModule) {
$scope.saved = "gold";
$scope.myObj = localStorageService.get('key')
}]);
<div class="three columns" ng-repeat="smth in myObj">
```
after that you will have your object in your view and can do with that everything you want.
Eventually you want to feed ng-repeat an array. Depending on your JSON file's contents you may have to call
JSON.parse(jsonStr);
or pass the contents of the object in JavaScript into an array somehow.
But think this:
<div class="three columns" ng-repeat="??">
Wants something like
<div class="three columns" ng-repeat="{arrayOfObjects}">
where is some arrayOfObjects = [ {...}, {...}, {...}];
If you already have stored everything in localStorage, Angular can access the values directly using native JS or angular-local-storage.
Just fetch values from localStorage in your controller, and pass it to view using $scope.
$scope.valueFromLocalStorage = window.localStorage.getItem('productQuery');
Now, you can use ng-repeat over valueFromLocalStorage to display values in your view.
<div class="row section">
<div class="three columns" ng-repeat="v in valueFromLocalStorage">
<div class="panel">
<img class="panelImage" ng-src="/images/{{v.imageName}}" ></img>
<p class="panelTitle">{{v.name}}</p>
<p class="panelPrice">{{v.price}}</p>
</div>
<img class="mFireOne" src="images/fire.png">
<p class="mViewOne">9318</p>
<img class="mFireTwo" src="images/heart.png">
<p class="mViewTwo">172</p>
</div>
Also, there is a correction in your ajax.js file:
var save = function(obj) {
localStorage["productQuery"] = JSON.stringify(obj); //obj instead of productQuery
};
Good day;
I am learning angularjs and i looked at the example found in the spring website http://spring.io/guides/gs/consuming-rest-angularjs/.
The problem is nothing displays on the view but using firebug, i can see that data is returned from the server.
Here is my controller
function AController($scope, $http){
$http.get('http://127.0.0.1:5000/auth/users').
success(function(data){
$scope.user = data;
});
}
and my view
<div class="container" ng-controller="AController">
<p>Email is {{user.email}}</p>
<p>password is {{user.password}}</p>
</div>
Can someone please tell me what i am doing wrong?
Oh and here is the data returned from the server
[
{
"email": "azy#yahoo.com",
"id": 15,
"isActive": null,
"password": "$6$rounds=93733$jj3PWiZjtc0yC1Ws$bCIpDORaYFUDD.8kRRGpV64rMqFFQgR9ujlQEeTSd4r/To1snucdg.fsy2Ovkz39tRpy18ZWQnN7dKomdapKx."
},
{
"email": "abd#yahoo.com",
"id": 16,
"isActive": null,
"password": "$6$rounds=100762$uSVOZI5oPAtEaDn9$HqqfIYQVw7g2ITH7IzK/SnCXBnKJW9wQTjSiJ16BGogkWFh89iC2/SjEY/OEXNrB/YHGI66R.wjwgg5n.2R5P0"
},
{
"email": "xvc#yahoo.com",
"id": 17,
"isActive": null,
"password": "$6$rounds=94664$A/yXLhEW57Sd3ymD$unFuK75sG6jbvH9b2eQTcnIIjYi16NmSCPSxgPR7noE.JSmZDCtvxctY1s9t69nRj5IZMviPEhopnci9CpBaX/"
}
]
Your returned data is array. So HTML should look something similar to this:
<div class="container" ng-controller="AController">
<div ng-repeat="u in user">
<p>Email is {{ u.email }}</p>
<p>password is {{ u.password }}</p>
</div>
</div>