Show json with AngularJS - json

Im new to AngularJS. Now I have a json object from my spring controller, how do i use/print in my jsp?
I tried something like this. the console shows the json perfectely, and with angular it does not...
<div data-ng-init="stats=${stats}">
<li data-ng-repeat="stat in stats">{{stat.name}}</li>
</div>
<script>
console.log(${stats});
</script>
Json:
{ "Types": [{"name": "study", "value":0},{"name": "health", "value":0},{"name": "culture", "value":0},{"name": "nightlife", "value":0},{"name": "other", "value":0},{"name": "friendship", "value":0}] })

Because JSON string must be properly quoted if placed into HTML attribure value, you either escape " characters in JSON or probably better use ' quotes for ngInit:
<div data-ng-init='stats=${stats}'>
<li data-ng-repeat="stat in stats.Types">{{stat.name}}</li>
</div>
Demo: http://plnkr.co/edit/XLIE9VCSn9gL3oO6ULol?p=info

You need to reference the array property of stats.
<li data-ng-repeat="stat in stats.Types">{{stat.name}}</li>

Related

How present JSON List in Angular HTML with *ngFor

I get a result in the JSON Format like these sample from a webservice.
How can i iterate over this items to prensent the objects
HTML Code - not working
<div *ngFor="let item of List">
{{item.Code}}
</div>
JSON Sample
"List": {
"0": {
"Code": "A"
},
"1": {
"Code": "B"
},
"2": {
"Code": "C",
}
}
unfortunally the webservice does not provide this as an Array [] of objects
I want to see the list of all items für the Key "Code"
You can use KeyValuePipe like here.
So the your code would be something like this:
<div *ngFor="let item of List | keyvalue">
{{item.value.Code}}
</div>
As it was not working with
<div *ngFor="let item of List | keyvalue">
{{item.value.Code}}
</div>
Typescript was throwing an error because {{item.value.Code}} was not known.
I did some additional research and found the following solution
<div *ngFor='let key of objectKeys(List)'>
{{List[key].Code}}
</div>
in the typescript class corresponding to the html file you have to add
objectKeys = Object.keys;

when using a GET method data is coming in console not in HTML

