Obtain data from Json using angular - javascript

Below is my code:
post.json
[
{
"client_id":"100",
"client_name":"MM Hope House",
"user_fname":"Betty",
"user_lname":"Johnson",
"user_id":"10",
"username":"bjohnson",
"total_web":"$500",
"campaigns":{
"campaign":[{
"id":"23",
"campaign_name":"MM Hope House",
"start_date":"4/15/2015",
"end_date":"6/13/2015",
"goal":"$20,000",
"total_pledges":"$1550",
"total_donations":"$1000"
}],
"pledgees":[{
"pledgee_fname":"Tavonia",
"pledgee_lname":"Evans",
"pledge_email":"tavonia#gmail.com",
"pledge_date":"4/22/2015",
"pledge_amount":"$50.00",
"paid":"$50.00",
"last_pledge":"$50.00"
}],
"donors":[{
"donor_fname":"Pat",
"donor_lname":"Smith",
"donor_email":"patsmith#onlinemediainteractive.com",
"total_cdonation":"$10.00",
"total_ldonation":"$450.00",
"last_donation":"$200.00",
"last_pledge":"$350.00"
}]
}
}
]
My HTML code:
<script>
function PostsCtrlAjax($scope, $http) {
$http({method: 'POST', url: 'assets/js/posts.json'})
.success(function(data) {
console.log(data);
$scope.posts = data;
})
.error(function(data, status) {
$scope.posts = data || "Request failed";
});
}
</script>
My HTML code where I want to populate data:
<thead>
<tr>
<th>Campaign ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Amount</th>
<th>Email ID.</th>
<th>Pledge Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts" >
<td>{{post.id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
I am trying to get client_id pleg_fname from array, but do not know how to.

Your pledgess object is an array of objects so you should do this instead and your entire JSON is contained within an array so you need the first element which will be your entire object and you call it with posts[0] and then you specify the object you are trying to iterate : pledgees.
<tr ng-repeat="post in posts[0].campaigns.pledgees" >
<td>{{posts[0].campaigns.campaign[0].id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
Edit
You're right, I totally missed that array. See this plunker where I tested it http://plnkr.co/edit/dvdnjv2mN2gljQGI9Lls?p=preview
Edit 2
If you want the campaign ID just add this (updated the original code with this change)
{{posts[0].campaigns.campaign[0].id}}

Because of your posts object contains an array of one element, you should use posts[0] to get the first (and the only one) element. Moreover, your pledgees array is inside a campaigns object, so posts[0] become posts[0].compaigns.pledgees.
You should try this :
<tr ng-repeat="post in posts[0].campaigns.pledgees" >
<td>{{post.id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
</tr>
EDIT:
And, if you want the id from the campagin object at the same index than your pledgee item, you have to add track by $index to posts[0].campaigns.pledgees. So it's become posts[0].campaigns.pledgees track by $index.
So, now with $index you get the right index to get the right campaign ID in the campaign object with {{posts[0].campaigns.campaign[$index].id}}
And the result is :
<tr ng-repeat="post in posts[0].campaigns.pledgees track by $index" >
<td>{{posts[0].campaigns.campaign[$index].id}}</td>
<td>{{post.pledgee_fname}}</td>
<td>{{post.pledgee_lname}}</td>
<td>{{post.pledge_amount}}</td>
<td>{{post.pledge_email}}</td>
<td>{{post.pledge_date}}</td>
</tr>
You can see the result here : http://jsfiddle.net/Fieldset/y1asxm61/1/

Related

Angularjs : ngRepeat list down all the data from server

I successfully fetch data by using $http get from php server. But I have no idea how to display the data in Table form by using ngRepear because all the data is in few different project. I am going to display all the object of data into different row of a table. The following shows data I got from php server.
Following glimpse of code can give you idea
$scope.retrievedData = [];
//retrieve data from your server
//take the data into above scope variable
<table>
<tr ng-repeat = "data in retrievedData">
<td>data.AssetDescription</td>
<td>data.AssetNumber</td>
<td>data.ComputerName</td>
</tr>
</table>
You need to add that data to controller variable:
Controller
function YourController($scope, $http) {
$scope.tableData = [];
$http.get('url').then(function(result) {
$scope.tableData = result.data;
});
}
Template
<table>
<thead>
<tr>
<th>Description</th>
<th>Computer name</th>
<th>Borrow date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in tableData ">
<td>{{row.data.AssetDescription}}</td>
<td>{{row.data.ComputerName}}</td>
<td>{{row.data.borrowDate}}</td>
</tr>
</tbody>
</table>

orderBy not working with pagination and filters

<table>
<thead>
<tr>
<th class="col-md-3" ng-click="sortDirection = !sortDirection">Created At</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="food in foods | filter:foodFilter | itemsPerPage:pageSize | orderBy:'created_at_date'">
<td class="col-md-"> {{food.created_at_date}} </td>
</tbody>
</table>
<dir-pagination-controls
max-size= 7
boundary-links="true">
</dir-pagination-controls>
This is only a snippet of my code but its too large to put up. Everything is working except only some of the created_at_date is in order. When I click on a different filter to add in or remove data depending on that filter, only some of it is entered into the correct place. My main question is: is there someway to sort all of the dates properly while still allowing the everything else function as well? All help is welcome, Thanks
(function () {
"use strict";
App.controller('foodsController', ['$scope'],
function($scope) {
$scope.sortDirection = true;
In your controller you can add the method to order the array before you loop over them.
Assuming your foods array has an array of objects, each with a key of created_at_date and a value:
App.controller('foodsController', function($scope) {
$scope.foods = [{
created_at_date: 6791234
}, {
created_at_date: 9837245
}, {
created_at_date: 1234755
}];
// create a method exposed to the scope for your template.
$scope.orderBy = function(key, array) {
// now you've received the array, you can sort it on the key in question.
var sorted = array.sort(function(a, b) {
return a[key] - b[key];
});
return sorted;
}
});
Now on your template, you have a method available to sort your values for you:
<table>
<thead>
<tr>
<th class="col-md-3" ng-click="sortDirection = !sortDirection">Created At</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="food in orderBy('created_at_date', foods) | filter:foodFilter | itemsPerPage:pageSize">
<td class="col-md-"> {{food.created_at_date}} </td>
</tr>
</tbody>
</table>
The orderBy method which we've created on your controller returns an array, but it's just sorted by the key that's sent in as the first argument of the function. The second argument is the original array you're trying to sort.
At least this way you can check if you remove all your other filters to see if it's ordered correctly, if then after you add them back in it changes it's because those filters are also changing the order.

Knockout.js: Updating objects loaded with mapping plugin

I want to render a table containing a list of objects my server is sending me. I'm currently doing this:
<table>
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: status"></td>
</tr>
</tbody>
</table>
And the Knockout.js binding part:
var mappedData = komapping.fromJSON('{{{ services }}}');
ko.applyBindings({services: mappedData});
services is a variable containing JSON data and the whole page is rendered with handlebars. So far so good. I'm able to render the data received in the table.
Now the problem: I'd like to receive a notification which tells me that the status of a service has changed, and update the corresponding object within mappedData. The problem is that mappedData seems pretty opaque and I'm unable to retrieve an object and update it given its id.
Help appreciated!
Your mappedData variable at this point will be a knockout array with a bunch of objects that contain knockout observables.
So all you have to do is change the status observable in the correct object from the array.
function updateServiceStatus(id, status) {
var service = mappedData().filter(function(e) { return e.id() == id; });
if (service.length) {
service[0].status(status);
}
}
To get the object, you can write a helper function that will retrieve for you a service object. You could do something like this (assuming mappedData is an observableArray and id observable) :
function get_service_by_id(service_id){
for(var i=0;i<mappedData().length;i++){
if (mappedData()[i].id() === service_id){
return mappedData()[i];
}
}
return false;
}

Changing or editings Keys in objects, in order to show in view. Using Angular

Example JSON:
[{"name":"John", "date_of_birth":"01/12/1987","marital_status": "Open Relationship"}]
Example view:
<table>
<tr>
<th> Name </th>
<th>Date of Birth</th>
<th>Martial Status</th>
</tr>
<tr ng-repeat= "profile in profiles">
<td>{{profile.name}}</td>
<td>{{profile.date_of_birth}}</td>
<td>{{profile.marital_status}}</td>
</tr>
</table>
What I want is to ng-repeat the keys or table heading too. I know how to put ng-repeat and get keys and values. But what I will like is to change the keys and make them look nice, for e.g : date_of_birth should be Date of Birth, but with ng-repeat on it.
I do agree with the comments in under your question that it is not the best approach. Also, remember that in reality you shouldn't count on a particular order when iterating over object's params (see https://github.com/angular/angular.js/issues/6210).
However ;) in the spirit of solving interesting question…
If you really want to do this, you can do it this way:
<table>
<tr ng-repeat="(key, value) in profiles[0]">
<th>{{ key | snailToHuman }}</th>
</tr>
<tr ng-repeat= "profile in profiles">
<td>{{profile.name}}</td>
<td>{{profile.date_of_birth}}</td>
<td>{{profile.martial_status}}</td>
</tr>
</table>
And create a filter snailToHuman, e.g.:
app.filter('snailToHuman', function () {
return function (snail) {
return snail.split('_').map(function (word) {
word.charAt(0).toUpperCase() + word.slice(1);
}).join(' ');
};
})

AngularJS - Using variable name in JSON selector

I have a table using angularjs where I want to loop through an array to print specific headers from a json object. The header prints out fine, but the problem comes when I try to use a variable from my nested ng-repeat as a json selector. If you replace the inner ng-repeat with the commented section below it, it will work.
Table:
<table>
<thead>
<th ng-repeat="column in tableHeader">{{column}} <a ng-click="sort_by(column);"><i class="glyphicon glyphicon-sort"></i></a></th>
</thead>
<tbody>
<tr ng-repeat="data in filtered>
<td ng-repeat="column2 in tableHeader">{{data.column2}}</td>
<!-- <td>{{data.Environment}}</td>
<td>{{data.HostIP}}</td>
<td>{{data.ServiceName}}</td>
<td>{{data.Status}}</td>
<td>{{data.StartTime}}</td>
<td>{{data.Capacity}}</td>
<td>{{data.Txn}}</td>
<td>{{data.Errors}}</td>
<td>{{data.Build}}</td>
<td>{{data.Project}}</td>
<td>{{data.Author}}</td>
<td>{{data.ModifyDate}}</td>
<td>{{data.Port}}</td>
<td>{{data.BasePath}}</td> -->
</tr>
</tbody>
</table>
Array located in controller:
$scope.tableHeader = ['Environment', 'HostIP', 'Status', 'ServiceName', 'StartTime', 'Capacity', 'Txn', 'Errors', 'Build', 'Project', 'Author', 'ModifyDate', 'Port', 'BasePath'];
I think you're looking for {{data[column2]}}. Since column2 is just the string value of the property you want, treat data like an associative array in this case to get the property you're trying to display.
column2 was created by the ng-repeat and is what you want. Note {{column2}}:
<td ng-repeat="column2 in tableHeader">{{column2}}</td>

Categories

Resources