How to print data in html using ng-repeat angularjs - html

I have json data in controller as response. I have to print that data in html.
for that I have done as below:
In my controller
.controller('DataImportControl', ['$scope','$http', '$location', '$rootScope' , function($scope, $http, $location, $rootScope) {
console.log(" In dataimportCtrl");
$scope.readCustomer = function(){
console.log("in read customer");
$http.post('/custimport').success(function(response) {
console.log("in controller");
console.log("controller:"+response);
$scope.data=response;
}).error(function(response) {
console.error("error in posting");
});
};
}])
My html code:
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="" ng-controller="DataImportControl">
<form ng-submit="readCustomer()">
<button type="submit" >Submit</button>
</form>
<table class="table">
<thead>
<tr>
<th>Code exists in customer master</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cust in data ">
<td>{{cust.customer_code}}</td>
</tr>
</tbody>
</table>
</div>
<div >
</div>
</body>
</html>
My json data as response in controller :
{"jarray":[{"customer_name":["Ankita"],"customer_code":["c501"]}]}
My question is how to print json data in html using ng-repeat in my case?
Thanks in advance...

I'm assuming you want to print out the actual object, in that case just do
{{cust | json}}
Wrap it in pre tags to have it prettified.

The data being returned from your service is strangely formatted. I would assume you have multiple records being returned, but you are only showing one in this example.
The record you are showing here is an object, with an array as one of the properties. It is not clear if your object has multiple arrays, or if this array has multiple customer objects embedded in it. However, I worked up a quick plunker showing how to iterate through in both situations.
first, if you intend to iterate through data directly, and data will hold multiple arrays, you would use the (key, value) syntax, since data itself is an object and not an array.
<div ng-repeat="(key, value) in data">
key: {{key}}
<br/>value: {{value}}
<div ng-repeat="customer in value">
Customer name: {{customer.customer_name}}
<br/>Customer code: {{customer.customer_code}}
</div>
</div>
However, if your data is only returning a single object property, jarray, and you will always be iterating through this same property, the outer ng-repeat is unnecessary:
<div ng-repeat="customer in data.jarray">
Customer name: {{customer.customer_name}}
<br/>Customer code: {{customer.customer_code}}
</div>
you may want to clean up your service, either in angular or on your server, and remove jarray all together, if it doesn't hold a specific significance to the data.
http://plnkr.co/edit/Nq5Bo18Pdj4yLQ13hnrJ?p=preview

Related

How do I get rows from a list(table) in a protractor e2e test?

