Getting key value pairs from json reponse into angular js - angularjs

How do I map the json response to the table in html page.
Angularjs Controller:
app.controller('tableController', function ($scope,$http)
{
$scope.customerTable = [];
$scope.getTable = function ()
{
$http.get('<%=request.getContextPath()%>/GetTable.do').success(function (data)
{
$scope.customerTable = data;
// console.log($scope.customerTable);
});
};
});
html code:
<div ng-controller="tableController">
<!--<p>Click <a ng-click="getTable()">here</a> to load data.</p>-->
<table>
<tr>
<th>Card Number</th>
<th>First Name</th>
<th>Opening Balance</th>
<th>Withdrawal</th>
<th>Deposit</th>
<th>Closing Balance</th>
<th>Tx Date</th>
<th>Usage_Type</th>
</tr>
<tr ng-repeat="data in customerTable ">
<td>{{data[0]}}</td>
</tr>
</table>
<br>
<button class="form-control btn btn-success" type="submit" ng-click="getTable()">Load Table Data</button>
</div>
The response is in one array with key, value pairs. Do I have to modify the ng-repeat?
Here is the json response:
[{"TXDATE":"1-Aug-14","FIRST_NAME":"MOSES","USAGE_TYPE":"HOTELS/MOTELS/RESORTS","WITHDRAWAL":"15200","DEPOSIT":"0","CARD_NUMBER":"AL98****66325","CLOSING_BAL":"-362764.96","OPENING_BALANCE":"0"}]

You can use the fields in every object:
<tr ng-repeat="data in customerTable ">
<th>{{data.FIRST_NAME}}</th>
<th>{{data.CARD_NUMBER}}</th>
...
</tr>
Perhaps you could use a directive for this kind of table related iterations.

Use the attributes. it should be:
<tr ng-repeat="data in customerTable ">
<td>{{data.TXDATE}}</td> <!-- result: 1-Aug-14 -->
</tr>
and so on.

Yes, you have to modify it.
<tr ng-repeat="data in customerTable ">
<td>{{data['CARD_NUMBER']}}</td>
<td>{{data['TXDATE']}}</td>
<td>{{data['OPENING_BALANCE']}}</td>
...
</tr>

Related

Angularjs ng-repeat doesn't work as expected

I have an Angularjs controller(Angularjs 1.5.6) which calls a function from a python script, which returns an array of elements. I am trying to do an ng-repeat so that they appear in the table but for some reason, it doesn't show the elements of the array.
The 'Go' button in the html template triggers the function getSID which makes an HTTP call to a python script that returns an array. At the same time, the function also sets the scope, showval to true such that the table in the html appears only after the button is clicked.
<script>
angular.module('navigator', [])
.controller('HomeCtrl', function($scope, $http) {
$scope.getSid = function (sid) {
console.log(sid);
$http({
method: 'POST',
url: '/getMachine',
data: {sid:$scope.sid}
}).then(function(response) {
$scope.machines = [];
var object1 = response.data;
$scope.machines.push(object1);
//console.log(object1);
console.log($scope.machines);
$scope.showval = true;
}, function(error) {
console.log("hello");
console.log(error);
});
};
})
HTML code:
<div class="input-group mb-3 input-group-lg">
<div class="input-group-prepend">
<span class="input-group-text">Enter the SID</span>
</div>
<input type="text" class="form-control" ng-model="sid">
<button type="button" class="btn btn-outline-secondary" ng-click="getSid(sid)" ng-model="show" >
GO!
</button>
</div>
<div ng-show="showval">
<table class="table table-dark" >
<thead>
<tr>
<th scope="col">SID</th>
<th scope="col">Cluster</th>
<th scope="col">Node</th>
<th scope="col">Physical ip</th>
<th scope="col">Logical ip</th>
<th scope="col">Logical Host</th>
<th scope="col">Physical Host</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in machines">
<td>{{item}}</td>
</tr>
</tbody>
</table>
</div>
I googled ng-repeat and so several examples in plunker and I am following the same code but my code doesn't seem to work. Would be grateful for any assistance. Thanks for your time.
Your need to enclose track by $index within quotes as well,
<tr ng-repeat="item in machines track by $index">
Guilty of not posting the complete details. I was working with python flask and realized that the conflict is due to Jinja2.
I had to use the {%raw} {%end raw} so that Jinja2 processes it as an html.
More details in this Link
Now my code looks like this and ng-repeat is working.
{% raw %}
<tbody>
<tr ng-repeat="item in machines" >
<td>{{item}}</td>
</tr>
</tbody>
{% endraw %}

