How to consume JSON array in AngularJS? - javascript

What i trying to do here is, i want to consume the JSON that i produce using Spring Restful WebService, which is looked like this :
[
{
"userid": 1,
"firstName": "kevin",
"lastName": "buruk",
"email": "pucuk#ubi.com"
},
{
"userid": 2,
"firstName": "helm",
"lastName": "krpuk",
"email": "helmkrupuk#gmail.com"
},
{
"userid": 3,
"firstName": "batok",
"lastName": "kelapa",
"email": "batokkelapa#gmail.com"
}
]
That JSON is produce by this function in my Java Spring MVC Controller, which is looked like this :
SpringController.java
#RestController
#RequestMapping("/service/")
public class SpringServiceController {
UserService userService = new UserService();
#RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userService.getAllUsers();
return users;
}
}
And i am about to consume the JSON value into angular table, so i do store the JSON value in angular object in the scope, here is my Javascript code. i named this file app.js
app.js
function Hello($scope, $http) {
$http.get('http://localhost:8080/SpringServiceJsonSample/service/').
success(function(data) {
$scope.users = data;
});
}
and here is my html page. i named it index.html
index.html
<html ng-app>
<head>
<title>Angular Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Hello">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.userid}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</div>
</body>
</html>
What i missed here? i won't show anything. Before this i was trying to consume the JSON that i only have one record, it work properly. But this time i trying to consume the array, and i failed. What i missed here? is it the JSON or my javascript?

First of all, you have to use latest version of angular. Now, it's 1.4.5 with more performance optimizations and features.
About your question: error in html code. Here's the fixed version
function Hello($scope, $http) {
$scope.users = [
{
"userid": 1,
"firstName": "kevin",
"lastName": "buruk",
"email": "pucuk#ubi.com"
},
{
"userid": 2,
"firstName": "helm",
"lastName": "krpuk",
"email": "helmkrupuk#gmail.com"
},
{
"userid": 3,
"firstName": "batok",
"lastName": "kelapa",
"email": "batokkelapa#gmail.com"
}
]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app>
<table ng-controller="Hello">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.userid}}</td>
<td>{{user.firstName}}</td>
<td>{{user.lastName}}</td>
<td>{{user.email}}</td>
</tr>
</tbody>
</table>
</body>
As you can see, I fixed it with adding only one html tag!

Related

ReactJs Render Value (Array of Objects) of Object