The list in question is a table generated by a reactive angular form which does not have a specific ID. Following code is used to generate the list in angular part:
<p-table id='paragraphList' *ngIf="paragraphsObs | async; else loading"
[value]="paragraphsObs | async"
selectionMode="single" (onRowSelect)="select($event)"
scrollable="true">
<ng-template pTemplate="header">
<tr> ...header... </tr>
</ng-template>
<ng-template pTemplate="body" let-paragraph let-rowData>
<tr [pSelectableRow]="rowData">
<td width="15%">{{paragraph.cell1}}</td>
<td width="10%">{{paragraph.cell2}}</td>
<td width="31%">{{paragraph.cell3}}</td>
<td width="11%">{{paragraph.cell4 | dateTransform: helperService.MM_DD_YYYY_HH_MM_A_Z_DATE_PATTERN}}
</td>
<td width="11%">{{paragraph.cell5}}</td>
<td width="11%">{{paragraph.cell6 | dateTransform: helperService.MM_DD_YYYY_HH_MM_A_Z_DATE_PATTERN}}
</td>
<td width="11%">{{paragraph.cell7}}</td>
</tr>
</ng-template>
</p-table>
The corresponding table generated at the front-end has the following html source:
<p-table _ngcontent-c6="" id="paragraphList" scrollable="true" selectionmode="single" ng-reflect-selection-mode="single" ng-reflect-scrollable="true" class="ng-star-inserted" ng-reflect-value="[object Object],[object Object">
<div class="ui-table ui-widget ui-table-hoverable-rows" ng-reflect-ng-class="[object Object]">
<div class="ui-table-scrollable-wrapper ng-star-inserted">
<div class="ui-table-scrollable-view" ng-reflect-frozen="false">
<div class="ui-table-scrollable-header ui-widget-header">...header...</div>
<div class="ui-table-scrollable-body">
<table class="ui-table-scrollable-body-table" ng-reflect-klass="ui-table-scrollable-body-table" ng-reflect-ng-class="[object Object]">
<tbody class="ui-table-tbody" ng-reflect-template="[object Object]">
<tr _ngcontent-c6="" ng-reflect-data="[object Object]" class="ng-star-inserted">...</tr>
<tr _ngcontent-c6="" ng-reflect-data="[object Object]" class="ng-star-inserted">...</tr>
...
</tbody>
</table>
<div class="ui-table-virtual-scroller"></div>
</div>
</div>
</div>
</div>
</p-table>
I want to reach to those inner elements and get them as a list. I have tried using class names with element and all locators, to get the elements but to no avail. Then I tried using tag names to reach to those elements but that too doesn't seem to work.
This following small snippet returns 0 for the count of elements that I try to obtain from the list.
element(by.id('paragraphList')).element(by.css('.ui-table-scrollable-body-table'))
.all(by.tagName('tr')).count().then(function (result) {
console.log(result);
});
Any help would be appreciated. Thanks
Considering above is your full rendered HTML..
The code below will give an Array of arrays, where each array would be containing texts from all the cells of a row.
Explanation:
The code has three functions,
populateData() - is the driving function where we pass the resolved list of rows.
Then _populateRows() and _populateCells() run recursively to gather the text from the cells. This is also possible to do with a loop (as protractor queues the promises by itself) but I like keeping things clear on my end. _populateRows() recur on rows and _populateCells() recur on cells of each row. (more in comments)
Note This first thing which you should do before implementing this is: check the count() (or .length of resolvedRows) of element.all(by.css('#paragraphList table tbody tr')). As basically this was your original question I believe. Now If you have a count, then you can go with this solution or whatever suites your need.
let allRows = element.all(by.css(`#paragraphList table tbody tr`)); //will have all the rows.
allRows.then((rowsResolved) => {
// now have all the rows
PO.populateData(rowsResolved).then((allData) => {console.log(allData)}) // should be an Array od arrays, each array would be containing texts from all the cells.
// Considering you have a Page Object and added the functions below in the Page Object.
// Page Object is nothing but another class where we keep our utility methods
})
// driving function
populateData(rowsResolved) {
let data = [];
return this._populateRows(0, rowsResolved, data);
}
// calls itself recursively to loop over the rows
private _populateRows(index, rowsResolved, data) {
if (index >= rowsResolved.length) {
let defer = protractor.promise.defer();
defer.fulfill(data);
return defer.promise; // so that it is chainable even if I don't have any rows
}
let cells = element.all(by.css(`#paragraphList table tbody tr:nth-child(${index + 1}) td`));
cells.then((cellsResolved) => {
let cellData = [];
if (cellsResolved.length) {
data.push(cellData);
}
this._populateCells(0, cellsResolved, cellData);
return this._populateRows(index + 1, rowsResolved, data);
})
}
// calls itself recursively to loop over all the cells ofeach row.
private _populateCells(index, cellsResolved, cellData) {
if (index >= cellsResolved.length) {
let defer = protractor.promise.defer();
defer.fulfill(cellData);
return defer.promise; // so that it is chainable even if I don't have any cells(that would be an incorrect structure though, if a row exists then cells have to exist )
}
cellsResolved[index].getText().then((cellValue) => {
cellData.push(cellValue)
});
return this._populateCells(index + 1, cellsResolved, cellData);
}

Angularjs convert string to object inside ng-repeat

