Using ng-repeat with dynamic value - html

I have HTML that is rendered based on loaded metadata. It ends up forming a table of data based on a scoped value in the controller.
In the controller:
$scope.arrayOfCustomObjects = [{ entry: data1 },{ entry: data2 }];
The metadata is contained in a .json file, with the following format (I added two here, in reality there are hundreds, each one basically ends up describing an HTML element):
loadedMetaData:
{
"field_1": {
"index": 0,
"type": "selectbox",
"nameId": "arrayOfCustomObjects" <-- this is the string name of a scoped variable in a controller.
},
"field_2": {
"index": 1,
"type": "textinput",
"nameId": "textField"
}
}
And the HTML looks like this:
<div ng-repeat="field in loadedMetaData>
<div ng-repeat="item in field.nameId">
<!-- build out HTML for each -->
</div>
</div>
When I run this, it doesn't work (it never iterates over $scope.arrayOfCustomObjects). If I add a line to display {{field.nameId}} is displays 'arrayOfCustomObjects' but I think it's just the string, not the value it represents.
If I change the HTML to this it does work:
<div ng-repeat="field in loadedMetaData>
<div ng-repeat="item in arrayOfCustomObjects">
<!-- build out HTML for each -->
</div>
</div>
...but is there any way to keep the abstraction I'm going for? I'd like to be able to define the target array in the metadata so I don't have to define the controller-specific names in the HTML itself.

Suppose that your loadedMetadata is like:
[
"arrayOfCustomObjects",
// other 'data' object keys
]
Then you could have an object like this that stores your actual data:
data = {
"arrayOfCustomObjects": [
// some items
]
}
Then, in the template you do:
<div ng-repeat="field in loadedMetaData>
<div ng-repeat="item in data[field]">
<!-- display the items in arrayOfCustomObjects -->
</div>
</div>

This takes the value as string
var field = { "nameId": "arrayOfCustomObjects" }
change this to
var field = { "nameId": arrayOfCustomObjects }

Use a bracket notation property accessor with the this keyword:
<div ng-repeat="(fieldKey, fieldValue) in loadedMetaData>
<div ng-repeat="item in this[fieldValue.nameId]">
<!-- build out HTML for each -->
</div>
</div>
From the Docs:
It is possible to access the context object [($scope)] using the identifier this and the locals object using the identifier $locals.
— AngularJS Developer Guide - Expression Context

To achieve expected result, use below changes from your plunker code
Using scope function to convert string to scope variable
Rendering that variable inside inner ng-repeat
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.arrayOfCustomObjects = [1,2,3]
$scope.loadedMetaData = {
"field_1": {
"index": 0,
"type": "selectbox",
"nameId": "arrayOfCustomObjects"
},
"field_2": {
"index": 1,
"type": "textinput",
"nameId": "textField"
}
}
$scope.getVariable = function(val){
return $scope[val]
}
});
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl as ctrl">
<div>
<div ng-repeat="field in loadedMetaData">
<div ng-repeat="item in getVariable(field.nameId)">
{{item}}
</div>
</div>
</div>
</div>
</body>
</html>
codepen - https://codepen.io/nagasai/pen/XGLZzX

Related

How to implement nested data form in angular2

