Issue with parsing JSON in Angular 1.6.9 - angularjs

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

Related

Show button on change ng-model AngularJS

I want to show button post only when modelCheck will change.
My code :
HTML :
<table>
<tr>
<th>name</th>
<th><button class="btn" ng-if="modelCheck === {}" ng-click="post()">post</button></th>
<th><button class="btn disabled" ng-if="modelCheck !== {}" ng-click="post()">post</button></th>
</tr>
<tr ng-repeat="x in messages">
<td>{{x.name}}</td>
<td><input type="checkbox" ng-model="modelCheck[x.name]"/></td>
</tr>
</table>
JS:
$scope.modelCheck = {};
$scope.messages =
[
{
"name": "eva",
},
{
"name": "ben",
},
];
$scope.post = function(){
var data = [];
for (var k in $scope.modelCheck) {
if ($scope.modelCheck.hasOwnProperty(k) && $scope.modelCheck[k]) {
data.push({'name': k});
}
}
console.log(data);
// do with data as you wish from here
};
Plunker:http://next.plnkr.co/edit/xQ3AGFW03qGWKyxI
My code doesn't work. Thanks for answers and help in advance!
use this condition to check the empty object
<th><button class="btn" ng-if="(modelCheck | json) != ({} | json)" ng-click="post()">post</button></th>

AngularJS Displaying a sorted $http response in template partial

I'm currently working on a project that I need to sort the response by category and subcategory using Angular.
My controller currently looks like:
function($http, $stateParams) {
let vm = this;
$http({
method: 'GET',
url: url,
timeout: 10000,
contentType: "application/json;odata=verbose",
headers: {"Accept": "application/json;odata=verbose"},
params: {},
}).then(function(data, status, headers, config) {
let documents = data.data.d.results;
$.each(documents, function(i, item){
vm.data = sortDocuments(documents);
})
}).catch(function(error) {
console.log(error);
});
function sortDocuments(documents) {
return _.sortBy(documents, item => {
return {
category: item.Category,
subcategory: item.Subcategory,
documentURL: item.EncodedAbsUrl,
tags: item.Tags
}
})
};
})
I need to sort the category and subcategories in my view, but not sure how to go about doing it. My template partial currently looks like:
<div uib-accordion-group class="panel-default" heading="Subcategory Name">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Tags</th>
<th>Link</th>
</tr>
</thead>
<tbody ng-show="item.subcategory == 'Subcategory Name'" ng-repeat="item in documents.data">
<tr>
<td>
<p>{{ item.name }}</p>
</td>
<td>
<p>{{ item.tags.results }}</p>
</td>
<td>
<a href="{{ item.documentURL }}">Open
Document</a>
</td>
</tr>
</tbody>
</table>
</div>
Can anyone tell me what I'm missing in order to sort the view by category and subcategory?
I'm not sure why you're using _.map there. _.sortBy should do what you need.
http://underscorejs.org/#sortBy
this should be pretty close:
vm.data = _.sortBy(data.data.d.results, document => { return document.Category + document.Subcategory } )

Angular in electron, slow rendering for large json

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?

AngularJS JSON load from file with ng-click

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

Angular ng-repeat with filter not updating with http.get

I am filtering an array (results) with a query. By removing the filter, results accurately displays all elements. By removing the http.get that updates results and initializing results to contain elements, the filter accurately filters.
With both the filter and the http.get updating results, the message for no results is showing even when results contains data. I have verified that results is properly updated by the http.get (as evidenced by {{results}} showing correctly below). The following is what {{results}} displays:
[
{
"name": "Company Number 1 ",
"description": "description of 1 "
},
{
"name": "Company Number 1 ",
"description": "description of 1 "
},
{
"name": "Company Number 2 ",
"description": "description of 2 "
}
]
index.html
<div class="form-group label-floating">
<label class="control-label" for="addon1">Filter</label>
<input id="addon1" class="form-control" type="text" data-ng-model="query">
</div>
{{results}} <!--This works properly-->
<table class="table table-striped" id="resultsTable">
<tbody>
<tr data-ng-show="resultsFilter.length === 0">
<td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
</tr>
<tr data-ng-repeat="result in resultsFilter = (results | filter:query | limitTo:displayNum) track by result.name">
<td>
<button class="btn btn-primary btn-block">
{{result.name}}
</button>
</td>
</tr>
</tbody>
</table>
angular.js
$scope.query = "";
$scope.displayNum = 20;
$scope.results = [];
...
$scope.updateResults = function () {
$http({
method: "GET",
url: requestUrl,
params: {id: $scope.identifierInHierarchy.companyId}
})
.then(function successCallback(response) {
$scope.query = "";
$scope.results = [];
response.data.forEach(function (entry) {
$scope.results.push({
name: "Company Number " + entry.CompanyNumber,
description: "description of " + entry.CompanyNumber
});
});
},
function errorCallback(response) {
});
}
Update: No, changing resultsFilter to results does not resolve the issue. I also believe it is not incorrect since keeping resultsFilter and initializing results statically will filter correctly (as previously stated).
It's showing no result because of this
<tr data-ng-show="resultsFilter.length === 0">
<td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
</tr>
resultsFilter scope is limited to ng-repeat and you are trying to access it above scope. so Please change it only with results and then test it.
Hope this helps!!
You are using resultsFilter everywhere which is no where declared. It should be results.
<table class="table table-striped" id="resultsTable">
<tbody>
<tr data-ng-show="{{results.length}} === 0">
<td class="center" colspan="3">No results found.</td> <!--This message appears even when results should have elements-->
</tr>
<tr data-ng-repeat="result in results = (results | filter:query | limitTo:displayNum) track by result.name">
<td>
<button class="btn btn-primary btn-block">
{{result.name}}
</button>
</td>
</tr>
</tbody>

Resources