i've got a string saved in my db
{"first_name":"Alex","last_name":"Hoffman"}
I'm loading it as part of object into scope and then go through it with ng-repeat. The other values in scope are just strings
{"id":"38","fullname":"{\"first_name\":\"Alex\",\"last_name\":\"Hoffman\"}","email":"alex#mail","photo":"img.png"}
But I want to use ng-repeat inside ng-repeat to get first and last name separate
<div ng-repeat="customer in customers">
<div class="user-info" ng-repeat="name in customer.fullname">
{{ name.first_name }} {{ name.last_name }}
</div>
</div>
And I get nothing. I think, the problem ist, that full name value is a string. Is it possible to convert it to object?
First off... I have no idea why that portion would be stored as a string... but I'm here to save you.
When you first get the data (I'm assuming via $http.get request)... before you store it to $scope.customers... let's do this:
$http.get("Whereever/You/Get/Data.php").success(function(response){
//This is where you will run your for loop
for (var i = 0, len = response.length; i < len; i++){
response[i].fullname = JSON.parse(response[i].fullname)
//This will convert the strings into objects before Ng-Repeat Runs
//Now we will set customers = to response
$scope.customers = response
}
})
Now NG-Repeat was designed to loop through arrays and not objects so your nested NG-Repeat is not necessary... your html should look like this:
<div ng-repeat="customer in customers">
<div class="user-info">
{{ customer.fullname.first_name }} {{ customer.fullname.last_name }}
</div>
This should fix your issue :)
You'd have to convert the string value to an object (why it's a string, no idea)
.fullname = JSON.parse(data.fullname); //replace data.fullname with actual object
Then use the object ngRepeat syntax ((k, v) in obj):
<div class="user-info" ng-repeat="(nameType, name) in customer.fullname">
{{nameType}} : {{name}}
</div>
My advise is to use a filter like:
<div class="user-info"... ng-bind="customer | customerName">...
The filter would look like:
angular.module('myModule').filter('customerName', [function () {
'use strict';
return function (customer) {
// JSON.parse, compute name, foreach strings and return the final string
};
}
]);
I had same problem, but i solve this stuff through custom filter...
JSON :
.........
"FARE_CLASS": "[{\"TYPE\":\"Economy\",\"CL\":\"S \"},{\"TYPE\":\"Economy\",\"CL\":\"X \"}]",
.........
UI:
<div class="col-sm-4" ng-repeat="cls in f.FARE_CLASS | s2o">
<label>
<input type="radio" ng-click="selectedClass(cls.CL)" name="group-class" value={{cls.CL}}/><div>{{cls.CL}}</div>
</label>
</div>
CUSTOM FILTER::
app.filter("s2o",function () {
return function (cls) {
var j = JSON.parse(cls);
//console.log(j);
return j;
}
});

ng-repeat with json data

I have the following json data saved in json column in postgres database
{
"runway": [
{"number":"13R/13L", "length":"14511", "lengthuom":"ft"},
{"number":"10R/15L", "length":"98641", "lengthuom":"ft"},
{"number":"16R/22L", "length":"65410", "lengthuom":"ft"}
]
}
I'm tryig to get it by ng-repeat but I don't know how.
I try with the following code
<tr ng-repeat="ass in assetb track by $index">
<td>{{ass.runway.number}}</td>
</tr>
Can anyone help me please to display this data in table?
Check out this may help you :--
function MyController($scope){
var data = {"runway":[ {"number":"13R/13L", "length":"14511", "lengthuom":"ft"},
{"number":"10R/15L", "length":"98641", "lengthuom":"ft"},
{"number":"16R/22L", "length":"65410", "lengthuom":"ft"} ]}
$scope.list = data.runway;
}
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
</head>
<body>
<div ng-controller="MyController">
<p ng-repeat="l in list track by $index">{{l.number}}</p>
</div>
</body>
</html>
Remove the line track by $index and use like
<tr ng-repeat="ass in assetb.runway">
<td>{{ass.number}}</td>
</tr>
Fiddle
Get your data from database and store it in $scope variable. Something like:
$scope.assetb = {
"runway": [
{"number":"13R/13L", "length":"14511", "lengthuom":"ft"},
{"number":"10R/15L", "length":"98641", "lengthuom":"ft"},
{"number":"16R/22L", "length":"65410", "lengthuom":"ft"}
]
};
And since ng-repeat requires an array, modify your HTML something like this:
<tr ng-repeat="ass in assetb.runway track by $index">
<td>{{ass.number}}</td>
</tr>

