I am trying to display the contents to the user from JSON Array using the ng-repeat
option. The JSON Array
is created dynamically so I am bit confused how to display the same to users.
The syntax of the JSON ARRAY
is as follows, the content of COMPLEX key
can increase or decrease dynamically:
jsonList = [
{
name : "AB",
local : "CD",
complex : [
name : "EF",
local : "GH",
complex : [
name : "IJ",
local : "LL".
complex : ........
]
]
},
{
name : "PQ",
local : "RS",
complex : [
name : "TU",
local : "VW",
complex : [
name : "XY",
local : "Z1".
complex : ........
]
]
}
......
];
I am just confused how can display this to users.
I want it to look something like this where the user has the option to add the complex
values at every step using the Add Another
option:
I am really confused how to store the values in JSON Array
automatically and loop though it using the ng-repeat
and display to users automatically. Since the JSON Array
is not fixed and can vary at every point, can someone please help me with some logic on how to proceed for this issue.
I tried to display in HTML Table
but confused how to loop when there is so many complex
objects.
I'd use a self-referencing component. I have an example here, based on your data. Note that the component uses itself in its template. This makes sure that it can continue forever if it wants to
function myComponentController() {
this.addNode = function(el) {
el.complex.push({
name: "New name",
local: "New local",
complex: [],
});
}
}
const myComponentConstructor = {
controller: myComponentController,
controllerAs: "$ctrl",
bindings: {
data: '=',
},
template: `
<div ng-repeat="el in $ctrl.data" class="block">
<span>Name: {{el.name}}</span>
<my-component data="el.complex"></my-component>
<button ng-click="$ctrl.addNode(el)">Add another</button>
</div>
`,
}
const app = angular
.module("app", [])
.component("myComponent", myComponentConstructor);
.block {
border: solid 1px red;
padding: 5px;
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<my-component data='[{
name: "AB",
local: "CD",
complex: [{
name: "EF",
local: "GH",
complex: [{
name: "IJ",
local: "LL",
complex: []
}]
}]
},
{
name: "PQ",
local: "RS",
complex: [{
name: "TU",
local: "VW",
complex: [{
name: "XY",
local: "Z1",
complex: []
}]
}]
}]'></my-component>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With