Issues parsing a nested JSON with AngularJS - html

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>

Related

How to print data in html using ng-repeat angularjs

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

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>

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>

show a div on a button click using angularjs and HTML

I want to show a div on a button click using angularjs and HTML
I am learning angularJs.
I want to design a webpage in which on click of 'Add' button a div(EmployeeInfoDiv) is shown.
When I fill the textboxes in it and save it the data should reflect in table within the div(EmpDetTable).
Here is the HTML page code:
<body ng-app="MyApp">
<div ng-controller="EmpDetCtrl">
<div ng-model="EmpDetTable" class="container body" ng-hide="addEmp">
<label class="TabHeadings">Employee Details</label>
<div class="EmployeeInfo">
<table ng-model="Employee" border="1">
<thead><tr><th>Name</th><th>Designation</th><th>Salary</th></tr></thead>
<tbody>
<tr ng-repeat="emp in employees">
<td>{{emp.name}}</td>
<td>{{emp.desg}}</td>
</tr>
</tbody>
</table>
<button ng-model="AddEmp" ng-click="ShowAddEmployee()">Add</button>
</div>
</div>
<div ng-model="EmployeeInfoDiv" class="popover right EmployeeInfo" style="width:1500px;" ng-show="addEmp" >
<label class="TabHeadings" style="width:830px;">Employee Details</label>
<div class="EmployeeInfo">
<table>
<tr><td><label class="table_label">Name:</label></td><td><input type="text" ng-model="name" class="textbox"/></td>
<td><label class="table_label">Designation:</label></td><td><input type="text" ng-model="desg" class="textbox"/></td>
</tr>
</table>
<div ng-model="botton_container">
<button ng-model="save" class="save_buttons" ng-click="SaveData();">Save</button>
<button ng-model="cancel" class="cancel_buttons" ng-click="ShowViewEmployee();">Cancel</button>
</div>
</div>
</div>
</div>
</body>
Controller Code:
function EmpDetCtrl($scope) {
$scope.employees = [
{ name: 'A',desg: 'C'}
];
$scope.addNew = function () {
$scope.employees.push({
name: $scope.name,desg: $scope.desg
});
}
$scope.ShowAddEmployee= function () {
return $scope.EmployeeInfoDiv=true;
}
$scope.ShowViewEmployee=function () {
return $scope.EmployeeInfoDiv = false;
}
}
I don't know whether this code is correct or not.
I just tried it.
Can anyone please help me out.
Thanks in advance.
Your ng-click is updating the EmployeeInfoDiv variable. So, reference that in ng-show and ng-hide:
<div ng-hide="EmployeeInfoDiv" class="container body">
...
<div ng-show="EmployeeInfoDiv" class="popover right EmployeeInfo" style="width:1500px;">
You do not need ng-model in the div to make that work.
ng-model="EmployeeInfoDiv"
Update
A few more issues. Most important is that (at least in the code posted) MyApp isn't defined anywhere, and your controller is defined on the global scope. So you need to change your html to:
<div ng-app>
<div ng-controller="EmpDetCtrl">
...
However, note that this is not the recommended method. See the angular documentation for controllers.
Here is a working demo: http://jsfiddle.net/wittwerj/xrB77/

Angular JS shows HTML within the tag

I am trying to insert HTML inside template using ng-bind-html-unsafe attribute. But for some reason its not working.
My code:
<tr class="white two-button" ng-repeat="(key,value) in recommendations | ojoScoreFilter:ojoScore | relevancyScoreFilter:relevancyScore | orderBy:predicate:reverse">
<td>
<div ng-bind-html-unsafe="value.button"></div>
</td>
</tr>
I am not able to see the HTML.
If I change ng-bind-html-unsafe="value.button" to ng-bind-html-unsafe="{{value.button}}" then it shows HTML but within the attribute, something like this:
<div ng-bind-html-unsafe="<a class="action_hrefs full-width bgcolor10 purple-hover flat-button flat-white-button btn" data-value="947" href="#"><i class="fa fa-lock"></i> Unlock</a>"></div>
Ok I found solution for this:
JS:
$scope.renderHtml = function(html_code)
{
return $sce.trustAsHtml(html_code);
};
HTML:
<p ng-bind-html="renderHtml(value.button)"></p>
make a filter like this
.filter('trusted',
function($sce) {
return function(ss) {
return $sce.trustAsHtml(ss)
};
}
)
and apply this as a filter to the ng-bind-html like
<div ng-bind-html="code | trusted">