Issues parsing a nested JSON with AngularJS

I have the following contoller in my app :
angular.module('myApp.controllers', []).
controller('ClientesController', [ '$scope', '$rootScope', 'Clientes',
function($scope, $rootScope, Clientes) {
$rootScope.clientes;
Clientes.query(function(response) {
$rootScope.clientes = response;
})
}]);
Which returns a JSON object with the following format :
[{"idCliente":1,
"nomeFantasia":"Flores",
"razaoSocial":"Transportes Flores Ltda.",
"contatosClientes":
[
{"idContatoCliente":1,
"dddCelular":21,
"email":"ljames#cavaliers.com"},
{"idContatoCliente":2,
"dddCelular":21,
"email":"test#cavaliers.com"}
]
}]
And a template which tries to parse the JSON with ng-repeat :
<tr ng-repeat="cliente in clientes | filter:searchText">
<td>{{cliente.idCliente}}</td>
<td>{{cliente.razaoSocial}}</td>
<td>{{cliente.nomeFantasia}}</td>
<td>{{cliente.contatosClientes.email}}</td>
<td>
<div class="right floated ui green icon buttons">
<div class="ui button">Editar</i></div>
</div>
</td>
</tr>
The problem is that I can access the outer keys (idCliente,razaoSocial, etc) with the object.key sintaxe, but I can't access the inner keys (contatosClientes.email, for example) in the nested array.
I've tried many approaches and I am starting to think that is something wrong with my REST API, but before change all my backend code I would like to know if someone can help me with this issue.
Best regards,
Antonio Belloni
contatosClientes is an array, you'll have to do ng-repeat for that too, for example:
<tr ng-repeat="cliente in clientes | filter:searchText">
<td>{{cliente.idCliente}}</td>
<td>{{cliente.razaoSocial}}</td>
<td>{{cliente.nomeFantasia}}</td>
<td ng-repeat="contato in cliente.contatosClientes>{{contato.email}}</td>
<td>
<div class="right floated ui green icon buttons">
<div class="ui button">Editar</i></div>
</div>
</td>
</tr>

AngularJS: How to get the key of a JSON Object

I am unsure if this has got anything to do with AngularJS at all and if it is only JSON related.
Anyhow, let us say that we have the following JSON:
$scope.dataSets = {
"names": ["Horace", "Slughorn", "Severus", "Snape"],
"genders": ["Male", "Female"]
}
Now, I am using the ng-repeat directive to print the above as follows:
<div ng-repeat="data in dataSets>
//Continue readig to know what I am expcting here
</div>
What I expect within the <div></div> tags is to print "name" and "genders". That is, I wish to print the keys of the JSON. I have no idea what the keys are, as in they could be anything. How can I do this?
As docs state it:
(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
<div ng-repeat="(key, data) in dataSets">
{{key}}
</div>
for accessing Json key-value pair from inside controller in AngularJs.
for(var keyName in $scope.dataSets){
var key=keyName ;
var value= $scope.dataSets[keyName ];
alert(key)
alert(JSON.stringify(value));
}
if dataSets is an array and not an object you first need to ng-repeat the array items and then the key or value.
<div ng-repeat="item in dataSets">
<div ng-repeat="(key, value) in item">
{{key}}
{{value}}
</div>
</div>
just my 2 cents.
For every dataSet in dataSets, print the key and then iterate through the individual items:
<div ng-repeat="(key, dataSet) in dataSets">
<div>{{key}}</div>
<div ng-repeat="value in dataSet">
{{value}}
</div>
</div>
{{dataset}} can be displayed in one go also, the array would be displayed as a comma separated list of values.