reference a json field name that contains a dot - javascript

I am trying to reference a field from the JSON in Angular
{ "elements": [
{
"LCSSEASON.IDA2A2": "351453",
"LCSSEASON.BRANCHIDITERATIONINFO": "335697"
},
{
"LCSSEASON.IDA2A2": "353995",
"LCSSEASON.BRANCHIDITERATIONINFO": "298931"
},
{
"LCSSEASON.IDA2A2": "310935",
"LCSSEASON.BRANCHIDITERATIONINFO": "282654"
},
{
"LCSSEASON.IDA2A2": "353967",
"LCSSEASON.BRANCHIDITERATIONINFO": "353966"
},
{
"LCSSEASON.IDA2A2": "355294",
"LCSSEASON.BRANCHIDITERATIONINFO": "355293"
}
]
}
In the HTML Template, I want to print the element - elements.LCSSEASON.IDA2A2
But having 2 dots in key is causing issues in below code
Any ideas and suggestions??
I cannot change server JSON Output as its legacy application and I have no control.
<ul *ngFor="let item of items"> <li> {{item.LCSSEASON.IDA2A2}} </li> </ul>

access the property using square brackets like this
<ul *ngFor="let item of items"> <li> {{item['LCSSEASON.IDA2A2']}} </li> </ul>

Related

How to get nested JSON data by using ng repeat in angularjs

I'm trying to getting items._id value in ng view by using ng-repeat.
occurring all data but i want specific data.
data.json
[ { _id : "td6v9db4514cc4ewew4334",
firstName : 'ayaz',
lastName : 'memon',
items : '[{"_id":"item2","_name":"My Item #4"},
{"_id":"item3","_name":"My Item #4"}]',
totalItems : 3,
totalPrice : 2999.97 } ]
Controller
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json").then((response) => {
console.log(response.data)
$scope.userInfo = response.data
})
})
ng view
<body ng-app="myApp">
<div ng-controller="myCtrl">
<ul ng-repeat="x in userInfo">
<li >{{x}}</li>
</ul>
Here you are using nested json object ie items in userInfo, you can write ng-repeat as,
<body ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in userInfo.items">{{x._id}}</li>
</ul>
Note: It will be good to understand if you use ng-repeat in <li></li> instead of <ul></ul>
Try using nested ng-repeat like this:
<ul ng-repeat="user in userInfo">
<li ng-repeat="x in user.items">{{x._id}} : {{x._name}}</li>
</ul>
I'm assuming your http call will return a valid response because the Json data you've given is invalid. The keys need to be in enclosed within " ". I've also structured the the ng-repeat assuming that your response will have multiple objects
Try this,
[{
"_id": "td6v9db4514cc4ewew4334",
"firstName": "ayaz",
"lastName": "memon",
"items": [{
"_id": "item2",
"_name": "My Item #4"
},
{
"_id": "item3",
"_name": "My Item #4"
}
],
"totalItems": 3,
"totalPrice": 2999.97
}]
and you could get your repeated "_id" in the items now in ng-repeat="item in userInfo.items" and with {{item._id}} .
Please correct me if there's any mistake, I'm still new.
Thanks.
I was trying to retrieve string as an object that was a mistake. I used object data instead of string and got result.
This is worked for me:
<ul>
<li ng-repeat="user in userInfo">
<ul>
{{user._id}}
<li ng-repeat="item in user.items">
{{item._id}}
</li>
</ul>
</li>
</ul>
Plunker Example:
http://plnkr.co/edit/hzWdj2IiUI2RytYVUI7m?p=preview

dynamically Build ng-template using list