I have written my get method inside ngOnInIt(). When I am printing data in console it is visible, but when printing in HTML using interpolation, it is returning [ object object]
{{filteredCourses}} ==> [object object]
and when i am using {{course.category|json}} so here i am getting all values of array ["course" : "database" , "category" : "database" , "length" : "2hr" ] thats how the value is coming
html :-
<div class="courses" fxLayout="row wrap" fxLayoutAlign="center" [#animateStagger]="{value:'50'}">
<div class="course" *ngFor="let course of filteredCourses" fxFlex="100" fxFlex.gt-xs="50"
fxFlex.gt-sm="33" [ngClass]="course.category" [#animate]="{value:'*',params:{y:'100%'}}">
<div class="course-content" fxLayout="column" fxFlex="1 1 auto">
<div class="header" fxLayout="row" fxLayoutAlign="center center"
[ngClass]="course.category + '-bg'">
<div class="category" fxFlex>
{{course.category|json}}
</div>
</div>
</div>
Code:
filteredCourses: any[];
this.product_name = getProduct()['name'];
console.log(this.product_name);
this.token = getToken();
this.httpHeaders = new HttpHeaders({ "Authorization": "Bearer " + this.token });
this._httpClient.get('http://127.0.0.1:8000/api/products/info/'+this.product_name+'/',{headers: this.httpHeaders})
.subscribe(
data => {
this.product = data;
this.courses = data['cources'];
this.filteredCourses = this.courses;
console.log(this.filteredCourses);
},
error => {
console.log(error);
}
);
try using JSON.stringify(yourObject) or maybe in certain cases you can use Object.keys().
You need to use loop if its an array of object or you might want to print the properties of object individually.
But if you want to see the object filteredCourses in template, use json pipe.
{{filteredCourses | json}}
In case you need help to print values using *ngFor or properties, do let us know.
I suppose filteredCourses collection contains an array of objects. So you need to iterate through filteredCourses using ngFor directive to render data in the HTML template.
Like:
<ul>
<li ngFor="let item of filteredCourses">{{item.courseName}}</li>
</ul>

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 Json Looping

Hi I am new to angular I have a requirment as follows.
app.js
$scope.fields = {
"fields": {
"LastName1": "ABC",
"FirstName1": "XYZ",
"LastName2": "123",
"FirstName2": "345",
"LastName3": "PQR",
"FirstName3": "ASD",
}
};
In my html I need to loop over this and display in
index.html
<tr ng-repeat="key in fields">
this doesn't seem to work. Please help.
I want my output as
LastName1 ABC
FirstName1 XYZ
and so on.
Also If user makes any changes to this, I want to be able to push the changes back to fields Json. Please help.
You can use the (key, value) in object syntax.
In your case :
<div ng-repeat="(key1, value1) in fields">
<li ng-repeat="(key2, value2) in value1">{{key2}} : {{value2}}</li>
</div>.
But :
You need to be aware that the JavaScript specification does not define
the order of keys returned for an object. (To mitigate this in Angular
1.3 the ngRepeat directive used to sort the keys alphabetically.)
Version 1.4 removed the alphabetic sorting. We now rely on the order
returned by the browser when running for key in myObj. It seems that
browsers generally follow the strategy of providing keys in the order
in which they were defined, although there are exceptions when keys
are deleted and reinstated. See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
If this is not desired, the recommended workaround is to convert your
object into an array that is sorted into the order that you prefer
before providing it to ngRepeat. You could do this with a filter such
as toArrayFilter or implement a $watch on the object yourself.
More details : https://docs.angularjs.org/api/ng/directive/ngRepeat
Edit : What if you want to change the object now ?
You can't do :
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="value2" /><br />
{{key2}} : {{value2}}
</li>
</div>
Why ? Because ng-model will change value2 in the current scope, and not in your object fields as you don't use dot notation.
For each item/iteration, ng-repeat creates a new scope, which
prototypically inherits from the parent scope, but it also assigns the
item's value to a new property on the new child scope.
More details : https://github.com/angular/angular.js/wiki/Understanding-Scopes
But you can do :
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="fields[key1][key2]" /><br />
{{key2}} : {{value2}}
</li>
</div>
Take a look !!!
Try change to:
<tr ng-repeat="(key, value) in fields.fields">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
Here is a working plunker where you can update the model: http://jsfiddle.net/ttgfybk0/1/
Repeat data is in object format like
{
"LastName1": "ABC",
"FirstName1": "XYZ",
"LastName2": "123",
"FirstName2": "345",
"LastName3": "PQR",
"FirstName3": "ASD",
}
use the ng-repeat="(key, value) in expression"
<tr ng-repeat="(key, value) in fields.fields">
<td>{{key}} {{value}}</td>
</tr>
working example ishttp://plnkr.co/edit/Y5lPH1?p=preview

How can I ensure that my Backbone forms return data that's formatted the same way as it came in?

In short:
When using Backbone and Underscore templates, what's the best way to ensure that the data in a form is formatted in the exact same way when POSTed to the server as it was when it was initially fetched?
Longer question:
I'm currently using Backbone’s fetch() to retrieve some data from the server as JSON. On success I'm taking that JSON and using the data in an Underscore template like so:
<div class="module-content">
<form>
<div class="customer-primary">
<% if (ParentCompany) { %>
<div class="row">
<div class="label">Parent Company</div>
<div class="value">
<div class="current-value"><%= ParentCompany %></div>
<div class="editable-value"><input name="ParentCompany" value="<%= ParentCompany %>"></div>
</div>
</div>
<% } %>
<% if (Title) { %>
<div class="row">
<div class="label">Title</div>
<div class="value">
<div class="current-value"><%= Title %></div>
<div class="editable-value"><input name="Title" value="<%= Title %>"></div>
</div>
</div>
<% } %>
…
</div>
</form>
</div>
The JSON has a number of children with multiple entries, like this:
{
"UserID":"12345",
"FirstName":"Brandon",
"Ship": {
"Address1":"33 One Two Ave",
"Address2":"#23D",
"Address3":"",
"City":"New York",
"State":"NY",
"Country":"United States",
"Zip":"10023"
},
"Phones": [
{
"Kind":"Tel",
"Number":"512-123-4567"
},
{
"Kind":"Fax",
"Number":"512-123-4567"
}
]
}
How can I ensure that I build the form out in such a way that it returns an object that's formatted in the same way for easy DB updates?
Please let me know if you need more info!
If I understand your question, you're trying to make sure the JSON data structure matches what the server expects when you're sending data. (And coincidentally, that it's in the same structure that you received from the server.)
What you want to do is override the model's toJSON function so your data is serialized as expected. Then, when it gets persisted by Backbone.sync, the proper data structure will be sent to the remote API.
Take a look at these:
Saving Backbone model and collection to JSON string
backbone.js: overwritting toJSON
I think the best you can do is to validate your model. and make the fields that you need to be sent required, if you need all of them ,then validate your entire model.
This plugin is a good option for this task.
https://github.com/fantactuka/backbone-validator