ng-repeat parsing every character of json - angularjs

Still Trying to track down why I cannot display json data from asp.net webmethod won't display in table using ng-repeat - I've gotten to the point where it looks like there is an issue with my json but I don't see the problem
The table with the server json - I added an index column and it seems to add a row per character ??
Here is a screenshot of the data - There is the json data from the server and a manually created angular collection that looks like my json data
Thanks for any insight
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test1.aspx.cs" Inherits="SampleAngularjs.Test1" %>
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
<body ng-app="codeapp">
<div ng-controller="CodeController" >
<button ng-click="doClick(item, $event)">Send AJAX Request</button>
<br />
Data from server: {{codes}}
<br />
Data from Manually built Collection: {{fields}}
<br />
<h3>And here is what you get if you just return the promise returned by $http.get():</h3>
<pre>{{codes | json}}</pre>
<br />
<h3>Manually Built Angular Collection Table</h3>
<table>
<tr>
<th>Code</th>
<th>Desc</th>
</tr>
<tr ng-repeat="code in fields">
<td>{{code.Code}}</td>
<td>{{code.Desc}}</td>
</tr>
</table>
<br />
<h3>Server Json Table</h3>
<table>
<tr>
<th>Row</th>
<th>Code</th>
<th>Desc</th>
</tr>
<tr ng-repeat="code in codes track by $index">
<td>({{$index + 1}}) </td>
<td>{{code.Code}}</td>
<td>{{code.Desc}}</td>
</tr>
</table>
</div>
<script>
angular.module("codeapp", [])
.controller("CodeController", function ($scope, $http) {
$scope.fields = [{ Code: "aaa", Desc: "aaa, desc" }, { Code: "bbb", Desc: "bbb, desc" }];
$scope.codes = [];
$scope.doClick = function (item, event){
$http.post('Test1.aspx/GetAllCodes', { data: {} })
.success(function (data, status, headers, config) {
$scope.codes = data.d;
})
.error(function (data, status, headers, config) {
$scope.status = status;
});
}
})
.config(function ($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
</script>
</body>
</html>

You're getting a string from the server and ng-repeat over a string gives you each character. Try parsing it yourself to see if it works, then check out the request and response headers to see why it isn't sending the data back as application/json:
.success(function (data, status, headers, config) {
$scope.codes = JSON.parse(data.d);
})

Related

angularjs with jquery datatable search button does not work

When i try to use jquery datatable with angularjs, search button doesn't work. but if i bind the data using pure asp.net mvc by actionresult method, it works correctly.
I bind the data from user-role.js and i'm using ng-repeat to bind them.
my angularjs version is 1.7.2
jquery.datatble version is 1.10.16
cshtml codes below.
<script type="text/javascript" src="~/Scripts/app/user-role.js"></script>
<div ng-app="userRoleGridApp" ng-controller="userRoleGridCtrl">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="table-responsive">
<table class="table" id="user-table">
<thead>
<tr>
<th>UserId</th>
<th>User Name</th>
<th>Name Surname</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in Users track by $index">
<th>{{x.UserId}}</th>
<th>{{x.UserName}}</th>
<th>{{x.NameSurname}}</th>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#user-table').DataTable({
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
//'csvHtml5',
'pdfHtml5'
]
});
});
</script>
Js side
var app = angular.module("userRoleGridApp",
['ngAnimate',
'ngRoute']);
var baseUrl = location.origin;
app.controller("userRoleGridCtrl", function ($scope, $http) {
$scope.Users = {};
initUser();
function initUser() {
$http({
method: "get",
url: baseUrl + "/UserRole/GetUsers"
}).then(function (response) {
$scope.Users = response.data;
}, function () {
alert("Error Occur");
});
}
});

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 JS ng-repeat not displaying values

