Issue in populating ajax data into table via ng-repeat - javascript

I am trying to populate a table on receiving JSON data on an Ajax get from Mongo DB.
I am able to see the received data in alert. But my table is not populated.
I am clicking the retrive button to get the data.
JS code:
$scope.retrive = function()
{
$scope.people =[];
$.ajax({
url : "https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=veTqID_gkb74tG-yL4MGcS1p2RRBP1Pf",
type : "GET",
dataType: "json",
success: function(data) {
$scope.people = JSON.stringify(data);
alert($scope.people);
//alert("status = "+data.status+"descripttion"+data.description);
//console.log(data);
//document.getElementById("n1").innerHTML = data[0].name;
//alert(JSON.stringify(data));
tableCreate(data);
//alert(data[0].name);
//var json = JSON.parse(data);
//alert(json.name);
}
});
};
}]);
HTML code:
<div>
<table>
<tr>
<th>ITEM</th>
<th>DESCRIPTION</th>
<th>QUANTITY</th>
<th>LOCATION</th>
<th>CATEGORY</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.Item}}</td>
<td>{{person.Description}}</td>
<td>{{person.Quantity}}</td>
<td>{{person.Location}}</td>
<td>{{person.Category}}</td>
</tr>
</table>
</div>
Here is the Plunker Link :
http://plnkr.co/edit/OKzTApbW7ii8R0EMrOyx?p=preview