Here is Json schema :
{
"_id" : ObjectId("59031d77fd5e1c0b3c005d15"),
"resume_data" : {
"work_experience" : [
{
"company" : "example",
"website" : "example.com",
"position" : "Internship",
"highlights" : "Learn To Create API In Laravel Framework. and also Learn Angular 2 for Front end Development.",
"project_experience" : [
{
"projectName" : "Fb Project",
"teamMember" : "5",
"technology" : "PHP,Laravel-5,Angular-2,MongoDb",
"projectPosition" : "Back-end Developer"
}
]
}
]
}
}
Here is image:
I have reference of this answer but i don't know about nested form data. can anyone explain how to implement it.
Here is your code, which sets the data you are receiving from backend, here I have stored it in a variable data.
Please notice, this is a shortened version of your form, but the basics are there, you only need to add the few missing properties in corresponding form arrays.
The build of the empty form looks is just a FormArray named work_experience matching your json structure:
this.myForm = this.fb.group({
work_experience: this.fb.array([])
})
We add the fields when you are receiving the data, call a function called setWorkExperience in the callback when receiving data:
setWorkExperience(){
// get the formarray
let control = <FormArray>this.myForm.controls.work_experience;
// iterate the array 'work_experience' from your JSON and push new formgroup with properties and the inner form array
this.data.work_experience.forEach(x => {
// add the rest of your properties also below
control.push(this.fb.group({company: x.company, project_experience: this.setFormArray(x)}))
})
}
setFormArray is called from the previous function, where we patch the data with from project_experience to the inner form array:
setFormArray(x) {
// create local array which is returned with all the values from the 'project_experience' from your JSON
let arr = new FormArray([])
x.project_experience.map(y => {
// add the rest of your properties below
arr.push(this.fb.group({projectName: y.projectName}))
})
return arr;
}
The template would then look like this:
<form [formGroup]="myForm">
<!-- Outmost array iterated -->
<div formArrayName="work_experience">
<div *ngFor="let a of myForm.get('work_experience').controls; let i=index">
<h3>COMPANY {{i+1}}: </h3>
<div formGroupName="{{i}}">
<label>Company Name: </label>
<input formControlName="company" /><span><button (click)="deleteCompany(i)">Delete Company</button></span><br><br>
<!-- inner formarray iterated -->
<div formArrayName="project_experience">
<div *ngFor="let b of myForm.controls.work_experience.controls[i].controls.project_experience.controls; let j=index">
<h4>PROJECT {{j+1}}</h4>
<div formGroupName="{{j}}">
<label>Project Name:</label>
<input formControlName="projectName" /><span><button (click)="deleteProject(a.controls.project_experience, j)">Delete Project</button></span>
</div>
</div>
<button (click)="addNewProject(a.controls.project_experience)">Add new Project</button>
</div>
</div>
</div>
</div>
</form>
In the template you can see the buttons for add and delete of projects and companies. Adding and deleting companies are straightforward, where initCompany() returns a formGroup:
deleteCompany(index) {
let control = <FormArray>this.myForm.controls.work_experience;
control.removeAt(index)
}
addNewCompany() {
let control = <FormArray>this.myForm.controls.work_experience;
control.push(this.initCompany())
}
In the add project we pass as parameter from the template the current formArray control, to which we just push a new FormGroup:
addNewProject(control) {
control.push(this.initProject())
}
In the delete function we pass the current formarray as well as the index of the project we want to delete:
deleteProject(control, index) {
control.removeAt(index)
}
That should cover pretty much everything.
Plunker
Please Check it Out This
Plunker Here
Json Store Like This
{
"name": "",
"work_experience": [
{
"name": "asdasd",
"project_experience": [
{
"Project_Name": "asdasdasd"
},
{
"Project_Name": "asdasdasd"
}
]
}
]
}

generating with angularJS HTML from JSON-Objects

I'm developing an app with the Ionic framework based on angularjs. I'd like to let generate HTML elements or components from a JSON file. These are buttons, lists, labels, etc.
My JSON objects look like this:
[
{
"category": "communicationPage",
"type": "Button",
"id": "communicationButton",
"icon": "ion-chatboxes",
"name": "Communication",
"onClick": "window.location.href='communicationPage.html'",
"ngclick": "open()",
"ngcontroller": "openctrl",
"color": "white",
"background-color": "#ff5db1",
"font-size": "20px"
},
{
"category": "servicePage",
"type": "Button",
"id": "serviceButton",
"icon": "ion-briefcase",
"name": "Service",
"onClick": "window.location.href='servicePage.html'",
"color": "blue",
"background-color": "#009900",
"font-size": "26px"
}
]
I can access via my Controller on the JSON file and parse as follows:
myApp.controller('generateHTMLCtrl', function ($scope, $http) {
$http.get('myJSONFile.json').success(function(data){
$scope.components = data;
//...
});
});
The code translates of course nothing.
My question is, how can I adapt my JavaScript code so that from a
JSON object following HTML element is generated?:
<button style="color: blue; background-color: #ff5db1; font-size: 20px" onclick="window.location.href='communicationPage.html'" id="communicationButton" class="button">
<i class="ion-chatboxes"></i> <br> Communication
</button>
Once my JSON object is located always in the JSON file, should always be created the HTML element on the page.
The second question is how I can position this generated HTML
element just in my HTML page?
I want that the HTML element is generated between the responsive grid element, such as:
<div class="row responsive-sm">
<div class="col">
<!-- The Button should be generated hier-->
</div>
</div>
The third and final question is how I can let generate the HTML
element on the appropriate page? Such as: If in JSON object the key-value pair of "category": "communicationPage" occurs should the corresponding HTML element be created on 'communicationPage.html'
I would look forward to an example. Many thanks.
For the two first point, use the data-binding and ng-repeat : directive
<div class="row reponsive-sm" ng-controller="generateHTMLCtrl">
<div ng-repeat="component in components">
<button style="color : {{component.color}}; background-color : {{component.background-color}} ... ">
</button>
</div>
</div>
For the last point, I'm not sure if it's possible with AngularJS ...

How to build dynamic controls in angular js using json?