I am trying to build ng-template dynamically, In the Data structure, I have a Object that contains list of object of same type or other type of object.
[
{
type: "device",
id: 1,
allowedTypes: ["device","action"],
max: 5,
columns: [
{
type: "action",
id: "1"
},
{
type: "device",
id: 2,
allowedTypes: ["device","action"],
max: 5,
columns: [
{
type: "action",
id: "1"
},
{
type: "action",
id: "2"
}
]
}
]
}
]
My ng-template code:
<script type="text/ng-template" id="and.html">
<div class="container-element box box-red">
<h3>And {{item.id}}</h3>
<ul dnd-list="item.columns"
dnd-allowed-types="item.allowedTypes"
dnd-disable-if="item.columns.length >= item.max">
<li ng-repeat="element in item.columns"
dnd-draggable="element"
dnd-effect-allowed="move"
dnd-moved="item.columns.splice($index, 1)"
dnd-selected="models.selected = element"
ng-class="{selected: models.selected === element}"
ng-include="element.type + '.html'" onload="onloadAction()">
</li>
</ul>
<div class="clearfix"></div>
</div>
</script>
In the ng-template code the first level or different types of object can easily be added, however same type of object does not work properly when added in the 2nd level, it seems the its going in a recursive loop.
This is because the nested ng-template (child) ng-template use of root item.columns from the ng-repeat="element in item.columns".
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'">
</li>
any advise how to resolve this issue.
I have managed to resolve this issue, ng-repeat create a new child scope, however the item from the parent scope is also visible to in the child scope, as this is recursive that mean child template and parent template both have the variable with the same name called item. However the child scope variable item is ignored:
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'">
</li>
in the above snippet the element also has a variable called item, so in the child scope when we call item.columns the item variable of parent is invoked again, to ensure that the item variable of child is not ignored, we need to use ng-init with ng-include and set the current element as item in the child scope as shown below:
<li ng-repeat="element in item.columns"
dnd-draggable="element"
ng-include="element.type + '.html'" ng-init="item=element">
</li>
To read more on this please visit
http://benfoster.io/blog/angularjs-recursive-templates

Angular, connect objects and display right information

I'm creating an angular webapp, listing different cars in a sidebar and some information about the specific car in a informationbox.
The purpose is to show the right information in the box when clicking the different cars.
I have two different arrays(two API-endpoints), where the first array lists the car name, and the other one got the information about the car. But I have no idea how to connect the objects with the primary key and the foreign key, and how I'm supposed to output the right information after clicking the car.
app.js:
angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
function fetch() {
$http({method : 'GET',url : 'http://*cars*'})
.success(function(data) {
$scope.cars = data;
});
$http({method : 'GET',url : 'http://*information*'})
.success(function(data) {
$scope.information = data;
});
}
fetch();
})
html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
For now all I have done is that I've fetched the data and outputed the cars in the sidebar. But now I've been googling and trying to connect the cars to the information with loops and functions for hours, but stil clueless.
Yes, I'm new to this. Any kind of help would be great! Thanks
You can deal with this with the ng-route. You can do something like :
In your route definition:
.when(/cars/:Id), {
name: 'cars',
templateUrl : 'ayourtemplate.html',
controller : 'yourCtrl'
})
In your html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
The Id will be your key tou will just have to match the right key in your $scope.information
It depends on what information those arrays contains.
If you're sure, that every element corresponds to other, you can just use $index in the html.
<li ng-repeat="name in cars">
{{ name.displayName }}
<p>{{ information[$index] }}</p>
</li>
However, if elements in array aren't ordered, you will have to check primary keys of objects in arrays. Let's assume, that data in arrays looks like this:
cars:
[
{ id: "1", name: "Carrera GT" },
{ id: "2", name: "DB 11" },
... and so on
]
information:
[
{ id: "2", info: "Lorem ipsum" },
{ id: "1", info: "Dolor sit amet" },
...
]
Then I'd suggest using loops and constructing new array using ids.
var carinfo = [];
cars.forEach(car => {
obj["id"] = car.id;
obj["name"] = car.name;
obj["info"] = ""; // Placeholder
info.forEach(c => {
if (c.id === car.id) {
obj["info"] = c.info;
}
});
carinfo.push(obj);
});
$scope.carInfo = carinfo;
Then you can use $scope.carInfo in the html file.
<li ng-repeat="car in carInfo">
{{ car.name }}
<p>{{ car.info }}</p>
</li>

AngularJS - Display complex JSON data with a single ng-repeat

