Currently I want to show HTML table by parsing JSON data from file using Angular JS, And It's not working can someone please help me?
And Also As a Enhancement How Can I get the 2 Divs for 2 different JSON file
HTML Code
<html>
<div ng-controller="get_controller">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="geValues()" class="btn btn-primary">Submit</button>
</span>
</div>
<div ng-controller="get_controller">
<table>
<tbody>
<tr>
<th ng-repeat="list in personDetails">{{list.Name}}
</th>
</tr>
<tr>
<td class="features" ng-repeat="list in personDetails">{{list.Location}}
</td>
</tr>
</tbody>
</table>
</div>
</html>
Angular JS Code
var app = angular.module('myApp', ["ngTable"]);
app.controller('get_controller', function ($scope, $http) {
$scope.geValues = function() {
$http({method: 'POST', url: 'posts.json'}).success(function(data) {
$scope.post = data;
$scope.personDetails = Employee;
})
},
});
posts.json (Json File)
{
"Employee": [
{
"Name": "Rocky",
"Location": "Office"
},
{
"Name": "John",
"Location": "Home"
}
]
}
Should be a GET request, also the you need to access the data from the response object which contains the Employee array. Code should be,
$http.get('test.json').then(function (response){
$scope.post = response.data;
$scope.personDetails = response.data.Employee;
});
if you want it to happen on ng-click, put the call inside a function,
$scope.geValues = function() {
$http.get('test.json').then(function(response) {
$scope.post = response.data;
$scope.personDetails = response.data.Employee;
});
}
DEMO
Related
I am pretty new to angular and i am running into an issue displaying JSON data with the ng-repeat tag in my JSP.
Here's my code,
I am fetching data from an external REST service and it is sending me the JSON which is well formatted.
Here's the sample JSON,
{"products":[
{
"description":"E-Series Util",
"effectiveEndDate":"2099-04-20",
"effectiveStartDate":"2018-04-20",
"id":"2c92c0f962e1d5af0162e698b14b6520",
"name":"NOD-E-series-Utilities",
"productFeatures":[
],
"productRatePlans":[
{
"description":"",
"effectiveEndDate":"2025-04-20",
"effectiveStartDate":"2018-04-20",
"id":"2c92c0f862e1caed0162e699ffc922e6",
"name":"NOD-E series-Utilities",
"productRatePlanCharges":[
{
"billingDay":"SpecificDayofMonth/1st of the month",
"billingPeriod":"Month",
"billingPeriodAlignment":"AlignToCharge",
"description":"",
"endDateCondition":"Subscription_End",
"financeInformation":{
"deferredRevenueAccountingCode":"",
"recognizedRevenueAccountingCode":""
},
"id":"2c92c0f962e1d5af0162e6a313cc752d",
"model":"PerUnit",
"name":"NOD-E Series-Utilities-NR",
"pricing":[
{
"currency":"USD",
"price":"0E-9"
}
],
"pricingSummary":[
"USD0/NR"
],
"ratingGroup":"ByBillingPeriod",
"revenueRecognitionRuleName":"Recognize upon invoicing",
"taxCode":"",
"taxable":false,
"triggerEvent":"ContractEffective",
"type":"Usage",
"uom":"NR",
"usageRecordRatingOption":"EndOfBillingPeriod",
"useTenantDefaultForPriceChange":true
},
{
"billingDay":"SpecificDayofMonth/1st of the month",
"billingPeriod":"Month",
"billingPeriodAlignment":"AlignToCharge",
"description":"",
"endDateCondition":"Subscription_End",
"financeInformation":{
"deferredRevenueAccountingCode":"",
"recognizedRevenueAccountingCode":""
},
"id":"2c92c0f862e1caed0162e6a0cb842eab",
"model":"PerUnit",
"name":"NOD-E Series-Utilities-Usage",
"pricing":[
{
"currency":"USD",
"price":"0.100000000"
}
],
"pricingSummary":[
"USD0.1/GB"
],
"ratingGroup":"ByBillingPeriod",
"revenueRecognitionRuleName":"Recognize upon invoicing",
"taxCode":"",
"taxable":false,
"triggerEvent":"ContractEffective",
"type":"Usage",
"uom":"GB",
"usageRecordRatingOption":"EndOfBillingPeriod",
"useTenantDefaultForPriceChange":true
}
],
"status":"Active"
}
],
"sku":"SKU-00000020"
}
}
Here's my HTML snippet
<div class="panel-body">
<div class="row" ng-repeat="a in products">
<table class="table table-striped">
<tr>
<td class="col-md-8 lead "><strong>{{a.name}}</strong></td>
<td class="col-md-2">
<button id="view_btn" class="btn btn-sm prospect-color"
ng-click="showplan = ! showplan"
>View Plans</button>
</td>
<td class="col-md-2">
<button id="add_cart_btn" class="btn btn-sm prospect-color"
ng-click="addItemToCart(a)"
>Add to Cart</button>
</td>
</tr>
<tr>
<td class="col">
<div class="card card body" ng-show="showplan" ng-repeat="r in a.productRatePlans" >
<strong>{{a.description}} with SKU # - {{r.name}} </strong> {{a.sku}}</div>
</td>
</tr>
</table>
</div>
</div>
Here's my JS file,
$http({
method: 'GET',
url:'/WebStoreSMP/rest/products/',
}).then(function (response)
{
// var obj = JSON.parse(response);
$scope.products = angular.fromJson(response);
console.log("[main] # of items: " + JSON.stringify(response))
},function (error){
alert("AJAX failed to get data for product, status=" + error);
});
The issue is that i am not seeing any data on the HTML page.
The console log is printing the entire JSON response.
Any idea what might be wrong here?
Thanks,
VK
Hopefully someone can help.
I am developing an application using HTML AngularJs which uses ng-repeat,ng-options and ng-model and populates multiple rows based on the data in the database for a user. Each row has static data coming from DB (returned as object via restAPI) and dynamic select option for user selection. Select option is hardcoded in app.js and linked to model on HTML for DB update upon selection using update button. Each row has its own button and i can see update function is working at row level.
I want to set the default value of the drop down list dynamically as value of an element coming from database. Object is same as one being used to populate rows with static data .
Code is in the fiddle at https://jsfiddle.net/6j88L61y/4/
HTML below
<body>
<h1 align="center">User Tracker</h1>
<div ng-controller="MainController as main">
<div>
<p>Please Enter ID </p>
<p>
<input type="text" ng-model="main.model.userName"></input>
<button ng-click="main.model.getOrgList()">List State List</button>
</p>
</div>
<hr ng-show="main.model.formSubmitted"></hr>
<div>
<table class="table table-bordered" border="1">
<thead>
<tr>
<th>ID</th>
<th>User Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="org in main.model.orgList" id="{{org.id}}">
<td>{{org.id}}</td>
<td align="center">{{org.user}}</td>
<td align="center">
<select ng-model="main.model.selectedRecord.appCurrentStateSelected[$index]" ng-options="option.value as option.value for option in main.model.appCurrentStateList" ></select>
</td>
<td>
<button ng-click="main.model.updateAppDetailsList({id:org.id,userName:org.name,appCrntState:main.model.selectedRecord.appCurrentStateSelected})">Update</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
JS
"use strict";
angular.module('myApp',[]);
angular.module('myApp').service('AppModel', function( $http) {
this.userId='';
this.userName ="";
this.formSubmitted="";
this. selectedRecord ={appCurrentStateSelected:''};
this.appCurrentStateList =[{name: 'New',value:'New',id:1}, {name: 'InUse',value:'InUse',id:2},{name: 'Inactive',value:'Inactive',id:3},{name: 'Deleted',value:'Deleted',id:4}];
this.submittedAppDetailsList=[];
console.log(' json sample:'+this.submittedAppDetailsList);
var path = 'home';
var currentProtocol = location.protocol;
var host =location.host;
var apiHost = currentProtocol+'//'+host+'/api/';
console.log('API url is : ' +apiHost);
// Get method
this.getOrgList = function() {
var path = 'home/userid';
console.log(this.userName);
console.log(this.selectedRecord);
$http.get(apiHost+path+'/'+this.userName+'/')
.then(function(response) {
this.orgList =response.data;
this.formSubmitted = true;
console.log(response.data);
}.bind(this),
function(response) {
console.log(response.data);
});
}
// Post method
this.updateAppDetailsList = function(appdetailsList) {
var path = 'home/update';
console.log(this.selectedRecord);
$http.post(apiHost+'home/update/',appdetailsList)
.then(function(response) {
this.submittedAppDetailsList.push(response.data);
this.formSubmitted = false;
console.log(response.data);
}.bind(this),
function(response) {
console.log('Error : '+response.data);
});
}
});
angular.module('myApp').controller('MainController', ['AppModel', function (AppModel) {
this.model = AppModel;
}]);
I'm currently learning Electron and using AngularJS.
I've my REST api in node and express and my database is MongoDB.
this is my route
router.get('/branch/:branch',function (req,res,next) {
var br = req.params.branch;
var final = [];
db.collection('users').find({"branch": br}, function (err, docs) {
docs.forEach(function (ele) {
console.log(ele['fir_id']);
final.push(ele['fir_id']);
})
db.punch_coll.find(function (err, docs) {
var d = [];
console.log(final);
docs.forEach(function (ele) {
console.log(ele['fir_id']);
if(final.includes(parseInt(ele['fir_id']))) {
ele['date'] = ele['date'].toDateString();
ele['punch_in'] = ele['punch_in'].substring(0, 8);
ele['punch_out'] = ele['punch_out'].substring(0, 8);
d.push(ele);
}
console.log(d);
})
console.log(d);
res.send(d);
})
});
});
punch_coll document
{
_id: 58e21075e0c6800ce8b08d92,
fir_id: '4',
date: 'Mon Apr 03 2017',
punch_in: '14:35:57',
punch_out: ''
}
user document
{
_id: 58e20ee0e0c6800ce8b08d82,
name: 'A B C',
fir_id: 1,
branch: 'CSE',
year: 'SE'
}
HTML and Angular Controller Script
<body ng-app="myApp" ng-controller="myCtrl">
<form class="pure-form">
<strong>Enter FIR-ID</strong> <input type="text" ng-model="fid" ng-
change="change()" class="pure-input-rounded">
</form>
</br>
<div class="pure-g">
<div class="pure-u-8-24" style="border-style: solid;border-
color:lightgrey;">
<header class="w3-container w3-light-grey">
<h2>Fir ID :- {{fid}}</h2>
<h3>Name :- {{user[0].name}} </h3>
</header>
<div class="w3-container">
<h2>Branch :- {{user[0].branch}} </h2>
<hr>
<h2>Academic Year :- {{user[0].year}} </h2>
</div>
</div>
</div>
<form class="pure-form">
<select id="state" ng-model="branch" ng-change="changeBranch()">
<option>CSE</option>
<option>MECH</option>
<option>CIVIL</option>
<option>ENTC</option>
</select>
</form>
<!-- <h2>Fir ID :- {{fid}}</h2>
<h2>Name :- {{user[0].name}} </h2>
<h2>Branch :- {{user[0].branch}} </h2>
<h2>Academic Year :- {{user[0].year}} </h2> -->
<div style="right:0;top:0;position:absolute;font-size:20px;">
<table class="pure-table pure-table-horizontal">
<thead>
<tr>
<th>Fir ID</th>
<th>Date</th>
<th>Punch In</th>
<th>Punch Out</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in name">
<td>{{ x.fir_id }}</td>
<td>{{ x.date }}</td>
<td>{{ x.punch_in }}</td>
<td>{{ x.punch_out }}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
// You can also require other files to run in this process
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.name;
$scope.user;
$scope.fid;
$scope.branch='CSE';
$scope.change = function() {
//get punches for specific fir_id
$http.get('http://localhost:3000/users/'+$scope.fid)
.then(function(response) {
$scope.user=response.data;
})
//get punches for specific fir_id
$http.get('http://localhost:3000/punch/'+$scope.fid)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
$scope.changeBranch = function(){
//get record as per branch
$http.get('http://localhost:3000/branch/'+$scope.branch)
.then(function(response) {
console.log(response.status);
$scope.name=response.data;
}, function errorCallback(response) {
$scope.name=null;
});
};
});
The table is rendering slow for large json takes 1second it's like it's lagging.
I'm new to this so of course I'm doing something horrible. I think the way I'm using that async functions are bad also but dont know whats making it slow foreach or anything else.
So, after replacing foreach with simple for loop it solved the problem but I don't know whats the exact reason. Anyone had same problem?
I'm an old "backender" and pretty new to Angular and modern frontend programming, but I have to learn...
I have the following problem: There is a list with several different person properties, which are created via ng-repeat from Controller response. The values are editable, but the display control depends on the type of the property. The Gender, for example, needs to be edited via a Select-Box. The options for the select box are obtained from a Rest-Server.
So now the main question: How can I build different Select Boxes for each property?
I tried the following code, which is not working:
<section class="contactProperty" ng-repeat="property in contactDetail.properties">
<table>
<tr>
<td>{{property.message}}</td>
<td rowspan=2>{{property.value}}
<script>
var lst = ContactDetailController.getClassification(property.type);
</script>
<input ng-show="{{property.displaystyle_id}}==1" type="text" ng-model="property.value"/>
<select ng-show="{{property.displaystyle_id}}==3" ng-model="property.value">
<option ng-repeat="opt in lst" value="{{opt.id}}">{{opt.message}}</option>
</select>
</td>
</tr>
<tr>
<td>
<select type="text" ng-model="property.status_id">
<option ng-repeat = "status in contactDetail.propertyStatus" value="{{status.id}}">{{status.message}}</option>
</select>
</td>
</tr>
</table>
</section>
The Controller is defined on the top level element with following code
.controller('ContactDetailController',
['$scope', '$rootScope', 'ContactDetailService',
function ($scope, $rootScope, ContactDetailService) {
$scope.getContactDetail = function () {
ContactDetailService.getContactDetail(function(response) {
if(response.success) {
$scope.contactDetail=response;
} else {
$scope.error = response.message;
}
});
};
$scope.getClassifications= function(type) {
ContactDetailService.getClassifications(type, function(response) {
if (response.success) {
return response;
}
});
};
$scope.getContactDetail();
}]);
And the corresponding service:
.factory('ContactDetailService',
['$http', '$rootScope', '$location',
function ($http, $rootScope, $location) {
var service = {};
service.getContactDetail = function(callbackFunc) {
delete $http.defaults.headers.common['X-Requested-With'];
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$rootScope.apiRoot=apiRoot;
var id=$location.search().id;
$http.get(apiRoot+'/contactdetail?id='+id, {})
.success(function(response){
$rootScope.contactDetail=response;
callbackFunc(response);
}).error(function(response){
alert("error"+response.message);
});
};
service.getClassifications = function(type, callbackFunc) {
var apiRoot="";
apiRoot = $rootScope.environments[window.location.host];
$http.get(apiRoot+'/classifications?type='+type, {})
.success(function(response) {
callbackFunc(response);
})
.error(function(response) {
alert("error"+response.message);
});
};
return service;
}]);
Can anyone help me?
you can show/hide fields using ng-show/ng-hide or ng-if or ng-switch depending on your type of variable selected. if this is what you want.
I will try to explain more precisley:
This is a part of my incomming Json from the Backend:
"properties": [
{
"id": 8,
"type_id": 25,
"status_id": 13,
"contact_id": 4,
"value": "27",
"create_date": null,
"update_date": null,
"guikey": "gui.gender",
"message": "Geschlecht",
"displaystyle_id": 3,
"queryparam": "9",
"options": [
{
"id": 26,
"type": 9,
"guikey": "gui.male",
"language": "de",
"message": "Männlich",
"displaystyle_id": 0
},
{
"id": 27,
"type": 9,
"guikey": "gui.female",
"language": "de",
"message": "Weiblich",
"displaystyle_id": 0
}
]
}
],
It is rendered by following code:
<section class="contactProperty" ng-repeat="property in contactDetail.properties">
<table>
<tr>
<td>{{property.message}}</td>
<td rowspan=2 ng-switch on="property.displaystyle_id">{{property.value}}
<input ng-switch-when="1" type="text" ng-model="property.value"/>
<input ng-switch-when="2" type="date" ng-model="property.value"/>
<select ng-switch-when="3" ng-model="property.value">
<option ng-repeat="opt in property.options" value="{{opt.id}}">{{opt.message}}</option>
</select>
</td>
</tr>
<tr>
<td>{{property.status_id}}
<select type="text" ng-model="property.status_id">
<option ng-repeat = "status in contactDetail.propertyStatus" value="{{status.id}}">{{status.message}}</option>
</select>
</td>
</tr>
</table>
</section>
The resulting HTML contains a Select box as expacted:
<section class="contactProperty ng-scope" ng-repeat="property in contactDetail.properties">
<table>
<tbody>
<tr>
<td class="ng-binding">Geschlecht</td>
<td class="ng-binding" on="property.displaystyle_id" ng-switch="" rowspan="2">
27
<select class="ng-scope ng-pristine ng-valid" ng-model="property.value" ng-switch-when="3">
<option class="ng-binding ng-scope" value="26" ng-repeat="opt in property.options">Männlich</option>
<option class="ng-binding ng-scope" value="27" ng-repeat="opt in property.options">Weiblich</option>
</select>
</td>
</tr>
<tr>
</tbody>
</table>
</section>
But the Browser displays the Value "Männlich" in this example, but I expected to see "Weiblich" because the property.value 27 is passed from the json. I just show the value for debug as {{property.value}} and it shows 27, which is correct. I don't understand why the dropdown still showing the first entry (26/Männlich) in this case...
I'm relatively new to Angular and got stuck with something ....
I'm trying to add a function to my controller and then to my view/html that would allow me mark a Vote <button> active/inactive based on the result of comparison of data from two different json files. Pseudo code would be something like this
if Vote exists:
display disabled vote button with a number of existing votes
else:
display active vote button (with a number of existing votes) and then disable it after vote has been submitted
that function would be checking if link.id list exists in users's vote.link/id list
link json example
{"description": "Lorem Ipsum", "id": 1, "resource_uri": "/api/v1/links/1/", "timestamp_added": "2015-02-15T17:22:33.300349", "url": "http://google.com/", "user": "user1"}
vote json example
{"id": 351, "resource_uri": "/api/v1/votes/351/", "timestamp_added": "2015-03-30T15:00:09.622308", "user": "user1", "vote": "up", "voted_link": "1"}
controller.js
app.controller('LinksCtrl', function ($scope, $http){
$http.get('http://localhost:8001/api/v1/links/?limit=0').
success(function(data) {
console.log('http.get OK');
$scope.links = data;
});
$http.get('http://localhost:8001/api/v1/votes/?limit=0').
success(function(data) {
console.log('http.get OK');
$scope.votes = data;
});
$scope.sortField = 'objects.likes';
$scope.reverse = true;
<!-- ############# LOOKING FOR HELP WITH THIS FUNCTION ###########
$scope.isDisabled = function (link_id) {
return "true if link_id is present in the list of link IDs from the votes array" );
};
-->
$scope.voteUp = function(id){
$http.post('http://localhost:8001/api/v1/votes/', {
user: "user1",
voted_link: "1",
vote: "up"
}).
success(function(data, status, headers, config) {
console.log('http.post OK');
}).
error(function(data, status, headers, config) {
console.log('http.post NOK');
});
};
});
view.html
<div ng-controller="LinksCtrl">
<tr ng-repeat="link in links.objects">
<td>{{ link.url }}</td>
<td>{{ link.description }}</td>
<td><button
ng-disabled="isDisabled(link.id)"
ng-click="voteUp(link.id)"
>Vote
</button></td>
</tr>
</div>
Code also here: https://jsfiddle.net/v6hkz9rr/7/.
Any ideas how should I be going about it?
thanks
-s
I modified your example to match your request. check this out
i replaced $http calls with static data for the demo
js
var app = angular.module('plunker', []);
app.controller('LinksCtrl', function($scope) {
$scope.links = {
objects: [{
id: 1,
url: 'https://facebook.com',
description: 'facebook the social network',
votes: 4
}, {
id: 2,
url: 'https://google.com',
description: 'google inc',
votes: 10
}]
};
$scope.votes = [];
/*-- ############# LOOKING FOR HELP WITH THIS FUNCTION ########### */
$scope.isDisabled = function(link) {
return $scope.votes.indexOf(link.id) >= 0;
};
$scope.voteUp = function(link) {
link.votes++;
$scope.votes.push(link.id);
}
});
html
<body ng-controller="LinksCtrl">
<div class="container">
<h4>Links</h4>
<table class="table table-bordered">
<thead>
<tr>
<th>
url
</th>
<th>
description
</th>
<th>
#
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="link in links.objects">
<td>{{ link.url }}</td>
<td>{{ link.description }}</td>
<td>
<button class="btn btn-xs btn-default" ng-disabled="isDisabled(link)" ng-click="voteUp(link)">Vote ({{link.votes}})</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
http://plnkr.co/edit/xPEnB4inzZxVUBsWpaw1?p=preview