Query in looping through JSON data set in getting front-end output - javascript

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>

Related

Angular radio selection not checked correctly

In my Angular1.x app, my models maps to my radio selection correctly, however the radio button itself is not selected except for the very last one. Not really sure what the problem is. I created a very small example below to illustrate this behaviour. Any help is greatly appreciated.
http://plnkr.co/edit/dgGCvtOEb9WKTNtQHjqd?p=preview
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.questions = [{
"category": "Movies",
"questions": [{
"title": "M1",
"score": "4",
},
{
"title": "M2",
"score": "2",
}
]
},
{
"category": "Foods",
"questions": [{
"title": "F1",
"score": "3",
},
{
"title": "F2",
"score": "4",
}
]
},
{
"category": "Sports",
"questions": [{
"title": "S1",
"score": "5",
}]
}
];
});
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="todo.js"></script>
<link rel="stylesheet" href="todo.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<div ng-repeat="(ccKey, cc) in todoList.questions">
<hr/>
<div>
<b style="color: red;">Category</b> : {{cc.category}}
</div>
<div ng-repeat="(qqKey, qq) in cc.questions">
<br/>
{{qq.title}} : Selected Score: {{qq.score}}
<br/>
<div ng-repeat="n in [].constructor(5) track by $index">
<input type="radio" ng-model="qq.score" name="q-{{ccKey}}-{{qqKey}}" value="{{$index+1}}"><br/>Score: {{$index+1}} : Group: q-{{ccKey}}-{{qqKey}}
</div>
</div>
</div>
</div>
</body>
</html>
Try removing the name attribute from your <input type="radio"> tag. This seems to be causing a conflict with what Angular is doing to manage your radio tags. I am able to see all categories selected, and the selections are still grouped within a given question.
In the Angular input[radio] docs, they do not show using a name attribute: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
If what you want is the initial selection of the values when the page first loads,then use
ng-value="($index+1).toString()"
Since your scores are given as strings, you need to convert the number to string to match the score when you use "ng-value". Or better, you can just set your scores as integers and leave the rest of the code unchanged:
todoList.questions = [{
"category": "Movies",
"questions": [{
"title": "M1",
"score": 4,
},
{
"title": "M2",
"score": 2,
}
]
}, ....
Here is a modified plunker

ng-repeat ng-click showing only last value from an array

I am trying to show the details of each of my values from my data in a pop up window however, only last value from an array is shown three times instead of three different values.
This is my html:
<div ng-repeat="value in all | filter: (!!locationFilter || undefined) && {type: locationFilter} | filter: priceFilter | filter: datesFilter | orderBy:sortProp">
<ul>
<li><img src="app/images/{{value.image}}.jpg" alt="Smiley face" height="100" width="240"></li>
<li><strong>{{value.id}}</strong></li>
<li><strong>{{value.address}}</strong></li>
<li>city: {{value.city}}</li>
<li>postcode: {{value.postcode}}</li>
<li>price: £{{value.price}}</li>
<li>num_of_beds: {{value.num_of_beds}}</li>
<li>{{value.type}}</li>
<li>{{value.minutes}}</li>
<li>{{value.added}}</li>
</ul>
<div ng-click="togglePopup(value)">
view details
<div class="modal-outer" ng-if="showPopup">
<div class="modal-container">
{{selectedValue.address}}
<div ng-repeat="subValue in value.details track by $index">
<ul>
<li>{{subValue.desc}}</li>
<li>{{subValue.info}}</li>
</ul>
</div>
</div>
</div>
</div>
</div>
and the javascript function:
$scope.showPopup = false;
$scope.selectedValue = {};
$scope.togglePopup = function(value) {
$scope.showPopup = !$scope.showPopup;
if (value)
$scope.selectedValue = value;
};
My data:
"allData": {
"patientsData": {
"patients": [{
"id": 1,
"image": "amsterdam",
"address": "17 Peregrine House",
"city": "London",
"postcode": "SW11 2NL",
"price": "150.000",
"num_of_beds": 1,
"type": "terraced",
"minutes": 20,
"added": "Jan 6 2017",
"details": [{
"desc": "Beautiful terraced house looking like houses in Amsterdam",
"info": "dcjkbc"
}]
}, {
"id": 2,
"image": "dutch",
"address": "22 Portland House",
"city": "London",
"postcode": "SW12 2SE",
"price": "800.000",
"num_of_beds": 3,
"type": "detached",
"minutes": 10,
"added": "Dec 28 2016",
"details": [{
"desc": "Dutch house in the countryside",
"info": "dcjkbc"
}]
}, {
"id": 3,
"image": "evy",
"address": "2 Holland Road",
"city": "London",
"postcode": "SW10 2RE",
"price": "950.000",
"num_of_beds": 4,
"type": "terraced",
"minutes": 5,
"added": "Jan 5 2017",
"details": [{
"desc": "Newly decorated house",
"info": "dcjkbc"
}]
}]
}
}
when I click view details ng-click="togglePopup(value) it shows the popup but only displaying the last value from subarray called details from my json so it would only show Newly decorated house and dcjkbc for all houses so it would be displayed three times. I would appreciate any help.
According to the documentation it is better practice to track by an objects id when it is available anyway:
If you are working with objects that have a unique identifier property, you should track by this identifier instead of the object instance. Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance. If you don't have a unique identifier, track by $index can also provide a performance boost.
Since you have an id value you should track by value.id instead:
<div ng-repeat="subValue in value.details track by value.id">
And here is a link to their documentation:
https://docs.angularjs.org/api/ng/directive/ngRepeat
As far as your error, your code works totally fine. Here is a link to a working codepen:
http://codepen.io/egerrard/pen/egvOaX
Your problem is in some other code that isn't shared here.
Try changing this line:
<div ng-repeat="subValue in value.details track by $index">
to
<div ng-repeat="subValue in all[$index].details track by $index">
I suspect value is ending by being bound to the last element of your ng-repeat. This way you should be for sure be selecting the proper value element from your list.
Attempt 2:
This is a little more of a re-write type answer. Could you update the pop-up so that it is not inside the ng-repeat?
<div class="modal-outer" ng-if="showPopup">
<div class="modal-container">
{{selectedValue.address}}
<div ng-repeat="subValue in value.details track by $index">
<ul>
<li>{{selectedValue.details.desc}}</li>
<li>{{selectedValue.details.info}}</li>
</ul>
</div>
</div>
</div>

AngularJS deep filter through array in ng-repeat

My question is looking similar to other questions. But it is different.
Please take a look of below code.
I want to filter data by an array of objects.
Here is the snippet
HTML
<div
ng-repeat="(key, value) in ledgerData.ledgers track by $index"
ledger-pop
index="$index"
ftype="ftypeUpdate"
itemdata="value"
acntlist="fltAccntList"
class='drEntryForm_{{$index}} pr'
name='drEntryForm_{{$index}}'
update-ledger="updateEntry(entry)"
novalidate
>
</div>
JS
$scope.ledgerDataata = {
"ForwardedBalance": {
"amount": 0,
"type": "CREDIT"
},
"creditTotal": 4008,
"debitTotal": 4008,
"balance": {
"amount": 4008,
"type": "CREDIT"
},
"ledgers": [
{
"transactions": [
{
"particular": {
"name": "Sarfaraz",
"uniqueName": "temp"
},
"amount": 1001,
"type": "DEBIT"
}
],
"description": "testing",
"tag": "testing"
},
{
"transactions": [
{
"particular": {
"name": "frnd",
"uniqueName": "frndafafaf14453422453110l26ow"
},
"amount": 2001,
"type": "CREDIT"
},
{
"particular": {
"name": "Rahul",
"uniqueName": "cake"
},
"amount": 3001,
"type": "DEBIT"
}
],
"description": "testing",
"tag": "testing",
}
]
}
I am trying to filter by
ng-repeat="(key, value) in ledgerData.ledgers track by $index | filter:{transactions[0]:{type: 'DEBIT'}}"
But am getting error
thanks in advance :-)
You need to write nested ng-repeat to solve this problem.
outer ng-repeat for the array ledgerData.ledgers and
inner ng-repeat for transaction array in ledgerData.ledgers
<div ng-repeat="(keyOne, ledger) in ledgerData.ledgers track by $index">
{{ledger.description}}
<div ng-repeat="(keyTwo, transaction) in ledger.transactions | filter:{type:'DEBIT'}">
{{transaction.type}}
</div>
</div>
Actually I got the solution.
I've googled hardly and got a library for angularjs-filter.
Here is the link it is very good plugin for filter dirty works and how to use it.
How I got success:
html
ng-repeat="(key, value) in ledgerData.ledgers | pick: debitOnly track by $index"
AngularJS
$scope.debitOnly = (ledger) ->
'DEBIT' == ledger.transactions[0].type
that's it.

