get data from json array to Table angularJS - javascript

I have this json data:
{
status: "SUCCESS",
data: [
{
FirstName: "Student ",
LastName: "1",
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Id: 2,
ObjectState: 0
}
}
]
}
I have tried like this,in my controller and in the view:
app.js:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
var i;
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
for(i=0;i<data.length;i++){
$scope.paged = data[i].data; // response data
console.log($scope.paged+" $scope.paged");
}
$scope.currentPageStores= $scope.paged;
console.log($scope.currentPageStores+" values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Students.html:
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tr>
</tbody>
</table>
and this what I get in console:
values
success
I didn't get any data in console or in the Table :(
any help please
thanks
Update:
I try with this:
$rootScope.usersData = angular.toJson(data.data);
console.log($rootScope.usersData+" my data");
I get all the data that I want to display in console
Update2:
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
console.log(JSON.stringify(data)+"myData");
for(i=0;i<data.length;i++){
$scope.paged = data.data[i]; // response data
console.log($scope.paged+" $scope.paged");
}
.....
}
I get this in console:
{"status":"SUCCESS","data":[{"FirstName":"Student ","LastName":"1","Id":1,"ObjectState":0},{"FirstName":"Student ","LastName":"2","Id":2,"ObjectState":0}]}myData

No need to loop around in controller. Try the following:
Your Controller:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
$scope.currentPageStores= data.data;
console.log($scope.currentPageStores+ " values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Your student.html
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores track by $index" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tbody>
</table>
Here is a PLUNKER example of how you access when the data comes in an array as yours : http://plnkr.co/edit/Q9ewbH7XevsOQG0Yzv6B?p=preview

You can't print a object on console with another string.
use
console.log(JSON.stringify($scope.currentPageStores)+" values");
or
console.log($scope.currentPageStores);

Related

For loop issue in angualrjs and javascript

Hi i have an array in this 7 object are present and 3 invertors, means
accoding to the data im getting columns correctly but columns are
wrong, how many invertors have been created on the particular date
those many should come. if that present day 2 inverotrs are 2 columns
should come dynamically... which i am not getting can any one help me out.
var url = "http://52.9.55.95:91/api/ExcelDetails/ExcelExportForLog?Sid=1&FromDt=2017-02-21&ToDt=2017-02-22"
console.log(url);
var tabledata=[];
$scope.inventorarray=[];
http({
method: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: url
}).
success(function (data, status, headers, config) {
// $scope.loaded = true;
$scope.data = data;
$timeout(function () { $scope.loaded = true; }, 500);
//console.log("reporting to data received : success");
console.log(data);
for(var i=0;i<data.length;i++){
var tdata={
"heading":"InvCount: "+i,
"Date":data[i].TimeofReading.substring(0,10)
}
tabledata.push(tdata);
}
$scope.tablearray=tabledata;
console.log($scope.tablearray)
for(var i=0;i<data.length;i++){
var Lastreadingkey=data[i].Lastreading;
var Readingbykey=data[i].Readingby;
debugger
var tdata={
"Lastreading":Lastreadingkey,
"Readingby":Readingbykey
}
$scope.inventorarray.push(tdata);
}
console.log($scope.inventorarray)
}).
error(function (data, status, headers, config) {
//$scope.loaded = false;
swal({ title: "Warning!", text: "Something went wrong!", type: "warning", confirmButtonText: "OK" });
$timeout(function () { $scope.loaded = true; }, 500);
//console.log("reporting to data received : failure");
//console.log(data);
});
var url = "http://52.9.55.95:91/api/ExcelDetails/ExcelExportForLog?Sid=1&FromDt=2017-02-21&ToDt=2017-02-22"
console.log(url);
var tabledata=[];
$scope.inventorarray=[];
http({
method: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: url
}).
success(function (data, status, headers, config) {
$scope.data = data;
$timeout(function () { $scope.loaded = true; }, 500);
for(var i=0;i<data.length;i++){
var tdata={
"heading":"InvCount: "+i,
"Date":data[i].TimeofReading.substring(0,10)
}
tabledata.push(tdata);
}
$scope.tablearray=tabledata;
console.log($scope.tablearray)
for(var i=0;i<data.length;i++){
var Lastreadingkey=data[i].Lastreading;
var Readingbykey=data[i].Readingby;
debugger
var tdata={
"Lastreading":Lastreadingkey,
"Readingby":Readingbykey
}
$scope.inventorarray.push(tdata);
}
console.log($scope.inventorarray)
}).
error(function (data, status, headers, config) {
//$scope.loaded = false;
swal({ title: "Warning!", text: "Something went wrong!", type: "warning", confirmButtonText: "OK" });
$timeout(function () { $scope.loaded = true; }, 500);
});
$scope.tableToExcel=(function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
}]);
myhtml page
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th></th>
<th ng-repeat="data in tablearray" colspan="2">{{data.heading}}</th>
</tr>
</thead>
<tr>
<td>Date</td>
<td ng-repeat="data in inventorarray"> <p ng-if="$index%2==0"> Last Reading</p><p ng-if="$index%2>0"> Read By</p> </td>
</tr>
<tr ng-repeat="data in tablearray">
<td> {{data.Date}}</td>
<td ng-repeat="data in inventorarray"> <p ng-if="$index%2==0"> {{data.Lastreading}}</p><p ng-if="$index%2>0">{{data.Readingby}}</p> </td>
</tr>
</table>
can any let know the loop please im stuc here from past 2days.. i
need to be finish today please make fiddle and send me