dirPagination numbers not change when ng-model search put something

At first, I'm using dirPagination. The problem is that when I search something, it's filtered correctly, but pagination number not change and also show all last number in pagination without any change and I see some page is empty because it does filter but page number is show.
<div data-ng-controller='productsController'>
<form `class='form-inline'>
<div class='form-group'>
<label>search</label>
<input type='text' data-ng-model='search' class='form-control' placeholder='search' />
</div>
</form>
<table class='table table-striped'>
<thead>
<tr>
<th>#</th>
<th>product</th>
<th>imet</th>
</tr>
</thead>
<tbody>
<tr dir-paginate='product in products|itemsPerPage:12|filter:search|orderBy:sortKey:reverse'>
<td>{{product.id}}</td>
<td>{{product.productName}}</td>
<td>{{product.time}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls max-size='10' direction-links='true' boundary-links='true' >
</dir-pagination-controls>
<script>
(function(){
var app = angular.module('products', ['angularUtils.directives.dirPagination']);
app.controller('productsController', function($scope, $http){
$scope.products = [];
$http.get('/products/json').success(function(data){
$scope.products= data;
});
});
})();
</script>
</div>
itemsPerPage must be the last filter, as below:
<tr dir-paginate='product in products | filter: search | orderBy: sortKey: reverse | itemsPerPage: 12'>
For more explanation, check it on FAQ on michaelbromley/angularUtils/.

Angular - How to update table with new values

I have a table with ng-repeat:
<table>
<tr>
<thead>
<th>key</th>
<th>value</th>
</thead>
</tr>
<tbody ng-repeat = "i in data">
<td>{{i.key}}</td>
<td>{{i.value}}</td>
</tbody>
</table>
The table is populated with data-ng-init, when the user clicks on a button:
<button ng-click="getNewVals()">new values</button>
I get json with new key-value, my question is how to repopulate the table with the new values baes on the key? is there a angular way to do so?
ng-repeat is bound to the model you are iterating over. If you update the model, ng-repeat will re-draw. In your example, whenever $scope.data changes, the ng-repeat will update itself.
Use this way. It's good if you provide your JSON.
<table>
<tr>
<thead>
<th>key</th>
<th>value</th>
</thead>
</tr>
<tbody>
<tr ng-repeat = "(key, val) in data">
<td>{{key}}</td>
<td>{{val}}</td>
</tr>
</tbody>
</table>
Look at the following example:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in persons">{{x.name}}, {{x.age}}</li>
</ul>
<button ng-click="changeIt()">Change json</button>
<script>
//1 module declaration
var app = angular.module('myApp', []);
//2 controller declaration
app.controller('myCtrl',function($scope){
$scope.persons = [
{name:"Peter", "age": 23},
{name:"Lina","age":26},
{name:"Robert", "age":33}
];
$scope.changeIt = function(){
$scope.persons = [
{name:"Larry",age: 59},
{name:"Joseph", age: 63},
{name:"Clara", age:71}
];
}
});
</script>
</body>
</html>
Hope it solves your problem.
you writing ng-reapet instead of ng-repeat
try this.
<table>
<tr>
<thead>
<th>key</th>
<th>value</th>
</thead>
</tr>
<tbody ng-repeat = "i in data">
<td>{{i.key}}</td>
<td>{{i.value}}</td>
</tbody>
</table>
<button ng-click="data.push({'key':1,'value':2})">new values</button>

Loading text before data is loaded AngularJS

Does anyone have a clue how to create a loading text before angular loads data in to a list?
I have this code for getting info from different subwebs (in sharepoint). But before (or while) the list is loaded I want to display a text "Loading...":
context.executeQueryAsync(Function.createDelegate(this, function () {
var webs = this._webs.getEnumerator();
while (webs.moveNext()) {
var subWeb = webs.get_current();
$scope.sites.push({
title: webs.get_title(),
});
$scope.$apply();
}
}
}),
HTML:
<div ng-controller="MainCtrl">
<table>
<thead>
<tr>
<th>
Site
</th>
<th>
Created
</th>
</tr>
</thead>
<tbody ng-repeat="site in sites">
<tr>
<td>
{{site.title}}
</td>
<td>
{{site.created | date:dateFormat}}
</td>
</tr>
</tbody>
</table>
<tbody ng-if="sites.length == 0">
<tr>
<td>
<img src="loading.gif">
</td>
</tr>
</tbody>
<tbody ng-repeat="site in sites" ng-if="sites.length > 0">
<tr>
<td>
{{site.title}}
</td>
<td>
{{site.created | date:dateFormat}}
</td>
</tr>
</tbody>
This produce 2 watchers but it will help.
some links of loading indicator : angular-spinner or angular-sham-spinner
also BLOG detailing on how the spinner works with angularjs
and in case you want to implement it yourself, below code will get you started...
app.directive("spinner", function(){
return: {
restrict: 'E',
scope: {enable:"="},
template: <div class="spinner" ng-show="enable"><img src="content/spinner.gif"></div>
}
});
warning : i havent tested the code but directive wont be more complex than this...

ng-show does not work with custom directive

I've just started using AngularJS and wanted to create a custom template directive for creating "in-place" editable tables. The idea would be to have something like:
<tr ng-repeat="customer in model.customers">
<ng-template ng-hide="customer === model.selectedCustomer"> <!-- display template-->
<td>{{customer.name}}</td>
</ng-template>
<ng-template ng-show="customer === model.selectedCustomer"> <!-- edit template -->
<td><input type="text" ng-model="customer.name"/></td>
</ng-template>
</tr>
It could then also be extended to specify a templateUrl e.g. <ng-template template-url="foo.html"></ng-template>
When I apply the ng-show directive to my custom directive it does not work. Here's the code for my directive:
var demo = angular.module("demo", [])
.directive("ng-template", function() {
return {
restrict: "E",
replace: true,
transclude: true
}
});
and HTML (http://jsfiddle.net/benfosterdev/ASXyy/):
<div ng-app="demo">
<table>
<tr ng-repeat="name in ['jane', 'john', 'frank']">
<ng-template ng-show="name !== 'frank'">
<td>{{name}}</td>
</ng-template>
</tr>
</table>
</div>
Furthermore, when I look at the generated HTML my custom directive doesn't even appear in the table:
<div ng-app="demo" class="ng-scope">
<ng-template ng-show="name !== 'frank'" class="">
</ng-template>
<table>
<tbody>
...
</tbody>
</table>
</div>
Essentially I'm trying to avoid writing code like this (setting the ng-show directive on every <td> element):
<table>
<tr ng-repeat="customer in customers">
<ng-template>
<td ng-hide="isSelected">{{customer.name}}</td>
<td ng-hide="isSelected">{{customer.age}}</td>
<td ng-hide="isSelected"><button ng-click="edit(customer)"</td>
<td ng-show="isSelected"><input type="text" ng-model="customer.name"/></td>
<td ng-show="isSelected"><input type="text" ng-model="customer.age"/></td>
<td ng-show="isSelected"><button ng-click="save(customer)"</td>
</ng-template>
</tr>
</table>
A couple of things occur to me when I look at your code.
ng-include offers very similar functionality to your proposal for extending ng-template. If you're going to load a view based on the state of the underlying model then I think this would be the way to go.
If you're not going to be loading the template from a separate view file, why not just use ng-show (or ng-if / ng-switch, which I prefer in most cases) on your td element?
Here is some example code using ng-include:
<table>
<thead>
<th>One</th>
<th>Two</th>
<th>Three</th>
<th></th>
</thead>
<tbody>
<tr ng-repeat="item in items" ng-include="getTemplate(item)"></tr>
</tbody>
</table>
Here is the full JSFiddle: http://jsfiddle.net/qQR6j/2.
Use ng-repeat-start and ng-repeat-end to specify the two alternative <tr> tags.
<div ng-app="demo">
<table ng-controller="Ctrl">
<tr ng-repeat-start="name in ['jane', 'john', 'frank']" ng-hide="isSelected(name)">
<td>{{name}} <button ng-click="select(name)">edit</button></td>
</tr>
<tr ng-repeat-end ng-show="isSelected(name)">
<td>{{name}}!</td>
</tr>
</table>
</div>
With this javascript
var demo = angular.module("demo", []);
demo.controller("Ctrl",
function Ctrl($scope) {
var selected;
$scope.isSelected = function(name) {
return selected === name;
};
$scope.select = function(name) {
selected = name;
};
});
Live example: http://jsfiddle.net/6FtjG/1/
Your browser renders the 'ng-template' outside of the table because its not a valid child of tr. Even if you have set replace to true, the directive needs to be rendered before it can be replaced.
You can see it is because of the table, because this does work:
<div>
<div ng-repeat="name in ['jane', 'john', 'frank']">
<ng-template ng-show="name !== 'frank'">
<div >{{name}}</div>
</ng-template>
</div>
</div>
see: Fiddle
This is something your browser does so you cannot avoid it.

Resources