Angular JSON Response - angularjs

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.

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");
});
}
});

how to disable\enable button on checked check box in datatable AngularJS?

I'm show the user list using datatable angularjs. I want to disable\enable button on checked check box.i have the one button this button enable on etlish one checked on check box in the table other wise disable this button.any one how can do that.
this is my button :
<button type="button" class="btn btn-success">Send</button>
This is my controller.js
app.controller("userscontroller", [
"$scope",
"$http",
"DTOptionsBuilder",
"DTColumnBuilder",
"userservice",
"$compile",
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder, userservic, $compile) {
$scope.dtColumns = [
DTColumnBuilder.newColumn("fullName", "Full Name").withOption('name','firstname'),
DTColumnBuilder.newColumn("username", "Name").withOption('name','username'),
DTColumnBuilder.newColumn("email", "Email").withOption('name', 'email'),
DTColumnBuilder.newColumn(null).withTitle('Action').notSortable().renderWith(function (data, type, full, meta) {
return '<button class="btn btn-primary" ng-click="delete(' + data.id + ');"><i class="fa fa-eye"></i>' + '</button>';
}),
DTColumnBuilder.newColumn(null).withTitle('Action').notSortable().renderWith(function (data, type, full, meta) {
return '<input type="checkbox" name="check" id="'+ data.userid +'">';
})
]
$scope.dtOptions = userservice.GetAllUser(DTOptionsBuilder)
.withOption('processing', true)
.withOption('serverSide', true)
.withPaginationType('full_numbers')
.withDisplayLength(50)
.withOption('aaSorting', [3, 'desc']);
function createdRow(row, data, dataIndex) {
$compile(angular.element(row).contents())($scope);
}
}
]);
this is my code so any one idea how can do that please let me know.
Here is a very simple example on how to enable/disable a delete button when checking/unchecking an entry.
angular.module('app', []);
angular.module('app').controller('ExampleController', ['$scope', '$q', function($scope, $q) {
$scope.users = [{
"id": "1",
"fullName": "Marty McFly",
"username": "mmfly",
"email": "mmfly#bttf.com"
},
{
"id": "2",
"fullName": "Robert Plant",
"username": "rplant",
"email": "rplant#ledzep.com"
}
];
$scope.deleteUser = function(id) {
console.log("Deleting user with id", id);
}
}]);
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ExampleController">
<table border="1" cellpadding="8">
<tr>
<th></th>
<th>Fullname</th>
<th>Username</th>
<th>Email</th>
<th>Actions</th>
</tr>
<tr ng-repeat="user in users">
<td><input type="checkbox" ng-model="user._selected"></td>
<td>{{user.fullName}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td><button ng-disabled="!user._selected" ng-click="deleteUser(user.id)">Delete</button></td>
</tr>
</table>
</div>
</body>
</html>

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

ng-repeat parsing every character of json

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);
})

show 2 array through ng-repeat error

i am trying to make a table from 2 arrays in AngularJS one array contains Employees name and other array contain Services Name and rest of the cells contain check boxes but when i do i got error Error: [ngRepeat:dupes]
here is my AngularJS code
var model = angular.module('wizard', ['ngRoute'])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider.when("/m5", {
controller: "model5Controller",
templateUrl: "/templates/m5.html"
});
$routeProvider.otherwise({ redirectTo: '/' });
}]);
var model5Controller = ["$scope", "$http", "$window", function ($scope,
$http, $window) {
$scope.PBA = [];
$scope.SOB = [];
$http.get('/Test/GetPBA').
then(
function (result) {
//success
$scope.PBA = result.data;
},
function () {
//error
});
$http.get('/Test/GetSOB').
then(
function (result) {
//success
$scope.SOB = result.data;
},
function () {
//error
});
$scope.save = function () {
//to be written
};
}];
GetPBA/GetSOB returns JSON type Array of List
both contain properties like Id, Name
here is my html
<div>
<form ng-submit="save()">
<table border="1">
<tr>
<td><strong>Services</strong></td>
<td ng-repeat="e in PBA">{{e.Name}}</td>
</td>
<tr ng-repeat="i in SOB">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>
</table>
</form>
Try this
<tr ng-repeat="i in SOB track by $index">
<td>{{i.Name}}</td>
<td ng-repeat="e in PBA track by $index">
<input type="checkbox" name="{{e.Id}}" />
</td>
</tr>

Resources