Post data to server angular $http post

[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(data) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name":$scope.name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log('data success');
});
HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.date}}</td>
<td><button ng-click="postfunction(names)">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try function postfunction(), but it didn't post to server, in my console everything is ok, but name.name don't post to server.
The $scope.name you're trying to send isn't defined anywhere.
You'll want to change names here into name:
...
<td><button ng-click="postfunction(name)">POST</button></td>
...
and in your postfunction ditch $scope.name altogether and do this instead (also use .then instead of .success, .success is deprecated):
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name": name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data){
console.log('data success');
});
}
Are you sure that the API takes content type application/x-www-form-urlencoded? It is best to use the Angular default of application/json? If you must urlencode the data, use the $httpParamSerializerJQLike Service.
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
-- AngularJS Param Serializer API Reference

$http not defined when posting to server

Here's my json:
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function() {
$http({
method: 'POST',
url: 'serverUrl',
data: name.name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
My HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction()">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try $http.post in postfunction(), but I get "$http is not defined" in console.
You forgot to inject $http into your controller
app.controller('FirstCtrl', function($scope, service, $http) {
^
You have to inject $http service in your controller 'FirstCtrl' as below:
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serverUrl',
data: name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
Also additionally along with passing the argument to the post function, you have to pass the 'name' in the HTML as below, this is because, in your controller, 'name' is never defined.
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction(name.name)">POST</button></td>
</tr>
</tbody>

AngularJS $http get doesn't work but $.ajax does

I am new to AngularJS. I cannot seem to get $http to work. I have the following factory:
app.factory('employeeFactory', function ($http) {
var factory = {};
// get data form controller
var employees = [];
var Url = "../../../Employee/GetEmployees";
// this does not work ----------------------------
$http.get(Url, { params: { term: 'Step' }}).
success(function (response, status, headers, config) {
employees = response.data
}).
error(function (response, status, headers, config) {
alert(error);
});
// this works using JQuery ajax ----------------------------
$.ajax({
url: Url,
data: { term: 'Step' },
dataType: "json",
type: "GET",
error: function (request, status, error) {
alert(error);
},
success: function (response) {
$.each(response.data, function (i, obj) {
employees.push({ EmployeeName: obj.EmployeeName, EmployeeNumber: obj.EmployeeNumber });
});
}
});
factory.getEmployees = function () {
return employees
};
return factory;
});
And the following controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
init();
function init() {
$scope.employees = employeeFactory.getEmployees();
}
});
The ajax call in the factory works but the $https doesn't (both are in the factory, I just comment out one or the other while testing). I looked in google chrome dev tools and both calls return data in the same format, but the $http data is not being bound to the html:
<div class="container">
<h4>This is view 1</h4>
Type a name to filter: <input type="text" data-ng-model="employeeSearch" />
<ul>
<li data-ng-repeat="employee in employees | filter:employeeSearch | orderBy:'EmployeeName'">{{ employee.EmployeeName }} - {{ employee.EmployeeNumber }}</li>
</ul>
</div>
Here is the format the factory returns for both calls:
{data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
data: [{EmployeeNumber:123456, EmployeeName:Johnson,Bob},…]
0: {EmployeeNumber:123456, EmployeeName:Johnson,Bob}
EmployeeName: "Johnson,Bob"
EmployeeNumber: "123456"
I don't understand why, when both calls return the data to the view in the same format, the binding is not occurring with the $http method. Any help is appreciated
The jQuery ajax works because you push to the returned reference.
In the angular ajax success handler you overwrite the variable, but the return value is still the empty reference.
So to get the angular $http function working, you should do the following in your success handler:
angular.forEach(response.data, function(value) {
employees.push(value);
});
use this code:
service:
app.factory('employeeFactory', function ($http) {
var employees = [];
var Url = "../../../Employee/GetEmployees";
var factory = {
getEmp:function(){
return $http.get(Url, { params: { term: 'Step' }})
}
}
return factory;
});
controller:
app.controller('EmployeeController', function ($scope, employeeFactory) {
$scope.employees = [];
function init() {
employeeFactory.getEmp().then(function(data){
$scope.employees=data;
})
.catch(function(err){
console.log(err);
})
}
init();
});

how to automatically update data on the view in angular.js

i have show the phone data on the view site :
<table class="table table-stripes data-tables" ng-controller="GetData as mydata">
<tr>
<th align="center"><div align="center">S.#</div></th>
<th align="center"><div align="center">Name</div></th>
<th align="center"><div align="center">Number</div></th>
<th align="center"><div align="center">Edit</div></th>
<th align="center"><div align="center">Delete</div></th>
</tr>
<tr ng-repeat="alldata in mydata.row | filter:search ">
<td>{{alldata.id}}</td>
<td>{{alldata.name}}</td>
<td>{{alldata.numbers}}</td>
<td><button class="btn btn-primary">Edit</button></td>
<td><button class="btn btn-danger">Delete</button></td>
</tr>
</table>
and when user add new one i want to refresh the controller. how can i do this
//getdata controller
myApp.controller("GetData",['$http','$log','$location','$timeout', function($http,$log,$location,$timeout){
var ata = this;
ata.row = [ ] ;
$http({method: 'POST', url: 'process/getdata.php'})
.success(function(data) {
// this callback will be called asynchronously
// when the response is available
// $log.log(data);
ata.row=data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}]);
// add new item controller
myApp.controller("addNumber",['$http','$log','transformRequestAsFormPost','$location', function($http,$log,transformRequestAsFormPost,$location){
this.add = function(name,number){
var mydata='name='+name+'&number'+number;
$http({
method: 'POST',
url: 'process/addnumbers.php',
data:{
name: name,
number: number
}}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$log.log(data);
if(data == 'true')
{
}
else
{
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
what should i do with getdata controller
what should i do when user add new record
try to refresh the page in add number controller. that might be help.
myApp.controller("addNumber",['$http','$log','transformRequestAsFormPost','$location','$route', function($http,$log,transformRequestAsFormPost,$location,$route){
this.add = function(name,number){
var mydata='name='+name+'&number'+number;
$http({
method: 'POST',
url: 'process/addnumbers.php',
data:{
name: name,
number: number
}}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$log.log(data);
if(data == 'true')
{
$route.reload();
// get the current path
$location.path();
// change the path
$location.path('/Dashboard');
}
else
{
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
}]);
inject $route service in the controller

Categories

Resources