{
"pendingShareholder": [
[{
"id": 5351,
"userName": "iverson",
"firstName": "Allen",
"lastName": "Iverson",
"password": "$2a$10$20ILdapdX6u8G1nH2jIr6upiKY04LCxD9yjHKUHRhUfpuG1w1ywd2",
"contact": "97801671",
"email": "john.doe#gmail.com",
"roles": [{
"id": 3,
"name": "ROLE_SHAREHOLDER"
}]
},
{
"id": 5951,
"userName": "rosgeller",
"firstName": "Ros",
"lastName": "Geller",
"password": "$2a$10$Udrju2Tj6mKGJRZA3d2GFer6kfSI988xI1/R50s.XmrHcIN1IJxoO",
"contact": "90908899",
"email": "peter.sou#gmail.com",
"roles": [{
"id": 3,
"name": "ROLE_SHAREHOLDER"
}]
}
]
]
}
Hi all
I have the above object. As you can see it is an object, with one key ("pendingShareholder"). The value of this key is an array inside an array (with objects inside).
I need to return this out in ReactJS. Using React Hooks here. I can't seem to do it no matter what :(
Can anyone help me. I am going nuts here
Thanks in advance!
const adminStateObject = useSelector((state) => state.admin11111);`
return (
<div className="adminmaincontent">
<h2>Pending Approval Users</h2>
<Table striped bordered hover size="sm" responsive>
<thead>
<tr>
<th>ID</th>
<th>UserName</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
{Object.keys(adminStateObject).map((key, i) => (
<tbody key={uuid()}>
{adminStateObject[key].map((key2, i2) => (
<tr key={uuid()}>
<td key={uuid()}>{key2.id}</td>
<td key={uuid()}>{key2.userName}</td>
<td key={uuid()}>{key2.firstName}</td>
<td key={uuid()}>{key2.lastName}</td>
<td key={uuid()}>{key2.contact}</td>
<td key={uuid()}>{key2.email}</td>
</tr>
))}
</tbody>
))}
</Table>
</div>
);
It looks like you have too many map operations going on. You need one that iterates over your nested array.
And as Gulam mentions in their comment using uuid on every tbody, tr, and td is overkill. Just add the object id as the row key.
function Example({ data }) {
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>UserName</th>
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{data.pendingShareholder[0].map(obj => (
<tr key={obj.id}>
<td>{obj.id}</td>
<td>{obj.userName}</td>
<td>{obj.firstName}</td>
<td>{obj.lastName}</td>
<td>{obj.contact}</td>
<td>{obj.email}</td>
</tr>
))}
</tbody>
</table>
);
};
const data = {pendingShareholder:[[{id:5351,userName:"iverson",firstName:"Allen",lastName:"Iverson",password:"$2a$10$20ILdapdX6u8G1nH2jIr6upiKY04LCxD9yjHKUHRhUfpuG1w1ywd2",contact:"97801671",email:"john.doe#gmail.com",roles:[{id:3,name:"ROLE_SHAREHOLDER"}]},{id:5951,userName:"rosgeller",firstName:"Ros",lastName:"Geller",password:"$2a$10$Udrju2Tj6mKGJRZA3d2GFer6kfSI988xI1/R50s.XmrHcIN1IJxoO",contact:"90908899",email:"peter.sou#gmail.com",roles:[{id:3,name:"ROLE_SHAREHOLDER"}]}]]};
// Render it
ReactDOM.render(
<Example data={data} />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Angular customer directive with filter and sort

I need to sort the json object with one of the userType thru ng-repeat. Now i was able to retrieve and display the data, and ISSUE is that I need to sort and display two different table the below list; One is for MARRIED and another for SINGLE.
How can i sort married/single when i use ng-repeat, and need to show in TWO tables. Any suggestions/help will be appreciated....
.controller('userInfo', ['$scope', 'userService', function ($scope, userService) {
userService.getuserList().then(function (users) {
users = {
"personalInfo": {
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Married",
"percentage": "50"
},"personalInfo": {
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Single",
"percentage": "50"
},
"personalInfo": {
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Married",
"percentage": "50"
}}
$scope.users = users;
});
}])
.directive('userDetails', function () {
return {
restrict: 'E',
scope: {
users: '='
},
controller: function ($scope) {
$scope.showEdit = function () {
$scope.isEdit = true;
}
},
template: `<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Relation</th>
<th>Percentage</th>
<th></th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in users">
<td>{{user.personalInfo.firstName}} {{user.personalInfo.lastName}}</td>
<td>{{user.userRelations.relationshipType}}</td>
<td><span ng-if="!isEdit">{{user.personalInfo.percent}}</span><input type="text"
ng-if="isEdit" ng-model="user.personalInfo.percent" class="form-control"></td>
<td><a ng-click="showEdit()" href="#">Update</a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">Total Percentage</td>
<td>100%</td>
<td><a ng-if="!isEdit" ng-click="showEdit()" href="#">Update</a><a ng-if="isEdit" ng-click="showEdit()" href="#">Save Percentage</a></td>
</tr>
</tfoot>
</table>
</div>`
};
})
<div class="container">
<div class="row">
<div class="col-md-9">
<h1>Update User Information</h1>
<div data-ng-controller="user">
<div data-ng-controller="userInfo">
<user-details user="users"></user-details>
</div>
</div>
</div>
</div>
</div>
users in your answer is not a valid object as it has "personalInfo" as key multiple times. You should instead create an array of objects like :
users = [{
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Married",
"percentage": "50"
},{
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Single",
"percentage": "50"
},{
"firstName": "Richardoo",
"lastName": "Gil",
"maritalStatus": "Married",
"percentage": "50"
}];
For creating two tables, for married and single,
HTML
<div class="row">
<div class="col-md-9">
<h1>Update User Information</h1>
<div data-ng-controller="user">
<div data-ng-controller="userInfo">
<user-details user="users" userfilter="single"></user-details>
<user-details user="users" userfilter="married"></user-details>
</div>
</div>
</div>
</div>
Change in userDetails directive template function
<tbody>
<tr data-ng-repeat="user in users | filter:{maritalStatus:$attrs.userfilter}">
<td>{{user.personalInfo.firstName}} {{user.personalInfo.lastName}}</td>
<td>{{user.userRelations.relationshipType}}</td>
<td><span ng-if="!isEdit">{{user.personalInfo.percent}}</span><input type="text"
ng-if="isEdit" ng-model="user.personalInfo.percent" class="form-control"></td>
<td><a ng-click="showEdit()" href="#">Update</a></td>
</tr>
</tbody>
<tr data-ng-repeat="user in users | filter:{maritalStatus:userfilter}"></tr>
$scope.sortType = 'x.user'

Handlebars not parsing data

I am trying to use handlebars to parse a javascript object but for some reason Handlebars is not loading the data properly...
Here is my template file:
{{> header}}
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Name</th>
<th>Job Title</th>
<th>Twitter</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{fullName person}}</td>
<td>{{jobTitle}}</td>
<td>#{{twitter}}</td>
</tr>
{{/users}}
</tbody>
</table>
</script>
<body>
<!-- Insertion point for handlebars template -->
<div id="main" style="margin-left:100px">
</div>
</body>
<script type="text/javascript" src="javascript/templating.js"></script>
Here is my .js file:
$(document).ready(function() {
var source = $("#some-template").html();
var template = Handlebars.compile(source);
var data = {
users: [ {
person: {
firstName: "Garry",
lastName: "Finch"
},
jobTitle: "Front End Technical Lead",
twitter: "gazraa"
}, {
person: {
firstName: "Garrasd",
lastName: "Finch"
},
jobTitle: "Photographer",
twitter: "photobasics"
}, {
person: {
firstName: "Garry",
lastName: "Finch"
},
jobTitle: "LEGO Geek",
twitter: "minifigures"
} ]
};
Handlebars.registerHelper('fullName', function(person) {
return person.firstName + " " + person.lastName;
});
console.log(template(data));
$("#main").append(template(data));
});
Note - when I console.log(template(data)), I get the following:
<table>
<thead>
<th>Name</th>
<th>Job Title</th>
<th>Twitter</th>
</thead>
<tbody>
</tbody>
Anyone have any idea what I'm doing wrong?? I'm using node.js + express.
Thank you!!
You didn't define any block helper for users but trying to use it in the template.
Change these lines
...
{{#users}}
...
{{/users}}
...
to these:
...
{{#each users}}
...
{{/each}}
...
Check out the documentation here: http://handlebarsjs.com/builtin_helpers.html#iteration
The each block helper
You can iterate over a list using the built-in each helper. Inside the
block, you can use this to reference the element being iterated over.

AngularJS set html properties

we are pretty bloody beginners with JavaScript and AngularJS, but the scenarios is pretty simple. We want to set html properties received from a REST service.
This is our profileController.js:
angular
.module('app')
.controller('profileController', ['$scope', '$http', '$window', function($scope, $http) {
// REST service works properly
var resource = 'http://localhost:8080/user';
$http.get(resource).then(function(result){
// logs right json
console.log(result);
// no effect
$scope.content = result.data.toString();
// no effect
if(!$scope.$$phase) {
$scope.$apply();
}
});
} ]);
profile.html
<div>
<div class="container">
<br><br><br>
<h2 class="sub-header">Profile</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Forename</th>
<th>Name</th>
<th>Role</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{profile.data}}</td>
<!-- Doesn't work as well
<td>{{profile.forename}}</td>
<td>{{profile.lastname}}</td>
<td>{{profile.role}}</td>
<td>{{profile.email}}</td>-->
</tr>
<div id="container" ng-controller="profileController">
<content-item forename="item"></content-item>
</div>
</tbody>
</table>
</div>
</div>
</div>
The REST service works properly and sends the json back, the log outputs in the JavaScript console are right, just the setting in html doesn't work and we have absolutely no clue.
Thanks in advance!
Consider this Plunk.
app.controller("myController", [
"$scope",
function($scope){
$scope.content = [
{
"firstname": "Natalie",
"lastname": "Portman",
"role": "Accountancy",
"email": "n.p#email.com"
},
{
"firstname": "Johnny",
"lastname": "Depp",
"role": "Sales Management",
"email": "j.d#email.com"
},
{
"firstname": "Kevin",
"lastname": "Costner",
"role": "Crisis control",
"email": "k.c#email.com"
},
];
}]);
Where the above $scope.content is a hardcoded simulation of your $scope.content = result.data;.
And usage:
<tr ng-repeat="profile in content">
<td>#</td>
<td>{{profile.firstname}}</td>
<td>{{profile.lastname}}</td>
<td>{{profile.role}}</td>
<td>{{profile.email}}</td>
</tr>
Check the Plunk for the complete code.
PS: I changed the {{profile.data}} to # for the example, as I don't know what that's supposed to be.
Try this
Check your ng-controller and ng-app too, this step in the angular tutorial should be fine for this.
Here, in your code, the ng-controller should be at least in the table tag i.e
<div>
<div class="container">
<br><br><br>
<h2 class="sub-header">Profile</h2>
<div class="table-responsive">
<table class="table table-striped" ng-controller="profileController">
<thead>
<tr>
<th>#</th>
<th>Forename</th>
<th>Name</th>
<th>Role</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{content}}</td>
<!-- Doesn't work as well
<td>{{content.forename}}</td>
<td>{{content.lastname}}</td>
<td>{{content.role}}</td>
<td>{{content.email}}</td>-->
</tr>
<div id="container">
<content-item forename="item"></content-item>
</div>
</tbody>
</table>
</div>
</div>
convert
$scope.content = result.data.toString();
to this:
$scope.content = result.data;
And if you want to print the data inside
<td>{{profile.data}}</td>
you have to change position of controller in html tag..

Accessing a JSON in AngularJS using ng-repeat

<table class="table table-striped" >
<thead>
<tr>
<th>Number</th>
<th>Zeroes</th>
</tr>
</thead>
<tbody ng-controller="ViewData as viewAll">
<tr ng-repeat="pop in viewAll.number">
<td>{{pop.number}}</td>
<td>{{pop.zeroes}}</td>
</tbody>
</table>
I have this table and I'm trying to get data to be outputted in it.
app.controller('ViewData', ['$http', '$scope',
function($http,$scope) {
$scope.viewAll = this;
$http.get('/someurl').success(function(data) {
$scope.viewAll.number = data;
});
}]);
This my controller getting the data.
{"number": {
"4": {
"zeroes": "5"
},
"5": {
"zeroes": "6"
},
"10": {
"zeroes": "7"
}}
And this is the data that /someurl is giving out to me.. Is there any way I can be able to handle this so I can be able to show it outside the table.
Thanks in advance for any kind of help given!
try:
<table class="table table-striped" >
<thead>
<tr>
<th>Number</th>
<th>Zeroes</th>
</tr>
</thead>
<tbody ng-controller="ViewData as viewAll">
<tr ng-repeat="{key, value} in viewAll.number">
<td>{{key}}</td>
<td>{{value.zeroes}}</td>
</tbody>
</table>
app.controller('ViewData', ['$http', '$scope',
function($http,$scope) {
var self = this;
$http.get('/someurl').success(function(data) {
self.number = data;
});
}]);

Categories

Resources