I am working on a angular js project. Right now the controls are static. But client wants to create the html controls based on database.
I have a table with controls specification
For eg:
type : text/dropdown/radio/checkbox
events : onchange/onblur/onfocus
attributes:"color:red"
How can I generate the dynamic model which can parse database value to html controls?
Any help would be really appreciated...
This is pretty easy using the ng-repeat directive. Note how I assign the value of the model back to the scope variable in the ng-repeat. This allows me to retrieve it later.
angular.module('formModule', []).
controller('DynamicFormController', ['$scope',
function($scope) {
//Set equal to json from database
$scope.formControls = [{
name: "Name",
type: "text"
}, {
name: "Age",
type: "number",
color: "red"
},
{
name: "UseNestedControls",
type: "checkbox",
nestCondition: true,
nestedControls: [{
name: "NestedText",
type: "text"
}]
}
];
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="formModule">
<div ng-controller="DynamicFormController">
<form>
<div ng-repeat="input in formControls">
<label>{{input.name}}</label>
<input type="{{input.type}}" ng-model="input.value" ng-style="{'color':input.color}" />
<div ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px" ng-show="input.value == input.nestCondition">
<label>{{nestedInput.name}}</label>
<input type="{{nestedInput.type}}" ng-model="nestedInput.value" ng-style="{'color':nestedInput.color}"/>
</div>
</div>
</form>
<div ng-repeat="input in formControls">
<span>{{input.name}} = {{input.value}}</span>
<div ng-repeat="nestedInput in input.nestedControls" style="margin-left:20px">
<span>{{nestedInput.name}} = {{nestedInput.value}}</span>
</div>
</div>
</div>
</body>

Angular ng-repeat with nested json objects?

I have a JSON object, represented as such:
{
"orders" : [
{
"ordernum" : "PRAAA000000177800601",
"buyer" : "Donna Heywood"
"parcels" : [
{
"upid" : "UPID567890123456",
"tpid" : "TPID789456789485"
},
{
"upid" : "UPID586905486090",
"tpid" : "TPID343454645455"
}
]
},
{
"ordernum" : "ORAAA000000367567345",
"buyer" : "Melanie Daniels"
"parcels" : [
{
"upid" : "UPID456547347776",
"tpid" : "TPID645896579688"
},
{
"upid" : "UPID768577673366",
"tpid" : "TPID784574333345"
}
]
}
]
}
I need to do a repeater on the second level of this, a list of the "upid" numbers.
I know already how to get the top level
<li ng-repeat="o in orders">{{o.ordernum}}</li>
But I am unclear on the sequence to loop a level down. For example, this is wrong:
<li ng-repeat="p in orders.parcels">{{p.upid}}</li>
I also know how to nest repeaters to get this, but in this case i don't need to display the top level at all.
CLARIFICATION
The goal here is to have one list with the 4 "upid" numbers (there are 2 for each parcel, and there are 2 parcels in the order).
Actually its same answer of #sylwester. The better way to put it in filter. And you can reuse it by passing propertyName parameter.
In your case we passed parcels
JS
myApp.filter('createarray', function () {
return function (value, propertyName) {
var arrayList = [];
angular.forEach(value, function (val) {
angular.forEach(val[propertyName], function (v) {
arrayList.push(v)
});
});
return arrayList;
}
});
HTML
<ul>
<li ng-repeat="o in ordersList.orders | createarray: 'parcels'">{{o.upid}}</li>
</ul>
Here is working Fiddle
You can just create new array 'parcels' like in demo below:
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
$scope.data = {
"orders": [{
"ordernum": "PRAAA000000177800601",
"buyer": "Donna Heywood",
"parcels": [{
"upid": "UPID567890123456",
"tpid": "TPID789456789485"
}, {
"upid": "UPID586905486090",
"tpid": "TPID343454645455"
}]
}, {
"ordernum": "ORAAA000000367567345",
"buyer": "Melanie Daniels",
"parcels": [{
"upid": "UPID456547347776",
"tpid": "TPID645896579688"
}, {
"upid": "UPID768577673366",
"tpid": "TPID784574333345"
}]
}]
};
$scope.parcels = [];
angular.forEach($scope.data.orders, function(order) {
angular.forEach(order.parcels, function(parcel) {
$scope.parcels.push(parcel)
})
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<ul>
<li ng-repeat="o in parcels">{{o.upid}}</li>
</ul>
</div>
</div>
Seems like you just need a double-nested for loop -
<ul>
<div ng-repeat="o in orders">
<li ng-repeat="p in o.parcels">{{p.upid}}</li>
</div>
</ul>
The HTML might be a little ugly here, but I'm not sure what exactly you are going for. Alternatively you could just create a new array of the parcels via mapping.
Searching a lot for nice and simple solution for iterating dynamically. I came up with this
JAVASCRIPT (angular): a person is an example of nested object. the is_object function will be use in the HTML view.
$scope.person = {
"name": "john",
"properties": {
"age": 25,
"sex": "m"
},
"salary": 1000
}
// helper method to check if a field is a nested object
$scope.is_object = function (something) {
return typeof (something) == 'object' ? true : false;
};
HTML: define a template for simple table. the 1st TD is the key which is displayed. another TD (2 or 3, but never both) will be show the value if its not an object (number / string), OR loop again if its an object.
<table border="1">
<tr ng-repeat="(k,v) in person">
<td> {{ k }} </td>
<td ng-if="is_object(v) == false"> {{ v }} </td>
<td ng-if="is_object(v)">
<table border="1">
<tr ng-repeat="(k2,v2) in v">
<td> {{ k2 }} </td>
<td> {{ v2 }} </td>
</tr>
</table>
</td>
</tr>
</table>
The reason that <li ng-repeat="p in orders.parcels">{{p.upid}}</li> does not work the way you expect is because the parcels array is an object inside each individual order in your order array, i.e. it is not an object of the orders array itself.
If your orders array is defined on the $scope of a controller, then you create the array on the $scope variable:
$scope.allParcels = $scope.orders
.map(function (elem) {
return elem.parcels;
}) // get an array where each element is an array of parcels.
.reduce(function (previousValue, currentValue) {
return previousValue.concat(currentValue);
}); // concat each array of parcels into a single array of parcels
then on the template, you can use <li ng-repeat='p in allParcels'>{{p.upid}}</li>
If, however, you do not want to place the array on the $scope, I believe you can do something similar to this:
<li ng-repeat="p in orders
.map(function (elem) {
return elem.parcels;
})
.reduce(function (previousValue, currentValue) {
return previousValue.concat(currentValue);
})">{{p.upid}}</li>
although I'm not 100% sure that Angular will evaluate the .map/.reduce in the ng-repeat expression (also having an array generated this way in an ng-repeat is ill-advised since angular would have to constantly generate a new array via map/reduce on each $digest cycle).

Populate JSON values in multiple tables With Knockout JS

I have a bootstrap accordion that obtains it's header info from JSON, within each accordion pane I have a table, and the information for each table also get's populated with JSON.
The issue I have is that the all of the table data populates within the first accordion pane.
It does not move on to the secondary table and populate the information in there, my JSON data does include ID's so it is possible to navigate between the items just not sure how.
Here is Some of the code:
<div class="well">
</div>
<div data-bind="attr: {id: 'collapse'+$index()}" class="accordion-body collapse">
<div class="accordion-inner">
<div id="injectbody">
<table class="table table-striped">
<thead>
<tr>
<th>ContentID</th>
<th>Content</th>
<th>Qty To Assign</th>
</tr>
</thead>
<tbody data-bind="foreach: Locations">
<tr>
<td id="Lot" data-bind="text: ContentID"></td>
<td id="Area" data-bind="text: Content"></td>
<td id="QtyToAssign">
<input type="text" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
And the JQuery to make it all work:
var data = {
"d": [{
"__type": "Sample",
"ItemID": "1",
"ItemName": "First Item",
"QtyUnassigned": 10
}, {
"__type": "Sample",
"ItemID": "2",
"ItemName": "Second Item",
"QtyUnassigned": 15
}]
};
var data2 = {
"d": [{
"__type": "Sample2",
"ItemID": 1,
"ContentID": "1",
"Content": "This Is The First Item Content"
}, {
"__type": "Sample2",
"ItemID": 2,
"ContentID": "2",
"Content": "This Is The Second Item Content"
}]
};
var ProductViewmodel;
//debugger;
//Binds ViewModel
function bindProductModel(Products) {
var self = this;
self.items = ko.mapping.fromJS([]);
ProductViewmodel = ko.mapping.fromJS(Products.d, self.items);
console.log(ProductViewmodel());
}
//Binds First DataSet
function bindModel(vm, data) {
var self = this;
vm.Locations = ko.mapping.fromJS(data.d);
console.log(ProductViewmodel());
}
//Starting Function
$(document).ready(function () {
bindProductModel(data);
bindModel(ProductViewmodel()[0], data2);
ko.applyBindings(ProductViewmodel);
});
I have also created this Fiddle to demonstrate what I am trying to get to.
Your error is that since your ViewModel is actually an array, you are only binding Locations to the first element of your variable ProductViewmodel here.
bindModel(ProductViewmodel()[0], data2);
This means you have something like...
[0].Locations = [],
[1].Locations = undefined
Thus throwing an error when binding your markup (see the console in your fiddle).
In a related note, your variable naming is extremely misleading. ProductViewmodel is an array, yet you name it as ViewModel and you applyBindings to it.
I would recommend you to give Learn KnockoutJS a review. Also, stick to conventions, when variable naming pick camelCase, or underscore_case, or PascalCase or something, but just don't mix them. Finally, if you have functions that do something only applicable for specific objects, try to use a better name other than bindModel like bindLocationsToModel.