Angular.js view - display a description from a code-description json - json

I have list of schools each with a code for a school level instead of ES, MS, HM.
[
{
"nameOfInstitution": "Summer Elementary",
"schoolLevel": "01304"
},
{
"nameOfInstitution": "Grady Middle",
"schoolLevel": "02400"
}
]
I am planning to use another JSON to get the description of those codes from:
{
"schoolLevel": [
{"01302": "All levels"},
{"01304": "Elementary"},
{"02400": "Middle"},
{"02402": "High school"}
]
}
What is the proper way to display this in Angular in a view where it would look like?
<div class="item item-text-wrap">
<p ng-repeat="school in schools">{{school.nameOfInstitution}} - {{school.schoolLevel}}</p>
</div>
Should it 1). iterate through the main JSON and insert the description after "schoolLevel" or 2). should I use a look-up method to find out the description each time I display a school?
I would think the first option is the better choice, but can anyone share some snippets of code on how to best achieve that?
Thank you!

You can create a filter for lookup:-
DATA:-
$scope.schools=[
{
"nameOfInstitution": "Summer Elementary",
"schoolLevel": "01304"
},
{
"nameOfInstitution": "Grady Middle",
"schoolLevel": "02400"
}
];
$scope.schoollevel={
"schoolLevel": [
{"01302": "All levels"},
{"01304": "Elementary"},
{"02400": "Middle"},
{"02402": "High school"}
]
}
Filter:-
app.filter('level',function(){
return function(item,filter){
//console.log(item.schoolLevel);
var levelVal;
item.schoolLevel.forEach(function(level){
if(typeof level[filter]!='undefined'){
console.log(level[filter]);
levelVal=level[filter];
}
}
);
return levelVal;
}
});
HTML:-
<p ng-repeat="school in schools">{{school.nameOfInstitution}} -
{{schoollevel|level:school.schoolLevel }}</p>
Plunker

Below code should work
Markup
<div class="item item-text-wrap">
<p ng-repeat="school in schools">{{school.nameOfInstitution}} -
{{level.schoolLevel | filter: school.schoolLevel : true }}</p>
</div>
Code
$scope.level = {
"schoolLevel": [
{"01302": "All levels"},
{"01304": "Elementary"},
{"02400": "Middle"},
{"02402": "High school"}
]
}

Related

How Can I make a list automatically with Json for my Angular project?

My json is :
{
"exp": [
{
"first": "bla",
"second": "blabla",
"desp": [
{
"line": "Instant Apzel bestseller"
},
{
"line": "Translated into 18 languages"
},
{
"line": "Most Recommended Book of the year."
},
{
"line": "A neglected project, widely dismissed, its champion written off as unhinged."
},
{
"line": "Yields a negative result in an experiment because of a flaw in the design of the experiment"
},
{
"line": "An Amazon, Bloomberg, Financial Times, Forbes, Inc., Newsweek, Strategy + Business, Teech Crunch, Washinton Post Best Business Book oof the year"
}
]
}
]
}
in html with angular how can I call this json data with easyly?
Cause now I do like that;
<p>{{item.description.desSummary}}</p>
<ul class="desc-content">
<li>{{item.description.desList.lineMono}}</li>
<li>{{item.description.desList.lineDi}}</li>
<li>{{item.description.desList.lineTri}}</li>
<li>{{item.description.desList.lineTetra}}</li>
<li>{{item.description.desList.linePenta}}</li>
<li>{{item.description.desList.lineHexa}}</li>
</ul>
and json like that:
"desList": {
"lineMono": "Instant Apzel bestseller",
"lineDi": "Translated into 18 languages",
"lineTri": "Most Recommended Book of the year.",
"lineTetra": "A neglected project, widely dismissed, its champion written off as unhinged.",
"linePenta": "Yields a negative result in an experiment because of a flaw in the design of the experiment",
"lineHexa": "An Amazon, Bloomberg, Financial Times, Forbes, Inc., Newsweek, Strategy + Business, Teech Crunch, Washinton Post Best Business Book oof the year"
}
I want to do that with just one code block like this:
> <div *ngFor=let item of exp>
> <ul><li>{{item.desp.line}}<li/><ul/>
> <div/>
How can I do like that. I tryed but there is some problems.
Use this way -
<div *ngFor="let item of data.exp" class="item">
<p class="first">{{ item.first }}</p>
<p class="second">{{ item.second }}</p>
<div class="desp-list" *ngFor="let desp of item.desp">
<p class="desp-item">{{ desp.line }}</p>
</div>
</div>
See this working example here with your data.
Edit: See a working example with data from a json file, here

Is there a method to display data from api where the id key is taken from another key?

JSON Data:
"abcd":[
{
"id":"1",
"cityId":"2",
},
{
"id":"2",
"cityId":"3",
}
],
"city":[
{
"id":"2",
"cityName":"california"
},
{
"id":"3",
"cityName":"vicecity"
}
]
Angular:
<div *ngFor="let clg of abcd$">
<p>
{{clg.cityId}}
<!-- Here i need to print the cityname from city by using the cityId we have got from abcd -->
</p>
</div>
app.component.ts:
ngOnInit() {
this.data.getColleges().subscribe(
data => this.abcd$ = data
)
}
fetching data from "abcd" is perfectly working....and no problem in fetching the datas from "city" too. But is it possible to fetch the cityName from "city" by using the cityId key from the "abcd" section.
You can use a method to get city by ID:
app.component.ts:
getCityByID = (cityID) => {
return this.city$.find(item => item.id === cityID);
}
Template:
<div *ngFor="let clg of abcd$">
<p>
{{ clg.cityId }}
{{ getCityByID(clg.cityId).cityName }}
</p>
</div>
Update
As far as I understand, you are fetching colleges and cities with 2 separate observables. Because of this, when you are trying to get city by ID, it may (or may not) throw an error if second observable has not been resolved yet. So, you need to combine/join these two streams together. I prefer combineLatest to do this but forkJoin will work as well.
In app.component.ts:
import { combineLatest } from 'rxjs';
......
ngOnInit() {
combineLatest(
this.data.getColleges(),
this.data.getCity()
).subscribe(([colleges, cities]) => {
this.abcd$ = colleges;
this.city$ = cities;
});
}
This way, you make sure that both abcd$ and city$ are inited. Hope this helps.
For further reading:
combineLatest: https://www.learnrxjs.io/operators/combination/combinelatest.html
forkJoin: https://www.learnrxjs.io/operators/combination/forkjoin.html