I am making an REST call from angular to Spring . I am able to get the response back .When i am trying to populate the values in the view using ng-repeat , nothing is shown on the screen .
This is my Angular Code This code is inside the showhidecontroller
var resuls = $http.post('http://localhost:8080/aeservices/AddConfig', dataobj);
resuls.success(function(data, status, headers, config) {
$scope.dbresponse= data;
$scope.messagetest = $scope.dbresponse[0].messages;
alert($scope.messagetest);
console.log( $scope.messagetest);
console.log(data);
});
This is my Response i recieved from API
[{
"data12": null,
"name": null,
"errors": ["error data1", "error data2"],
"messages": ["Configuration has been Added successfully", "Configuration has been Added successfully"]
}]
This is my HTML
<table ng-controller="ShowHideController">
<tr ng-repeat="item in dbresponse[0].errors" >
<span><td align="left" class="validationMsg"><img src="images/red_bullet.gif" border="0" width="8" height="8" alt="">&nbsp
{{item}}
</td></span></tr>
</table>
I tried using ng-repeat by declaring myself an item like this $scope.items = ['one','two','three','four']. Even this is not showing up on the HTML.
Try using data.data,
Controller:
app.controller("listController", ["$scope", "$http",
function($scope, $http) {
$http.get('test.json').then(function(response) {
$scope.dbresponse = response.data;
});
}
]);
HTML:
<table ng-controller="listController">
<tr ng-repeat="item in dbresponse[0].errors">
<td align="left" class="validationMsg"><img src="images/red_bullet.gif" border="0" width="8" height="8" alt=""> {{item}}
</td>
</tr>
</table>
DEMO
Please try this below code and don't declare variable resuls.
$http.post('http://localhost:8080/aeservices/AddConfig', dataobj).success(function(data, status, headers, config) {
$scope.dbresponse= data;
$scope.messagetest = $scope.dbresponse[0].messages;
alert($scope.messagetest);
console.log( $scope.messagetest);
console.log(data);
});
The Problem that happened was i have declared my controller twice in the HTML

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 JSON Response

Below is a json response from my API. I would like to utilize ng-repeat in my html in order to show this data back to an end-user. How do I go about in my controller de-serializing this json data.
{
"message": "Query to return servers",
"result": [
{
"meta": [
"Computer",
"SQLPort",
"Domain"
],
"rows": [
[
"MyCompterName",
"1433",
"XXXX"
]
]
}
]
}
here is the code for the app.js that get loaded into the index.html
var app = angular.module('DSCApp', ['ngRoute', 'ngResource','ui.router']);
Config
app.config(function($routeProvider){
$routeProvider
.when('/DSC', {
templateUrl: "DSC.html",
controller: 'DscController'
})
.otherwise({ redirectTo: '/' });
});
Data Factory
app.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api';
var dataFactory = {};
dataFactory.getServers = function () {
return $http.get(urlBase);
};
return dataFactory;
}]);
Controller
app.controller('DscController', ['$scope', 'dataFactory',
function ($scope, dataFactory) {
$scope.status
$scope.servers;
getServers();
function getServers() {
dataFactory.getServers()
.success(function (srv) {
$scope.servers = srv;
})
.error(function (error) {
$scope.status = 'Unable to load server data: ' + error.message;
});
}
}]);
Using ng-repeat in both the table head and table body should work.
<html ng-app='app' ng-controller='DscController'>
<head>
</head>
<body>
<div class="container">
<div class="jumbotron">
<table ng-if="servers" class="table table-bordered">
<thead>
<tr>
<th ng-repeat="head in servers.result[0].meta">{{head}}</th>
</tr>
</thead>
<tbody ng-repeat="r in servers.result">
<tr ng-repeat="row in r.rows">
<td ng-repeat="item in row">{{item}}</td>
</tr>
</tbody>
</table>
<p ng-if="!servers">{{status}}</p>
</div>
</div>
</body>
</html>
I've included the necessary repeats to handle the data exactly as it was presented. I assume the meta will be the same for all results.

Resources