I am trying to display all the books of some series. I used nested ng-repeat and it works well. However, due to some recent changes on layout requirements, I cannot use nested ng-repeat (I want a single list of books). I would expect something like below
<ul>
<li>book1 of series1</li>
<li>book 2 of series 1</li>
<li>book1 of series 2</li>
<li>book2 of series 2</li>
<li>book1 of series 3</li>
<li>book2 of series 3</li>
</ul>
Is there a way to do it with 1 ng-repeat? Or with other approach? (I.e. Array)
Data
var data = {
"records": [
{
"name": "Spectrum Series",
"seriesid": "SpectrumSeries",
"book": [
{
"name": "White Curse",
"bookid": "WhiteCurse",
"image": "book1"
},
{
"name": "Blue Fox",
"bookid": "BlueFox",
"image": "book2"
}
]
}
… other series
]
};
Controller
$scope.serieslist = data.records;
HTML
<div ng-repeat="series in serieslist">
<ul ng-repeat="book in series.book">
<li>
<div>{{series.name}}</div>
<div>{{book.name}}</div>
</li>
</ul>
</div>
Since you want only one list of books, try this
<div ng-repeat="series in serieslist">
<li>
<div>{{series.name}}</div>
<div>{{series.book[0].name}}</div>
</li>
</ul>
</div>
Hope this helps!!!
You need to flatten the array first in your controller into an array with series number and book number, and then use the ng-repeat on the new array.
To do that you can use two angular.forEach on the original array (one for the series and other for the books in each series).
$scope.serieslist = [];
var seriesNumber = 1;
angular.forEach(data.records, function(series) {
var bookNumber = 1;
angular.forEach(series.book, function(book) {
$scope.serieslist.push(
{
seriesNumber: seriesNumber,
bookNumber: bookNumber++,
seriesid: series.seriesid,
name: series.name,
book: book
});
});
seriesNumber++;
});
Here's a plnkr
Working JS fiddle
Just replace element of DOM for use nested ng-repeat
<div ng-app='Your app'>
<div ng-controller='Your controlelr'>
<ul ng-repeat="series in serieslist">
{{series.name}}
<li ng-repeat="book in series.book" >{{ book.name }}</li>
</ul>
</div>
</div>
or
<div ng-app='myApp'>
<div ng-controller='Home'>
<ul ng-repeat="series in serieslist">
<li ng-repeat="book in series.book" >{{ book.name }} of {{series.name}}</li>
</ul>
</div>
</div>
for this result
You can use something like underscorejs to produce a flattened version of your list and then ng-repeat over that. For how you might do that, refer to Karl's answer on this stackoverflow question here: How to flatten with ng-repeat
Controller
$scope.serieslist = data.records;
$scope.flatbooklist = [];
angular.forEach($scope.serieslist, function (series)
{
angular.forEach(series.book, function (book)
{
$scope.flatbooklist.push({seriesname: series.name, seriesid: series.seriesid, bookname: book.name, bookid: book.bookid, bookimage: book.image});
});
});
HTML
<ul ng-repeat="book in flatbooklist">
<li>
<div>{{book.seriesname}}</div>
<div>{{book.bookname}}</div>
</li>
</ul>

Nested lists in Angular JS

I am trying to create JSON to use for a nested list.
I assume I am using incorrect syntax on the second ng-repeat:
<ul>
<li ng-repeat="n in navData">Label = {{n.label}}</li>
<ul>
<li ng-repeat="n.children in n">Child label = {{p.label}}</li>
</ul>
</ul>
When my data model is
var nav = [{
label: 'Pages',
value: 'pages',
children: [{
label: 'Home',
value: 'home'
}, {
label: 'Left Nav',
value: 'left-nav'
}]
}, {
label: 'Components',
value: 'components'
}];
All I am getting in the html is the top level:
Label = Pages
Label = Components
Outer li tag should close after inner li tag with ng-repeat. And you should use different var name and slightly different expression (actually you have name your var as p {{p.label}} somewhere but not in nested loop):
<ul>
<li ng-repeat="n in navData">Label = {{n.label}}<!-- closing li removed //-->
<ul>
<li ng-repeat="p in n.children">Child label = {{p.label}}</li>
</ul>
</li> <!-- closing li tag added //-->
</ul>

Categories