Get nested values from JSON with angularJS

I need to get nested products from JSON to my html in <div ng-repeat="order in orders"></div> I tried many versions of getting products values(name, description etc.) but none of them works. How to do this ?
JSON:
[
{
"id":3,
"date":"00:00:00",
"user":{
"id":1,
},
"orderState":{
"id":1,
},
"products":[
{
"id":1,
"name":"Bosch POF 1200",
"description":"1200W",
"enabled":true,
"price":459,
},
{
"id":9,
"name":"Graphite 58G782",
"description":"a",
"enabled":true,
"price":429,
}
]
}
]
Controller
OrdersService.retrieveAllByCurrentUser().then(function(response) {
$scope.orders = response.data;
console.log(response.data);
}, function(error) {
registerError(error, 'retrieving all orders');
});
The ng-repeat directive creates a new scope, which means that you should be able to loop through the products within it like this:
<div ng-repeat="order in orders">
<div ng-repeat="product in order.products"> e.g. {{product.name}} </div>
</div>
I would also advise to write a directive for dealing with that kind of stuff, because your code can get unreadable really fast. Don't take my word for it though as I am no Angular expert.
Create a nested ng-repeat like this to access the products information:
<div ng-repeat="order in orders">
<div ng-repeat="product in order.products">
<h1 ng-bind="product.name"></h1>
<p ng-bind="product.description"></p>
</div>
</div>
For each order it will go into order.products and loop out the information as product, then you can access the information in product via dot notation, like product.name for example.
You can do nested ng-repeat in html
<div ng-repeat="order in orders">
<div ng-repeat "product in order.products">
<span>{product.name}}</span>
<span>{{product.description}}</span>
</div>
</div>

Angular orderBy object possible?

I have a JSON object representing calendar dates. These are added through a CMS and I'd like to be able to filter them based on date. My schema set-up has made this more difficult than I thought. Is it possible to orderBy the day value in this JSON object or is there a filter workaround?
Here is my JSON object:
{
"_id" : ObjectId("53f252537d343a9ad862866c"),
"year" : {
"December" : [],
"November" : [],
"October" : [],
"September" : [],
"August" : [],
"July" : [
{
"day" : "21",
"title" : "Event Title",
"summary" : "Event Summary",
"description" : "oEvent Description",
"_id" : ObjectId("53f252537d343a9ad862866d")
}
],
"June" : [],
"May" : [],
"April" : [],
"March" : [],
"February" : [],
"January" : []
},
"__v" : 0
}
Here is my view which already uses a custom filter to filter by month. The orderBy is not functioning but I've left it in as a placeholder to show where I'd like to set the functionality.
<div class="calDynamic" data-ng-repeat="n in [] | range:100">
<div ng-repeat="cal in calendar[n].year | filterKey:month">
<div ng-if="cal != '' ">
<div class="calendar">
<div ng-repeat="item in cal | orderBy: 'key.day' ">
<a href="/events/{{item.day}}">
<article class="eventslist">
<div class="numberedDate">
<h3>{{item.day}}</h3>
</div>
<div class="calInfo">
<h5>{{item.title}}</h5>
<p>{{item.summary}} <a>more</a></p>
</div>
</article>
</div><!-- ng-repeat val,key -->
</div><!-- calendar -->
</div><!-- ng-if cal -->
</div><!-- ng-repeat cal -->
</div><!-- calDynamic -->
You should be able to define a custom sort function that sorts by any item in your object. The key bit is to convert the object to an array in the filter function.
Here's an example:
app.filter('orderByDayNumber', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
You would then call it like this:
<div ng-repeat="(key, val) in cal | orderByDayNumber: 'day' ">
Note, you shouldn't write val.day as that is assumed.
Look at this great blog post here for more info.
EDIT: In fact, it looks like your structure is actually already an array, so while this technique will still work, it may not be necessary - it might have just been the way you were adding the parameter to orderBy that was causing issues.

HandlebarsJS - How to display nested JSON

I have this Backbone App where I display my data/json with HandlebarsJS.
Now my API returns nested JSON data:
{
"Live": [
{
"artist_name": "some artist",
"video_title": " some video title",
"video_thumbnail": "some thumbnail"
}
],
"Others" : [
{
"artist_name": "some artist",
"video_title": " some video title",
"video_thumbnail": "some thumbnail"
}
]
}
I tried to do
{{#each Live}}
<div>
<img src="{{video_thumbnail}}">
<h2>{{video_title}}</h2>
<h2>{{artist_name}}</h2>
</div>
{{/each}}
But that did not work...
Anyone who know what to do? thanks in advance...
Handlebar templates can be used in two ways.
1. We can save the file with (.hbs)
2. Second way is we need the handlebar template in script tag. Provided same in [jsfiddle][1] , I have provided link, you can check the below link
[1]: https://jsfiddle.net/trilokvallamkonda/cLgzf21y/13/