Try is like this:
Note (Just a tip ): Putting API keys within stack overflow questions is not a good idea. Keep the API key private as any body can use your key and you could blocked out from the service due to unauthorised usage.
var myApp = angular.module('myApp', []);
myApp.controller('projectController', function($scope, $http){
$scope.userDetails = [];
$scope.test = function(){
console.log("getting user projects, please wait ......");
// Simple GET request example (passing data) :
$http.get("https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=YOUR-API-KEY", {
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("");
$scope.userDetails = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Heres a working Plunker:
http://plnkr.co/edit/xoFuBa695E7O1g6gTcm4?p=preview
UPDATED Plunker
http://plnkr.co/edit/7E4PKbnqBDwsVptIaJ1Q?p=preview

Related

how to view the data when searching without submitting | angularjs

in order to make the search process faster, my client requested to view the data when just the search box is filled without even submitting, my code works fine at submitting, what should i change with my code so i can get the desired result. this is my first project with angular js, i am very new to this technology. Many thanks in advance.
HTML View:
<input id="searchInput" type="text"/> // search box where
// the function below "getSearchResults()" will get results when submitting
<input ng-click="getSearchResults()" type="submit"/>
<table>
<thead>
<tr>
<th>NOM</th>
<th>TELEPHONE</th>
<th>LOCATION</th>
<th>CODE</th>
</tr>
</thead>
<tbody >
//view the data
<tr ng-repeat="c in clients">
<td>{{c.firstname}} {{c.lastname}}</td>
<td>{{c.telephone}}</td>
<td>{{c.location}}</td>
<td>{{c.code}}</td>
</tr>
</tbody>
</table>
Js source:
var app = angular.module('DMDGroup', []);
$scope.clients;
app.controller('ClientALL', function($scope, $http) {
/* the function put all results in the scope variable (client) in a json
form and the results viewed with the ng-repeat on the tr tag*/
$scope.getSearchResults=function(){
var searchKeyWord=$("#searchInput").val();
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord":searchKeyWord};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
}
i want the to directly change the data in the table depends on the search results, i'll attach an image of my view
put ng-change instead of ng-click
<input ng-change="getSearchResults(searchVal)" ng-model="searchVal" class="searchClientBtn" type="submit"/>
in controller function
$scope.getSearchResults=function(value){
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord": value};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}

How to refresh the table records automatically in angularjs after an event occurs

I am working on a Web App , using Laravel as backend API and AngularJS for frontend. I have successfully fetched the data from Laravel API and displayed it via AngularJS ng-repeat . Now i want a delete button for each record which is displayed in the table.When a user click that delete button it should delete the clicked record.I did the following try which is working perfectly.But the problem occurs when i click delete button it deletes record from database but it is not refreshing the records list , instead of refreshing it just shows the headers titles of table and nothing else. When i manually refresh it from browser then it displays back the records list.I want to load the list automatically after the record is deleted.
Summary: On delete i want to load / refresh the list automatically which is not happening right now.
Student Controller:
public function destroy($id)
{
$student = Student::find(Input::get('id'));
if($student){
$student->delete();
return Response::json(['destroy'=>true]);
}
}
app.js
var myApp = angular.module('myApp', ['mainCtrl', 'myAppService']);
myappservice.js
angular.module('myAppService', [])
.factory('Result', function($http) {
return {
get : function() {
return $http.get('api/result');
},
show : function(id) {
return $http.get('api/result/' + id);
},
save : function(resultData) {
return $http({
method: 'POST',
url: 'api/result',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(resultData)
});
},
destroy : function(id) {
return $http.delete('api/result/' + id,{params: {id}});
}
}
});
MainCtrl.js
angular.module('mainCtrl', [])
.controller('mainController', function($scope, $http, Result) {
// object to hold all the data for the new comment form
$scope.resultData = {};
// loading variable to show the spinning loading icon
$scope.loading = true;
// get all the comments first and bind it to the $scope.comments object
Result.get()
.success(function(data) {
$scope.students = data;
$scope.loading = false;
});
// function to handle submitting the form
$scope.submitResult = function() {
$scope.loading = true;
// save the comment. pass in comment data from the form
Result.save($scope.resultData)
.success(function(data) {
$scope.resultData = {};
// if successful, we'll need to refresh the comment list
Result.get()
.success(function(getData) {
$scope.students = getData;
$scope.loading = false;
});
})
.error(function(data) {
console.log(data);
});
};
// function to handle deleting a comment
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Result.get()
.success(function(getData) {
$scope.students = getData;
$scope.loading = false;
});
});
};
});
View
<table class="table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
<th>Percentage</th>
<th>Delete</th>
</tr>
</thead>
<tbody ng-hide="loading" ng-repeat="student in students | filter:searchText">
<tr>
<td>#{{ student.rollno }}</td>
<td>#{{ student.name }}</td>
<td>#{{ student.fname }}</td>
<td>#{{ student.obtainedmarks }}</td>
<td>#{{ student.totalmarks }}</td>
<td>#{{ student.percentage }}</td>
<td>
Delete</p>
</td>
</tr>
</tbody>
</table>
Console Error: DELETE
http://localhost/ngresulty/public/api/result/30?id=30 500 (Internal
Server Error)
My guess would be that the Result.get() call is not returning the right data. You may want to check that endpoint.
Instead of making another call though, since you know that on deletion there was a success event, you could just change the scope then and not call your backend again, ie:
// function to handle deleting a comment
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// do something with data if you want to
$scope.students.splice(id, 1);
});
};
if you get 500 server error Result.destroy() calls error function. Its not success
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Result.get()
.success(function(getData) {
$scope.students = getData;
$scope.loading = false;
});
})
.error(function(data) {
// its not successful but i want call Result.get() anyway
Result.get()
.success(function(getData) {
$scope.students = getData;
$scope.loading = false;
});
}));
};
Try to put
$scope.$apply();
statement at the end of event

Displaying the contents of ng-controller after calling AJAX with the "as" function

What I'm trying to show the contents of ng-repeat after calling AJAX (i.e. $http)
<table ng-controller="TableController as tc">
<tr>
<th>Date</th>
<!-- other headers are here -->
</tr>
<tr ng-repeat="order in tc.orders" >
<td ng-bind="order.id"></td> //It doesn't appear
<td>#{{ order.id }}</td> //It doesn't appear as well. I use Laravel, so I need to put #
</tr>
</table>
Here is the relevant script part
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
this.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
this.orders = response.data;
console.log("Inside; "+this.orders.length);
});
});
From console.log("Inside; "+this.orders.length), I can see that the expected data was assigned to this.orders array. However, as the title of this post suggests, the array is not displayed with ng-repeat="order in tc.orders".
I followed this question, but following this did not solve this issue. Now I suspect that the cause lies in the as statement, which I have to use for this occasion.
As I don't see many information resources about the as online, I'd appreciate if you'd give any advice.
you should use your instance inside promise resolved function
to assign to the right instance (controller instance) :
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
instance.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
instance.orders = response.data;
console.log("Inside; "+ instance.orders.length);
});
});
its usual to name this instance : vm refers to View Model
Example:
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var vm= this;
vm.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
vm.orders = response.data;
console.log("Inside; "+vm.orders.length);
});
});