How to use ng-repeat with a JSON file stored in localStorage?

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
};

Displaying JSON with ng repeat

I have a JSON data in the format
[
{
"_1": {
"id": 4,
"cost": 45.0,
"measure": 4,
"NoOfUnits": 677,
"hours": null
},
"_2": {
"id": 1,
"name": "Truck",
"description": "Test"
}
},
{
"_1": {
"id": 1,
"cost": 1120.0,
"measure": 1,
"NoOfUnits": 500,
"hours": null
},
"_2": {
"id": 7,
"name": "PC300",
"description": null
}
},
]
I'm not able to display the data that I have store in a $scope variable say
$scope.result
This is my ng repeat functionality
<div ng-repeat="data in result">{{data.name}}{{data.description}}</div>
your $scope.result is contains 2 objects, with in one object u have set of object properties like _1,_2 , and then these properties are again objects like
"_1": {
"id": 4,
"cost": 45.0,
"measure": 4,
"NoOfUnits": 677,
"hours": null
}
, then u have the properties u need to print.
<ul>
<li ng-repeat="x in result"> // repeats objects
<ul ng-repeat="obj in x"> // repeat object properties '_1',"_2" , these are again objects
{{obj.name}}{{obj.description}}
<ul>
</li>
</ul>
With your data structure... You cannot access name and description directly from first ng-repeat.
Even if you have nested ng-repeat you are not guaranteed with name and description. You need to flatten the object after first ng-repeat and then you can access all the properties. Assuming that _1, _2 object properties are related.
Two loops are required---
<div ng-repeat="data in result">
<div ng-repeat="obj in data">
{{obj.cost}}{{obj.name}}
</div>
</div>
Demo: http://jsfiddle.net/HB7LU/8254/

Categories