ng-repeat not reflecting when the source variable gets modified

I have the following angularJs code. When my source data changes, my ng-repeat does not update my view. I looked at other posts and added $scope.$apply(); , $scope.$digest(); at the end of my ajax success callback, but it did not help. The idea is that the page will have an empty table in the begining and after the ajax call onReady() it will populate the rows with data. Could someone point me at what I am missing here or a better way to achieve the same
JS:
(function() {
var app = angular.module("jmeter-module", []);
app.controller('JmeterTableController', ['$scope', function($scope){
$scope.data = [];
$(document).ready(function(){
var url = "jmeterTableData.html";
fetchTableData(url, 10, 25);
});
function fetchTableData(url, minAge, maxAge){
$.ajax({
type: "GET",
url: url,
data: { minAge : minAge,
maxAge : maxAge },
datatype: "json",
success: function(data){
/*If I try to print data here, I see the values rightly getting returned*/
$scope.data = data;
},
error: function(e){
console.log(e);
}
});
}
}]);
})();
JSP:
<div id="buildGroupsParentDivId" ng-controller="JmeterTableController as row">
.
.
.
<tbody id="jmeter-table-content" >
<tr ng-repeat="val in row.data">
<td><img title="History" src="/images/history.png" width="20" height="20"></td>
<td><input type="checkbox" value="save"></td>
<td>{{val.firstName}}</td>
<td>{{val.lastResult}}</td>
</tr>
</tbody>
the problem is with the execution of $.ajax outside of the scope of Angular's digest cycle. You could get this working with $scope.$apply, but since you're already using Angular it's better to use the AngularJS xhr helper methods:
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

How to know which data has been changed in an array?

I'm trying to get which data has been changed in array. my use case is First time all data fetch from ajax and show within row and fetch new data using $http every 5 second. I need to know that if the new data is same as old one. If yes then which value has changed so I've to update that background to some color..
What I've already tried
var app = angular.module('app', []);
app.controller('listingController', function($scope, $http, $timeout){
$scope.listings;
setInterval(function(){
$http.get('_includes/ajax.php?req=get').
success(function(data, status, headers, config) {
$scope.listings = data;
console.log(data);
}).
error(function(data, status, headers, config) {
// log error
});
}, 5000);
});
app.controller('RentalDateController', function($scope, $log){
console.log($scope.listings);
$scope.$watch('listings.Third_Column', function (Third_Column, oldvalue) {
//$log.info(Third_Column, $scope.listings.First_Column);
console.log('being watched oldValue:', oldvalue, 'newValue:', Third_Column);
}, true);
});
My html is
<body ng-app="app">
<div ng-controller="listingController">
<table>
<tr>
<th>Testing</th>
<th>Pripse</th>
</tr>
<tr ng-repeat="row in listings" ng-controller="RentalDateController">
<input type="text" ng-model="row.Third_Column">
<input type="text" ng-model="row.First_Column">
<th>{{row.Third_Column}}</th>
<th>{{row.First_Column}}</th>
</tr>
</table>
</div>
</body>
I think I need to use $watch but it's not working.
You have the angular two-way data binding so it should automatically update your ng-repeat when the model changes.
I suggest the following
1) Remove RentalDate controller first.
2) Use $timeout, and on success of http use this
$scope.$apply(function(){
$scope.listing = data;
});
If that doesn't still automatically update, put the array in an object.
$scope.data = {}
$scope.data.listings = putArrayHere();
This will work because of this. Read up. :D
https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance
Try doing this:
var app = angular.module('app', []);
app.controller('listingController', function($scope, $http, $timeout){
$scope.listings;
var previousListing = [];
var newData;
setInterval(function(){
$http.get('_includes/ajax.php?req=get').
success(function(data, status, headers, config) {
$scope.listings = data;
console.log(data);
}).
error(function(data, status, headers, config) {
// log error
});
if( previousListing.length == $scope.listings.length )
{
console.log('No new data available.');
}
else
{
// length of the arrays are different, hence new data must be available
console.log('New data available!');
newData = $scope.listings.splice( 0, ($scope.listings.length - previousListing.length) ); // returns new data in the form of an array
console.log(newData);
previousListing = $scope.listings; // reset previous data variable
}
}, 5000);
});

Categories